Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Improve template page SEO and render READMEs (#1622)

Allen Zhouc50c2d654cb9
diff --git a/apps/docs/.gitignore b/apps/docs/.gitignore
index 23084d1e5..18763406f 100644
--- a/apps/docs/.gitignore
+++ b/apps/docs/.gitignore
@@ -2,3 +2,6 @@
# generated by `shadcn build` (pnpm registry:build) from registry.json + registry/
/public/r/
+
+# generated from template repositories before docs dev/build
+/.template-data/
diff --git a/apps/docs/app/[lang]/agents.md/route.ts b/apps/docs/app/[lang]/agents.md/route.ts
index 1d5c14f55..b2ff79289 100644
--- a/apps/docs/app/[lang]/agents.md/route.ts
+++ b/apps/docs/app/[lang]/agents.md/route.ts
@@ -1,7 +1,7 @@
import { createAgentsRoute } from "@vercel/geistdocs/routes/agents";
import { transformAgentsMarkdown } from "@/lib/geistdocs/agents-transform";
import { config } from "@/lib/geistdocs/config";
-import { templateEntries } from "@/lib/templates/data";
+import { templateManifest } from "@/lib/templates/manifest";
// Static, CDN-cacheable. /agents.md surfaces the agent instructions from the
// Geistdocs config and points agents at the machine-readable documentation
@@ -14,7 +14,7 @@ const agentsRoute = createAgentsRoute({
transform: (markdown, { request }) =>
transformAgentsMarkdown(markdown, {
origin: request.nextUrl.origin,
- templates: templateEntries,
+ templates: templateManifest,
}),
});
diff --git a/apps/docs/app/[lang]/sitemap.md/route.ts b/apps/docs/app/[lang]/sitemap.md/route.ts
index d80340b17..e941a4c03 100644
--- a/apps/docs/app/[lang]/sitemap.md/route.ts
+++ b/apps/docs/app/[lang]/sitemap.md/route.ts
@@ -4,7 +4,7 @@ import { resolveDocsPageTitle } from "@/lib/geistdocs/page-title";
import { transformSitemapMarkdown } from "@/lib/geistdocs/sitemap-transform";
import { geistdocsSource } from "@/lib/geistdocs/source";
import { integrationSource } from "@/lib/integrations/source";
-import { templateEntries } from "@/lib/templates/data";
+import { templateManifest } from "@/lib/templates/manifest";
export const revalidate = false;
export const dynamic = "error";
@@ -20,7 +20,7 @@ const sitemapRoute = createSitemapMarkdownRoute({
pageUrl: url,
tree: geistdocsSource.source.getPageTree(lang),
}) ?? title,
- templates: templateEntries,
+ templates: templateManifest,
}),
});
diff --git a/apps/docs/app/[lang]/templates/[slug]/file-viewer.tsx b/apps/docs/app/[lang]/templates/[slug]/file-viewer.tsx
index e98c8cf98..d252a2a7b 100644
--- a/apps/docs/app/[lang]/templates/[slug]/file-viewer.tsx
+++ b/apps/docs/app/[lang]/templates/[slug]/file-viewer.tsx
@@ -52,6 +52,9 @@ const categoryOrder = [
"lib",
];
+const treeRowClassName =
+ "min-h-8 w-full touch-manipulation rounded-sm px-2 text-left font-mono text-[13px] leading-none outline-none transition-colors focus-visible:ring-2 focus-visible:ring-blue-700 motion-reduce:transition-none md:min-h-7";
+
interface FileEntry {
file: HighlightedTemplateFile;
label: string;
@@ -151,7 +154,7 @@ export const FileViewer = ({ files }: FileViewerProps) => {
aria-label="Template files"
className="border-gray-alpha-400 border-b p-3 md:border-r md:border-b-0"
>
- <p className="px-2 pb-2 text-gray-800 text-label-13-mono">agent/</p>
+ <p className="px-2 pb-0.5 text-gray-800 text-label-13-mono md:pb-2">agent/</p>
<ul className="space-y-0.5">
{tree.map((node) => {
const Icon = node.style.icon;
@@ -162,7 +165,8 @@ export const FileViewer = ({ files }: FileViewerProps) => {
<button
aria-pressed={isSelected}
className={cn(
- "flex min-h-11 w-full touch-manipulation items-center gap-2 rounded-sm px-2 text-left font-mono text-[13px] leading-none outline-none transition-colors focus-visible:ring-2 focus-visible:ring-blue-700 motion-reduce:transition-none md:min-h-7",
+ treeRowClassName,
+ "flex items-center gap-2",
isSelected
? "font-medium text-gray-1000"
: "text-gray-900 hover:bg-gray-alpha-100 hover:text-gray-1000",
@@ -186,7 +190,8 @@ export const FileViewer = ({ files }: FileViewerProps) => {
<button
aria-expanded={isOpen}
className={cn(
- "flex min-h-11 w-full touch-manipulation items-center gap-2 rounded-sm px-2 text-left font-mono text-[13px] leading-none outline-none transition-colors focus-visible:ring-2 focus-visible:ring-blue-700 motion-reduce:transition-none md:min-h-7",
+ treeRowClassName,
+ "flex items-center gap-2",
containsSelected
? "text-gray-1000"
: "text-gray-900 hover:bg-gray-alpha-100 hover:text-gray-1000",
@@ -213,7 +218,8 @@ export const FileViewer = ({ files }: FileViewerProps) => {
<button
aria-pressed={isSelected}
className={cn(
- "min-h-11 w-full touch-manipulation truncate rounded-sm px-2 text-left font-mono text-[13px] leading-none outline-none transition-colors focus-visible:ring-2 focus-visible:ring-blue-700 motion-reduce:transition-none md:min-h-7",
+ treeRowClassName,
+ "truncate",
isSelected
? "font-medium text-gray-1000"
: "text-gray-800 hover:bg-gray-alpha-100 hover:text-gray-1000",
diff --git a/apps/docs/app/[lang]/templates/[slug]/opengraph-image.tsx b/apps/docs/app/[lang]/templates/[slug]/opengraph-image.tsx
index 905eecd2b..cd657adb2 100644
--- a/apps/docs/app/[lang]/templates/[slug]/opengraph-image.tsx
+++ b/apps/docs/app/[lang]/templates/[slug]/opengraph-image.tsx
@@ -1,5 +1,5 @@
import { notFound } from "next/navigation";
-import { getTemplateEntry } from "@/lib/templates/data";
+import { templateManifest } from "@/lib/templates/manifest";
import { createTemplateOgImage } from "@/lib/templates/og-image";
export const size = {
@@ -14,7 +14,7 @@ const TemplateOpenGraphImage = async ({
params: Promise<{ lang: string; slug: string }>;
}) => {
const { slug } = await params;
- const template = getTemplateEntry(slug);
+ const template = templateManifest.find((entry) => entry.slug === slug);
if (!template) {
notFound();
diff --git a/apps/docs/app/[lang]/templates/[slug]/page.tsx b/apps/docs/app/[lang]/templates/[slug]/page.tsx
index 5520b84fd..49702f9b7 100644
--- a/apps/docs/app/[lang]/templates/[slug]/page.tsx
+++ b/apps/docs/app/[lang]/templates/[slug]/page.tsx
@@ -9,16 +9,14 @@ import type { ComponentProps } from "react";
import { translations } from "@/geistdocs";
import { canonicalAlternates, templatePath } from "@/lib/geistdocs/canonical";
import { pageTitleMetadata } from "@/lib/geistdocs/metadata-title";
-import {
- getTemplateEntry,
- templateEntries,
- type TemplateEntry,
- type TemplateFile,
-} from "@/lib/templates/data";
+import { getTemplateEntry, type TemplateEntry, type TemplateFile } from "@/lib/templates/data";
+import { templateManifest } from "@/lib/templates/manifest";
+import { getSiteOrigin } from "@/lib/geistdocs/url";
import { cn } from "@/lib/utils";
import { integrationIcons } from "../integration-icons";
import { FileViewer, type HighlightedTemplateFile } from "./file-viewer";
import { TemplateActions } from "./template-actions";
+import { TemplateReadme } from "./template-readme";
interface PageParams {
lang: string;
@@ -27,7 +25,7 @@ interface PageParams {
export const generateStaticParams = (): PageParams[] =>
Object.keys(translations).flatMap((lang) =>
- templateEntries.map((entry) => ({ lang, slug: entry.slug })),
+ templateManifest.map((entry) => ({ lang, slug: entry.slug })),
);
export const dynamicParams = false;
@@ -38,79 +36,128 @@ export const generateMetadata = async ({
params: Promise<PageParams>;
}): Promise<Metadata> => {
const { slug } = await params;
- const entry = getTemplateEntry(slug);
- if (!entry) return { title: "Template not found" };
+ const entry = templateManifest.find((template) => template.slug === slug);
+ if (!entry) {
+ return { title: "Template not found" };
+ }
- const titleMetadata = pageTitleMetadata(`${entry.title} template - eve`);
+ const canonicalPath = templatePath(entry.slug);
+ const titleMetadata = pageTitleMetadata(entry.title);
return {
...titleMetadata,
description: entry.description,
- alternates: canonicalAlternates(templatePath(entry.slug)),
- openGraph: titleMetadata.openGraph,
- twitter: { ...titleMetadata.twitter, card: "summary_large_image" },
+ alternates: canonicalAlternates(canonicalPath),
+ openGraph: {
+ ...titleMetadata.openGraph,
+ description: entry.description,
+ type: "website",
+ url: canonicalPath,
+ },
+ twitter: {
+ ...titleMetadata.twitter,
+ card: "summary_large_image",
+ description: entry.description,
+ },
};
};
const TemplateDetailPage = async ({ params }: { params: Promise<PageParams> }) => {
const { slug } = await params;
- const entry = getTemplateEntry(slug);
+ const entry = await getTemplateEntry(slug);
if (!entry) {
notFound();
}
const highlightedFiles = await Promise.all(entry.files.map(highlightFile));
+ const canonicalUrl = new URL(`/templates/${entry.slug}`, getSiteOrigin()).toString();
+ const structuredData = createStructuredData(entry, canonicalUrl);
return (
- <main className="mx-auto max-w-[1080px] px-4 pt-10 pb-32 sm:px-6 sm:pt-12">
- <Link
- className="inline-flex min-h-8 items-center gap-1.5 rounded-sm text-gray-900 text-label-14 no-underline outline-none transition-colors hover:text-gray-1000 focus-visible:ring-2 focus-visible:ring-blue-700 focus-visible:ring-offset-2 focus-visible:ring-offset-background-100 motion-reduce:transition-none"
- href="/templates"
- >
- <ArrowLeftIcon aria-hidden="true" className="size-3.5" />
- Templates
- </Link>
+ <>
+ <script
+ dangerouslySetInnerHTML={{
+ __html: JSON.stringify(structuredData).replace(/</g, "\\u003c"),
+ }}
+ id={`template-structured-data-${entry.slug}`}
+ type="application/ld+json"
+ />
+ <main className="mx-auto max-w-[1080px] px-4 pt-10 pb-32 sm:px-6 sm:pt-12">
+ <Link
+ className="inline-flex min-h-8 items-center gap-1.5 rounded-sm text-gray-900 text-label-14 no-underline outline-none transition-colors hover:text-gray-1000 focus-visible:ring-2 focus-visible:ring-blue-700 focus-visible:ring-offset-2 focus-visible:ring-offset-background-100 motion-reduce:transition-none"
+ href="/templates"
+ >
+ <ArrowLeftIcon aria-hidden="true" className="size-3.5" />
+ Templates
+ </Link>
- <header className="mt-8 grid gap-4 lg:grid-cols-2 lg:items-start lg:gap-8">
- <div className="min-w-0">
- <h1 className="m-0 text-heading-40 text-gray-1000 sm:text-heading-48">{entry.title}</h1>
- <div className="hidden lg:block">
- <IntegrationList entry={entry} />
- </div>
- </div>
- <div className="min-w-0">
- <p className="max-w-[520px] text-copy-16 text-gray-900">{entry.description}</p>
- <div className="mt-6">
- <TemplateActions
- setupPrompt={entry.setupPrompt}
- sourceHref={entry.sourceHref}
- template={entry.slug}
- />
+ <header className="mt-8 grid gap-4 lg:grid-cols-2 lg:items-start lg:gap-8">
+ <div className="min-w-0">
+ <h1 className="m-0 text-heading-40 text-gray-1000 sm:text-heading-48">{entry.title}</h1>
+ <div className="hidden lg:block">
+ <IntegrationList entry={entry} />
+ </div>
</div>
- <div className="pt-3 lg:hidden">
- <IntegrationList entry={entry} />
+ <div className="min-w-0">
+ <p className="max-w-[520px] text-copy-16 text-gray-900">{entry.description}</p>
+ <div className="mt-6">
+ <TemplateActions
+ setupPrompt={entry.setupPrompt}
+ sourceHref={entry.sourceHref}
+ template={entry.slug}
+ />
+ </div>
+ <div className="pt-3 lg:hidden">
+ <IntegrationList entry={entry} />
+ </div>
</div>
- </div>
- <dl className="flex flex-wrap gap-x-10 gap-y-4 border-gray-alpha-400 border-t pt-6 lg:col-span-2">
- <OverviewItem label="Model" value={entry.model} />
- <OverviewItem label="Authored files" value={String(entry.files.length)} />
- </dl>
- </header>
+ </header>
- <section className="mt-14">
- <div>
- <h2 className="text-heading-24 text-gray-1000">Filesystem</h2>
- <p className="mt-2 text-copy-14 text-gray-900">
- Browse the authored files at revision{" "}
- <code className="text-copy-13-mono">{entry.sourceRevision.slice(0, 7)}</code>.
- </p>
- </div>
- <div className="mt-4">
+ <section aria-label="Filesystem" className="mt-8">
<FileViewer files={highlightedFiles} />
- </div>
- </section>
- </main>
+ </section>
+
+ <section aria-label="README" className="mt-16">
+ <div className="max-w-[760px]">
+ <TemplateReadme readme={entry.readme} sourceRevisionHref={entry.sourceRevisionHref} />
+ </div>
+ </section>
+ </main>
+ </>
);
};
+const createStructuredData = (entry: TemplateEntry, canonicalUrl: string) => ({
+ "@context": "https://schema.org",
+ "@graph": [
+ {
+ "@type": "BreadcrumbList",
+ itemListElement: [
+ {
+ "@type": "ListItem",
+ item: new URL("/templates", getSiteOrigin()).toString(),
+ name: "Templates",
+ position: 1,
+ },
+ {
+ "@type": "ListItem",
+ item: canonicalUrl,
+ name: entry.title,
+ position: 2,
+ },
+ ],
+ },
+ {
+ "@type": "SoftwareSourceCode",
+ codeRepository: entry.sourceRevisionHref,
+ description: entry.description,
+ keywords: ["eve", ...entry.integrations],
+ name: entry.title,
+ programmingLanguage: ["TypeScript", "Markdown"],
+ runtimePlatform: "eve",
+ url: canonicalUrl,
+ },
+ ],
+});
+
const highlightFile = async (file: TemplateFile): Promise<HighlightedTemplateFile> => ({
code: await highlight(file.contents, {
lang: file.language,
@@ -153,11 +200,4 @@ const IntegrationList = ({ entry }: { entry: TemplateEntry }) => (
</ul>
);
-const OverviewItem = ({ label, value }: { label: string; value: string }) => (
- <div className="min-w-0">
- <dt className="text-gray-800 text-label-12">{label}</dt>
- <dd className="mt-1 break-all text-copy-13-mono text-gray-1000">{value}</dd>
- </div>
-);
-
export default TemplateDetailPage;
diff --git a/apps/docs/app/[lang]/templates/[slug]/template-actions.tsx b/apps/docs/app/[lang]/templates/[slug]/template-actions.tsx
index 385f735e5..ffd148f38 100644
--- a/apps/docs/app/[lang]/templates/[slug]/template-actions.tsx
+++ b/apps/docs/app/[lang]/templates/[slug]/template-actions.tsx
@@ -39,34 +39,29 @@ export const TemplateActions = ({ setupPrompt, sourceHref, template }: TemplateA
return (
<div className="grid gap-2 sm:flex sm:flex-wrap">
<Button
- className="font-medium text-background-100! text-label-14"
+ className="w-full justify-center font-medium text-background-100! text-label-14 sm:w-52"
onClick={copyPrompt}
type="button"
>
- <span className="grid">
- <span
- aria-hidden="true"
- className="invisible col-start-1 row-start-1 flex items-center gap-2"
- >
- <CheckIcon aria-hidden="true" className="size-4" />
- Copied. Paste in your agent.
- </span>
- <span className="col-start-1 row-start-1 flex items-center justify-self-center gap-2">
- {copied ? (
- <>
- <CheckIcon aria-hidden="true" className="size-4" />
- Copied. Paste in your agent.
- </>
- ) : (
- <>
- <CopyIcon aria-hidden="true" className="size-4" />
- Setup with one prompt
- </>
- )}
- </span>
+ <span className="flex items-center gap-2">
+ {copied ? (
+ <>
+ <CheckIcon aria-hidden="true" className="size-4" />
+ Paste into your agent
+ </>
+ ) : (
+ <>
+ <CopyIcon aria-hidden="true" className="size-4" />
+ Setup with one prompt
+ </>
+ )}
</span>
</Button>
- <Button asChild className="font-medium text-label-14" variant="outline">
+ <Button
+ asChild
+ className="w-full justify-center font-medium text-label-14 sm:w-auto"
+ variant="outline"
+ >
<a
href={sourceHref}
onClick={() => track(analyticsEvents.templateSourceOpened, { template })}
diff --git a/apps/docs/app/[lang]/templates/[slug]/template-readme.tsx b/apps/docs/app/[lang]/templates/[slug]/template-readme.tsx
new file mode 100644
index 000000000..ac946ee8c
--- /dev/null
+++ b/apps/docs/app/[lang]/templates/[slug]/template-readme.tsx
@@ -0,0 +1,71 @@
+"use client";
+
+import { createCodePlugin } from "@streamdown/code";
+import { geistShikiTheme } from "@vercel/geistdocs/shiki-theme";
+import { useMemo } from "react";
+import { type Components, Streamdown } from "streamdown";
+import { resolveReadmeHref } from "@/lib/templates/readme-links";
+
+interface TemplateReadmeProps {
+ readme: string;
+ sourceRevisionHref: string;
+}
+
+export const TemplateReadme = ({ readme, sourceRevisionHref }: TemplateReadmeProps) => {
+ const codePlugin = useMemo(
+ () => createCodePlugin({ themes: [geistShikiTheme, geistShikiTheme] }),
+ [],
+ );
+ const components = useMemo<Partial<Components>>(
+ () => ({
+ a: ({ href, ...props }) => {
+ const resolvedHref = resolveReadmeHref(href, sourceRevisionHref);
+ if (!resolvedHref) {
+ return <span>{props.children}</span>;
+ }
+ const external = !resolvedHref.startsWith("#");
+ return (
+ <a
+ {...props}
+ href={resolvedHref}
+ rel={external ? "noopener noreferrer" : undefined}
+ target={external ? "_blank" : undefined}
+ />
+ );
+ },
+ h1: ({ children }) => (
+ <h2 className="mt-10 mb-4 text-heading-32 text-gray-1000 first:mt-0">{children}</h2>
+ ),
+ h2: ({ children }) => (
+ <h3 className="mt-8 mb-3 text-heading-24 text-gray-1000">{children}</h3>
+ ),
+ h3: ({ children }) => (
+ <h4 className="mt-6 mb-3 text-heading-20 text-gray-1000">{children}</h4>
+ ),
+ h4: ({ children }) => (
+ <h5 className="mt-6 mb-3 text-heading-16 text-gray-1000">{children}</h5>
+ ),
+ }),
+ [sourceRevisionHref],
+ );
+
+ return (
+ <Streamdown
+ allowElement={(element) => {
+ for (const child of element.children) {
+ if (child.type !== "text") continue;
+ if (/\[(?:Image )?blocked(?::[^\]]*)?\]/i.test(child.value)) return false;
+ }
+ return true;
+ }}
+ className="min-w-0 text-gray-900 [&_a]:font-medium [&_a]:text-gray-1000 [&_a]:underline [&_a]:underline-offset-4 [&_blockquote]:border-gray-alpha-400 [&_blockquote]:border-l [&_blockquote]:pl-4 [&_code]:text-gray-1000 [&_li]:my-1 [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:pl-5 [&_p]:my-3 [&_table]:my-5 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:pl-5"
+ components={components}
+ disallowedElements={["img"]}
+ mode="static"
+ plugins={{ code: codePlugin }}
+ shikiTheme={[geistShikiTheme, geistShikiTheme]}
+ >
+ {readme}
+ </Streamdown>
+ );
+};
diff --git a/apps/docs/app/[lang]/templates/[slug]/twitter-image.tsx b/apps/docs/app/[lang]/templates/[slug]/twitter-image.tsx
index e86d7505d..02c2f20d8 100644
--- a/apps/docs/app/[lang]/templates/[slug]/twitter-image.tsx
+++ b/apps/docs/app/[lang]/templates/[slug]/twitter-image.tsx
@@ -1,5 +1,5 @@
import { notFound } from "next/navigation";
-import { getTemplateEntry } from "@/lib/templates/data";
+import { templateManifest } from "@/lib/templates/manifest";
import { createTemplateOgImage } from "@/lib/templates/og-image";
export const size = {
@@ -14,7 +14,7 @@ const TemplateTwitterImage = async ({
params: Promise<{ lang: string; slug: string }>;
}) => {
const { slug } = await params;
- const template = getTemplateEntry(slug);
+ const template = templateManifest.find((entry) => entry.slug === slug);
if (!template) {
notFound();
diff --git a/apps/docs/app/[lang]/templates/page.tsx b/apps/docs/app/[lang]/templates/page.tsx
index 6b25c18be..0366e1f07 100644
--- a/apps/docs/app/[lang]/templates/page.tsx
+++ b/apps/docs/app/[lang]/templates/page.tsx
@@ -3,7 +3,7 @@ import { canonicalAlternates, canonicalRoutes } from "@/lib/geistdocs/canonical"
import { pageTitleMetadata } from "@/lib/geistdocs/metadata-title";
import { staticOgImage } from "@/lib/geistdocs/og";
import { translations } from "@/geistdocs";
-import { templateEntries } from "@/lib/templates/data";
+import { templateManifest } from "@/lib/templates/manifest";
import { TemplateGallery } from "./template-gallery";
const title = "Templates";
@@ -25,13 +25,23 @@ export const metadata: Metadata = {
export const generateStaticParams = () => Object.keys(translations).map((lang) => ({ lang }));
+const templateSummaries = templateManifest.map(
+ ({ category, description: templateDescription, integrations, slug, title: templateTitle }) => ({
+ category,
+ description: templateDescription,
+ integrations,
+ slug,
+ title: templateTitle,
+ }),
+);
+
const TemplatesPage = () => (
<main className="mx-auto max-w-[1080px] px-4 pb-32 sm:px-6">
<header className="pt-12 pb-8 sm:pt-16 sm:pb-10">
<h1 className="text-heading-32 text-gray-1000 sm:text-heading-40">{title}</h1>
<p className="mt-3 max-w-[460px] text-copy-16 text-gray-900">{description}</p>
</header>
- <TemplateGallery entries={templateEntries} />
+ <TemplateGallery entries={templateSummaries} />
</main>
);
diff --git a/apps/docs/app/[lang]/templates/template-gallery.tsx b/apps/docs/app/[lang]/templates/template-gallery.tsx
index a01b3fcfc..af09d26e9 100644
--- a/apps/docs/app/[lang]/templates/template-gallery.tsx
+++ b/apps/docs/app/[lang]/templates/template-gallery.tsx
@@ -20,7 +20,11 @@ import {
normalizeSearchQuery,
} from "@/lib/analytics/events";
import { templatePath } from "@/lib/geistdocs/canonical";
-import type { TemplateCategory, TemplateEntry, TemplateIntegration } from "@/lib/templates/data";
+import type {
+ TemplateCategory,
+ TemplateIntegration,
+ TemplateManifestEntry,
+} from "@/lib/templates/manifest";
import { integrationIcons } from "./integration-icons";
const ALL = "all" as const;
@@ -28,9 +32,14 @@ const ALL = "all" as const;
type FilterValue<T extends string> = typeof ALL | T;
interface TemplateGalleryProps {
- entries: TemplateEntry[];
+ entries: TemplateGalleryEntry[];
}
+type TemplateGalleryEntry = Pick<
+ TemplateManifestEntry,
+ "category" | "description" | "integrations" | "slug" | "title"
+>;
+
interface FilterSelectProps<T extends string> {
allLabel: string;
label: string;
@@ -77,7 +86,13 @@ const FilterOption = ({ label, value }: { label: string; value: string }) => (
</DropdownMenuRadioItem>
);
-const TemplateCard = ({ entry, onSelect }: { entry: TemplateEntry; onSelect: () => void }) => (
+const TemplateCard = ({
+ entry,
+ onSelect,
+}: {
+ entry: TemplateGalleryEntry;
+ onSelect: () => void;
+}) => (
<li>
<Link
className="flex min-h-36 flex-col rounded-lg border border-gray-alpha-400 bg-background-100 p-4 no-underline outline-none transition-colors hover:border-gray-alpha-500 hover:bg-gray-alpha-100 focus-visible:border-gray-alpha-600 focus-visible:ring-2 focus-visible:ring-blue-700 focus-visible:ring-offset-2 focus-visible:ring-offset-background-100 motion-reduce:transition-none"
diff --git a/apps/docs/app/sitemap.ts b/apps/docs/app/sitemap.ts
index 62045b3b3..f631ee932 100644
--- a/apps/docs/app/sitemap.ts
+++ b/apps/docs/app/sitemap.ts
@@ -12,7 +12,7 @@ import { createCanonicalSitemap, type SitemapSourceEntry } from "@/lib/geistdocs
import { geistdocsSource } from "@/lib/geistdocs/source";
import { getSiteOrigin } from "@/lib/geistdocs/url";
import { integrations } from "@/lib/integrations/data";
-import { templateEntries } from "@/lib/templates/data";
+import { templateManifest } from "@/lib/templates/manifest";
const getLastModified = (data: unknown): Date | undefined => {
if (!data || typeof data !== "object" || !("lastModified" in data)) return;
@@ -43,7 +43,7 @@ export default function sitemap(): MetadataRoute.Sitemap {
{ pathname: canonicalRoutes.integrations },
...integrations.map(({ slug }) => ({ pathname: integrationPath(slug) })),
{ pathname: canonicalRoutes.templates },
- ...templateEntries.map(({ slug }) => ({ pathname: templatePath(slug) })),
+ ...templateManifest.map(({ slug }) => ({ pathname: templatePath(slug) })),
],
});
}
diff --git a/apps/docs/lib/geistdocs/agents-transform.test.ts b/apps/docs/lib/geistdocs/agents-transform.test.ts
index 440457e47..30a00b8d0 100644
--- a/apps/docs/lib/geistdocs/agents-transform.test.ts
+++ b/apps/docs/lib/geistdocs/agents-transform.test.ts
@@ -38,11 +38,13 @@ describe("transformAgentsMarkdown", () => {
it("adds concise canonical template discovery entries", () => {
const output = transformAgentsMarkdown(input, {
origin: "https://eve.dev",
- templates: [{ slug: "chat", title: "Chat", description: "A persisted chat agent." }],
+ templates: [
+ { slug: "chat", title: "Chat agent template", description: "A persisted chat agent." },
+ ],
});
expect(output).toContain(
- "- [Chat template](https://eve.dev/templates/chat): A persisted chat agent.",
+ "- [Chat agent template](https://eve.dev/templates/chat): A persisted chat agent.",
);
});
diff --git a/apps/docs/lib/geistdocs/agents-transform.ts b/apps/docs/lib/geistdocs/agents-transform.ts
index 51966b0af..7f8bf0259 100644
--- a/apps/docs/lib/geistdocs/agents-transform.ts
+++ b/apps/docs/lib/geistdocs/agents-transform.ts
@@ -50,7 +50,7 @@ export const transformAgentsMarkdown = (
const templateLines = templates.map(
(template) =>
- `- [${escapeMarkdown(`${template.title} template`)}](${origin}/templates/${template.slug}): ${template.description}`,
+ `- [${escapeMarkdown(template.title)}](${origin}/templates/${template.slug}): ${template.description}`,
);
return `${corrected.trimEnd()}\n\n## Templates\n\n${templateLines.join("\n")}\n`;
diff --git a/apps/docs/lib/geistdocs/discovery.test.ts b/apps/docs/lib/geistdocs/discovery.test.ts
index 0dd516e26..eb9a2eb47 100644
--- a/apps/docs/lib/geistdocs/discovery.test.ts
+++ b/apps/docs/lib/geistdocs/discovery.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { integrations } from "../integrations/data";
-import { templateEntries } from "../templates/data";
+import { templateManifest } from "../templates/manifest";
import { integrationPath, templatePath } from "./canonical";
describe("authoritative hub discovery paths", () => {
@@ -12,9 +12,9 @@ describe("authoritative hub discovery paths", () => {
});
it("gives every template a unique canonical child link", () => {
- const paths = templateEntries.map(({ slug }) => templatePath(slug));
+ const paths = templateManifest.map(({ slug }) => templatePath(slug));
- expect(new Set(paths).size).toBe(templateEntries.length);
+ expect(new Set(paths).size).toBe(templateManifest.length);
expect(paths.every((path) => /^\/templates\/[^/?#]+$/.test(path))).toBe(true);
});
});
diff --git a/apps/docs/lib/geistdocs/sitemap-transform.test.ts b/apps/docs/lib/geistdocs/sitemap-transform.test.ts
index a8fcb9783..c1c0183ed 100644
--- a/apps/docs/lib/geistdocs/sitemap-transform.test.ts
+++ b/apps/docs/lib/geistdocs/sitemap-transform.test.ts
@@ -5,7 +5,9 @@ const transform = (markdown: string) =>
transformSitemapMarkdown(markdown, {
resolveTitle: (title, url) =>
title === "Overview" && url === "/docs/channels/overview" ? "Channels" : title,
- templates: [{ slug: "chat", title: "Chat", description: "A persisted chat agent." }],
+ templates: [
+ { slug: "chat", title: "Chat agent template", description: "A persisted chat agent." },
+ ],
});
describe("transformSitemapMarkdown", () => {
@@ -33,7 +35,7 @@ describe("transformSitemapMarkdown", () => {
const output = transform("# Documentation Sitemap");
expect(output).toContain(
- "- [Chat template](/templates/chat) | Type: Example | Summary: A persisted chat agent. | Canonical: /templates/chat",
+ "- [Chat agent template](/templates/chat) | Type: Example | Summary: A persisted chat agent. | Canonical: /templates/chat",
);
});
});
diff --git a/apps/docs/lib/geistdocs/sitemap-transform.ts b/apps/docs/lib/geistdocs/sitemap-transform.ts
index 21b17b8bf..2a30dc6e1 100644
--- a/apps/docs/lib/geistdocs/sitemap-transform.ts
+++ b/apps/docs/lib/geistdocs/sitemap-transform.ts
@@ -48,7 +48,7 @@ export const transformSitemapMarkdown = (
const templateLines = templates.map(
(template) =>
- `- [${template.title} template](/templates/${template.slug}) | Type: Example | Summary: ${template.description} | Canonical: /templates/${template.slug}`,
+ `- [${template.title}](/templates/${template.slug}) | Type: Example | Summary: ${template.description} | Canonical: /templates/${template.slug}`,
);
return `${transformed.trimEnd()}\n\n## Templates\n\n${templateLines.join("\n")}\n`;
diff --git a/apps/docs/lib/templates/compose.test.ts b/apps/docs/lib/templates/compose.test.ts
index a76cedf0e..945a64836 100644
--- a/apps/docs/lib/templates/compose.test.ts
+++ b/apps/docs/lib/templates/compose.test.ts
@@ -1,12 +1,11 @@
import { describe, expect, it } from "vitest";
import { composeTemplateEntries, type GeneratedTemplatesInput } from "./compose";
-import generatedTemplates from "./generated/templates.json";
-import { templateManifest, type TemplateManifestEntry } from "./manifest";
+import type { TemplateManifestEntry } from "./manifest";
const manifestEntry: TemplateManifestEntry = {
slug: "example",
- title: "Example",
+ title: "Example agent template",
description: "An example template.",
category: "Example",
integrations: ["HTTP API"],
@@ -21,6 +20,7 @@ const manifestEntry: TemplateManifestEntry = {
const generated: GeneratedTemplatesInput = {
templates: {
example: {
+ readme: "# Example\n\nAn example template.\n",
sourceRevision: "0123456789abcdef0123456789abcdef01234567",
files: [
{
@@ -38,8 +38,12 @@ describe("composeTemplateEntries", () => {
const [entry] = composeTemplateEntries([manifestEntry], generated);
expect(entry.slug).toBe("example");
- expect(entry.title).toBe("Example");
+ expect(entry.title).toBe("Example agent template");
expect(entry.sourceRevision).toBe("0123456789abcdef0123456789abcdef01234567");
+ expect(entry.sourceRevisionHref).toBe(
+ "https://github.com/vercel-labs/example/tree/0123456789abcdef0123456789abcdef01234567",
+ );
+ expect(entry.readme).toBe(generated.templates.example.readme);
expect(entry.files).toEqual(generated.templates.example.files);
expect(entry).not.toHaveProperty("github");
});
@@ -63,6 +67,7 @@ describe("composeTemplateEntries", () => {
const bad: GeneratedTemplatesInput = {
templates: {
example: {
+ readme: "# Example\n",
sourceRevision: "0123456789abcdef0123456789abcdef01234567",
files: [{ contents: "{}", language: "json", relativePath: "agent/agent.ts" }],
},
@@ -71,23 +76,13 @@ describe("composeTemplateEntries", () => {
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,
+ it("throws when generated README content is empty", () => {
+ const emptyReadme = {
+ templates: { example: { ...generated.templates.example, readme: "" } },
+ };
+ expect(() => composeTemplateEntries([manifestEntry], emptyReadme)).toThrow(
+ /Generated README is empty/,
);
-
- 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.ts
index bf10aacdb..5dd8d1ba5 100644
--- a/apps/docs/lib/templates/compose.ts
+++ b/apps/docs/lib/templates/compose.ts
@@ -17,19 +17,22 @@ export interface TemplateEntry {
files: TemplateFile[];
integrations: TemplateIntegration[];
model: string;
+ readme: string;
slug: string;
source: TemplateSource;
sourceHref: string;
sourceRevision: string;
+ sourceRevisionHref: string;
setupPrompt: string;
title: string;
}
-/** Shape of `generated/templates.json`, before language narrowing. */
+/** Shape of the repository snapshot produced before a docs build. */
export interface GeneratedTemplatesInput {
templates: Record<
string,
{
+ readme: string;
sourceRevision: string;
files: { contents: string; language: string; relativePath: string }[];
}
@@ -78,8 +81,24 @@ export const composeTemplateEntries = (
return { contents: file.contents, language: file.language, relativePath: file.relativePath };
});
+ if (!data.readme.trim()) {
+ throw new Error(`Generated README is empty for template "${entry.slug}" — ${SYNC_HINT}`);
+ }
+
const { github: _github, files: _paths, ...curated } = entry;
- return { ...curated, sourceRevision: data.sourceRevision, files };
+ const sourceRevisionHref = [
+ `https://github.com/${entry.github.owner}/${entry.github.repo}/tree/${data.sourceRevision}`,
+ entry.github.pathPrefix,
+ ]
+ .filter(Boolean)
+ .join("/");
+ return {
+ ...curated,
+ files,
+ readme: data.readme,
+ sourceRevision: data.sourceRevision,
+ sourceRevisionHref,
+ };
});
if (orphanedSlugs.size > 0) {
diff --git a/apps/docs/lib/templates/data.ts b/apps/docs/lib/templates/data.ts
index ad2271b43..870bd18ac 100644
--- a/apps/docs/lib/templates/data.ts
+++ b/apps/docs/lib/templates/data.ts
@@ -1,18 +1,34 @@
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { cache } from "react";
import {
composeTemplateEntries,
type GeneratedTemplatesInput,
type TemplateEntry,
} from "./compose";
-import generatedTemplates from "./generated/templates.json";
import { templateManifest } from "./manifest";
export type { TemplateEntry, TemplateFile } from "./compose";
export type { TemplateCategory, TemplateIntegration, TemplateSource } from "./manifest";
-export const templateEntries: TemplateEntry[] = composeTemplateEntries(
- templateManifest,
- generatedTemplates as GeneratedTemplatesInput,
-);
+const generatedTemplatesPath = join(process.cwd(), ".template-data/templates.json");
+
+export const getTemplateEntries = cache(async (): Promise<TemplateEntry[]> => {
+ let contents: string;
+ try {
+ contents = await readFile(generatedTemplatesPath, "utf8");
+ } catch (error) {
+ throw new Error(
+ `Template build data is missing at ${generatedTemplatesPath}. ` +
+ "Run `pnpm --filter eve-docs templates:sync` before rendering template pages.",
+ { cause: error },
+ );
+ }
-export const getTemplateEntry = (slug: string): TemplateEntry | undefined =>
- templateEntries.find((entry) => entry.slug === slug);
+ return composeTemplateEntries(templateManifest, JSON.parse(contents) as GeneratedTemplatesInput);
+});
+
+export const getTemplateEntry = cache(
+ async (slug: string): Promise<TemplateEntry | undefined> =>
+ (await getTemplateEntries()).find((entry) => entry.slug === slug),
+);
diff --git a/apps/docs/lib/templates/generated/templates.json b/apps/docs/lib/templates/generated/templates.json
deleted file mode 100644
index 9dbee70a9..000000000
--- a/apps/docs/lib/templates/generated/templates.json
+++ /dev/null
@@ -1,395 +0,0 @@
-{
- "$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"
- }
- ]
- },
- "kody-eve-template": {
- "sourceRevision": "8427e3c7e88a6a449dd7c79c601619ac37cf18e1",
- "files": [
- {
- "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Root agent runtime configuration.\n *\n * @remarks\n * Sets the model and the session budget for Kody, the GitHub maintainer agent; the rest of the\n * agent's surface (channels, connections, tools, skills, subagents) is discovered from the\n * filesystem under `agent/`. Conversation history is compacted once it reaches 75% of the context\n * window, and the per-session output token limit caps runaway sessions. `@vercel/connect` is\n * externalized from the build as a temporary workaround until eve handles transitive Connect\n * imports from `@github-tools/sdk` without configuration.\n */\nexport default defineAgent({\n build: { externalDependencies: [\"@vercel/connect\"] },\n compaction: { thresholdPercent: 0.75 },\n limits: {\n maxOutputTokensPerSession: 20_000,\n },\n model: \"anthropic/claude-fable-5\",\n});\n",
- "language": "typescript",
- "relativePath": "agent/agent.ts"
- },
- {
- "contents": "import { connectGitHubCredentials } from \"@vercel/connect/eve\";\nimport {\n defaultGitHubAuth,\n type GitHubComment,\n githubChannel,\n} from \"eve/channels/github\";\n\nconst BOT_NAME = \"Kody\";\n\n/**\n * Matches an `@Kody` mention on a word boundary, the same pattern the\n * channel's built-in comment gate uses. Kept in sync with {@link BOT_NAME}.\n */\nconst MENTION_PATTERN = /@kody(?=$|[^A-Za-z0-9_-])/iu;\n\n/**\n * Commenter roles allowed to start a session by mentioning the agent.\n *\n * @remarks\n * GitHub's `author_association` on the comment payload. Anything outside this\n * set (CONTRIBUTOR, FIRST_TIME_CONTRIBUTOR, NONE, MANNEQUIN) is a user the\n * repo hasn't trusted with write access, so their mentions are acknowledged\n * without dispatching.\n */\nconst TRUSTED_ASSOCIATIONS = new Set([\"COLLABORATOR\", \"MEMBER\", \"OWNER\"]);\n\n/**\n * Replicates the channel's built-in ignore rules: eve's own marker comments,\n * bot authors, and the agent's own `kody[bot]` login.\n */\nconst isIgnoredComment = (comment: GitHubComment): boolean => {\n if (comment.body.includes(\"<!-- eve:github:\")) {\n return true;\n }\n const { author } = comment;\n if (author === undefined) {\n return false;\n }\n return (\n author.type === \"Bot\" ||\n author.login.toLowerCase() === `${BOT_NAME.toLowerCase()}[bot]`\n );\n};\n\nconst isTrustedCommenter = (comment: GitHubComment): boolean => {\n const association = comment.raw.author_association;\n return (\n typeof association === \"string\" && TRUSTED_ASSOCIATIONS.has(association)\n );\n};\n\n/**\n * Task injected into the session dispatched when a pull request opens. The\n * PR's metadata and changed-file patches are already in the session's context\n * when this runs; the repo itself is checked out into the sandbox.\n */\nconst PR_SUMMARY_TASK = [\n \"A pull request was just opened. Post one comment that helps reviewers get oriented.\",\n \"Open with a short paragraph saying what the PR does and why, grounded in its title, description, and diff. Never guess at intent the diff doesn't show.\",\n \"Then add a markdown table breaking down the changed files: the file path, the kind of change (added, modified, removed, renamed), and what changed in one short phrase. For a very large PR, list the files that carry the substance and roll the rest into a final count row.\",\n \"Close with one line pointing reviewers at where to start. This comment is a summary, not a review: don't approve, request changes, or ask the author for anything.\",\n].join(\"\\n\\n\");\n\n/**\n * GitHub channel: @mentions on issues and pull requests, answered in-thread as\n * \"Kody\", plus a summary comment on every newly opened pull request.\n *\n * @remarks\n * - Credentials are brokered by Vercel Connect. The connector UID comes from\n * the `GITHUB_CONNECTOR` environment variable (falling back to\n * `github/kody-agent`); tokens are resolved per call and never exposed to\n * the model.\n * - `onComment` replaces the built-in mention gate to add an authorization\n * check: it keeps the default mention and ignore rules, then dispatches\n * only when the commenter's `author_association` marks them as trusted with\n * the repo (owner, member, or collaborator). Mentions from anyone else are\n * acknowledged without a session, so arbitrary accounts on a public repo\n * cannot drive the agent's write tools.\n * - `onPullRequest` dispatches only on the `opened` action and skips PRs\n * opened by bots (Dependabot and similar), so automated PRs don't each get\n * a summary comment. It is deliberately not gated by `author_association`:\n * summarizing outside contributors' PRs is the point, and the injected task\n * is scoped to posting a single summary comment. All other PR actions are\n * acknowledged without dispatching.\n */\nexport default githubChannel({\n botName: BOT_NAME,\n credentials: connectGitHubCredentials(\n process.env.GITHUB_CONNECTOR ?? \"github/kody-agent\"\n ),\n onComment: (ctx, comment) =>\n !isIgnoredComment(comment) &&\n MENTION_PATTERN.test(comment.body) &&\n isTrustedCommenter(comment)\n ? { auth: defaultGitHubAuth(ctx) }\n : null,\n onPullRequest: (ctx, pullRequest) =>\n pullRequest.action === \"opened\" && ctx.sender.type !== \"Bot\"\n ? { auth: defaultGitHubAuth(ctx), context: [PR_SUMMARY_TASK] }\n : null,\n});\n",
- "language": "typescript",
- "relativePath": "agent/channels/github.ts"
- },
- {
- "contents": "import { connectLinearCredentials } from \"@vercel/connect/eve\";\nimport { defaultLinearAuth, linearChannel } from \"eve/channels/linear\";\n\n/**\n * Linear channel: Agent Sessions in, Agent Activities out, via Vercel Connect.\n *\n * @remarks\n * Credentials are brokered by Vercel Connect, which supplies the app token and\n * verifies inbound webhooks by their Vercel OIDC signature. The\n * `onAgentSession` hook keeps the default created/prompted dispatch and adds\n * the requester's name and email as session context when Linear provides\n * them, so requests like \"email me a summary\" go to the right address without\n * asking.\n */\nexport default linearChannel({\n credentials: connectLinearCredentials(\n process.env.LINEAR_CONNECTOR ?? \"linear/kody-agent\"\n ),\n onAgentSession: (_ctx, event) => {\n if (event.action !== \"created\" && event.action !== \"prompted\") {\n return null;\n }\n const requester = event.agentActivity?.user ?? event.agentSession.creator;\n const context: string[] = [];\n if (requester?.email) {\n context.push(\n `The requesting user is ${requester.displayName ?? requester.name ?? \"unknown\"} (${requester.email}). When they ask for something by email, send it to that address unless they name another.`\n );\n }\n return { auth: defaultLinearAuth(event), context };\n },\n});\n",
- "language": "typescript",
- "relativePath": "agent/channels/linear.ts"
- },
- {
- "contents": "import { createRedisState } from \"@chat-adapter/state-redis\";\nimport { createResendAdapter } from \"@resend/chat-sdk-adapter\";\nimport type { Message, Thread } from \"chat\";\nimport { chatSdkChannel } from \"eve/channels/chat-sdk\";\nimport { requireEnv } from \"../lib/constants.js\";\n\n/**\n * Email channel built on the Chat SDK's Resend adapter: inbound mail in, agent replies out.\n *\n * @remarks\n * Thread state lives in Redis (`@chat-adapter/state-redis`, configured by `REDIS_URL`). The\n * adapter authenticates with `RESEND_API_KEY`, plus `RESEND_WEBHOOK_SECRET` for inbound\n * webhooks; both are read from env. Streaming is off because email has no incremental\n * rendering: each reply is delivered as one message. The sender address comes from\n * `RESEND_FROM_ADDRESS`, the same variable the system prompt and digest task use, so channel\n * replies and agent-sent mail share one identity. The destructured `bot` and `send` wire the\n * handlers below, which forward new mentions and follow-ups on subscribed threads into the\n * agent.\n */\nexport const { bot, channel, send } = chatSdkChannel({\n adapters: {\n resend: createResendAdapter({\n fromAddress: requireEnv(\"RESEND_FROM_ADDRESS\", \"[email protected]\"),\n fromName: process.env.RESEND_FROM_NAME ?? \"Kody\",\n }),\n },\n state: createRedisState(),\n streaming: false,\n userName: \"Kody Agent\",\n});\n\nbot.onNewMention(async (thread: Thread, message: Message) => {\n await thread.subscribe();\n await send(message.text, { thread });\n});\n\nbot.onSubscribedMessage(async (thread: Thread, message: Message) => {\n await send(message.text, { thread });\n});\n\nexport default channel;\n",
- "language": "typescript",
- "relativePath": "agent/channels/resend.ts"
- },
- {
- "contents": "import { defineMcpClientConnection } from \"eve/connections\";\nimport { linearAuth } from \"../lib/constants.js\";\n\n/**\n * Linear MCP connection for creating and cross-referencing issues.\n *\n * @remarks\n * Points at Linear's hosted MCP server and authenticates with the shared app-scoped\n * `linearAuth` from `agent/lib/constants.ts`, so this connection and any tool calling the\n * Linear API directly share one installation and one set of scopes. Tokens are resolved per\n * call and never exposed to the model.\n */\nexport default defineMcpClientConnection({\n auth: linearAuth,\n description: \"Linear workspace: issues, projects, cycles, and comments.\",\n url: \"https://mcp.linear.app/mcp\",\n});\n",
- "language": "typescript",
- "relativePath": "agent/connections/linear.ts"
- },
- {
- "contents": "import { defineMcpClientConnection } from \"eve/connections\";\nimport { requireEnv } from \"../lib/constants.js\";\n\n/**\n * Resend MCP connection for outbound email (digest sends, summaries, confirmations).\n *\n * @remarks\n * Auth is a static bearer token from `RESEND_API_KEY`, the same key the Resend\n * chat-sdk adapter uses. A static token works in every session, including the\n * weekly digest's cron run, which has no signed-in user: user-scoped Vercel\n * Connect cannot resolve there (`principal_required`) and the Resend connector\n * does not issue app-scoped tokens. The key is resolved per call and never\n * exposed to the model.\n */\nexport default defineMcpClientConnection({\n auth: {\n getToken: () =>\n Promise.resolve({ token: requireEnv(\"RESEND_API_KEY\", \"re_123\") }),\n },\n description:\n \"Resend MCP: Manage emails, templates, contacts, broadcasts, automations, and more end-to-end.\",\n url: \"https://mcp.resend.com/mcp\",\n});\n",
- "language": "typescript",
- "relativePath": "agent/connections/resend.ts"
- },
- {
- "contents": "import { defineInstructions } from \"eve/instructions\";\nimport { requireEnv } from \"./lib/constants.js\";\n\nconst fromAddress = requireEnv(\"RESEND_FROM_ADDRESS\", \"[email protected]\");\nconst fromName = process.env.RESEND_FROM_NAME ?? \"Kody\";\n\n/**\n * Kody's full system prompt, resolved once at build time.\n *\n * @remarks\n * The sending-email section injects `RESEND_FROM_ADDRESS` and\n * `RESEND_FROM_NAME` when the app is built (`eve build` / `eve dev` compile),\n * not per session, so the agent never has to ask who an email should be sent\n * from. The address is required; the name falls back to \"Kody\".\n */\nexport default defineInstructions({\n markdown: `# Identity\n\nYou are Kody, a GitHub maintainer agent for the team. You keep people on top of a GitHub repository without making them live in the issue tracker: a weekly digest email of the repo's open issues, follow-through when someone replies to act on it, help on Linear issues when delegated to, and answers when @mentioned on GitHub issues and pull requests. You do the tracker work; they stay in their inbox and their tools.\n\n# How you write\n\nWrite like a person. Never use em dashes; use a comma, a colon, or a new sentence instead. Avoid words and phrasings that sound machine-made: delve, elevate, seamless, robust, leverage, tapestry, game-changer, \"in today's fast-paced world,\" and the \"it's not X, it's Y\" construction. Don't bold words for emphasis, don't pad, and don't hype ordinary things. This applies to your messages, your emails, and everything you post to GitHub or Linear. Plain, specific, and warm.\n\n# How you work\n\n## 1. Start with the user\n\n- Call \\`get_user_preferences\\` at the start of a task and apply what it returns: standing notes like a preferred email address, how they like the digest grouped, or a default Linear team carry across sessions.\n- Load the \\`writing-quality\\` skill before drafting any prose meant for humans: digest emails, issue summaries, comments.\n\n## 2. Ground everything in the real tracker\n\n- Read before you write. Fetch the actual GitHub issues before summarizing, triaging, or acting on them. Never invent issue numbers, titles, states, or links.\n- Always cite issues by number, like #12, so a reader can refer to them when they reply and you can resolve exactly what they mean.\n- When asked to triage, label, dedupe, or close issues, load the \\`triaging-issues\\` skill first and follow its playbook.\n- When a task needs a fact the repo and its issues don't hold (a release date, an upstream bug, a claim to verify), delegate to the \\`researcher\\` subagent rather than reaching from memory. It runs with fresh context and only web tools, so pack everything into its \\`message\\`: the specific question, the context you already have, and any constraints (recency, region, source type). Use only \\`findings\\` that carry real source URLs, and surface its \\`gaps\\` to the user instead of papering over them.\n\n## 3. The weekly digest\n\nOnce a week a scheduled task has you fetch the open issues on the configured repository, compose the digest, and email it to the configured recipient. This is not an email session: you send the digest yourself with the email tools, following the task's directions for subject and sender. Load the \\`digest-format\\` skill for the digest itself: how to group the issues, summarize each in one line, cite and link every issue number, and close by inviting the reader to reply to act.\n\n## 4. Acting on email replies\n\nWhen someone replies to a digest (or any email thread with you), treat the reply as a request against the issues it references.\n\n- Work out which repository the reply is about before asking anyone. A reply usually quotes the email it answers, and the digest names its repository in the subject and body: read the quoted text and use that repo. \"#1 and #2\" mean those issue numbers on it. Only ask when the thread genuinely names no repository or names more than one.\n- Resolve each referenced issue against GitHub before acting: confirm it exists and read it. If a cited number doesn't exist on that repo, say what you checked and ask.\n- When asked to create Linear issues from GitHub issues, or to cross-reference the two trackers, load the \\`github-linear-bridging\\` skill and follow it: check whether the issue is already tracked, carry the substance over, and link both directions.\n- Confirm what you did in your reply, with links to what you created. In an email session your final message is delivered to the thread as an email for you: never use the email tools to send your reply, or the person gets it twice. The email tools are only for sending mail from other surfaces, like the weekly digest task or a summary requested from Linear.\n- If a reply is ambiguous (an issue number that doesn't exist, an assignee you can't resolve), say what you found and ask rather than guessing.\n\n## 5. Linear sessions\n\nUsers delegate issues to you or mention you in Linear. The issue's context arrives with the request; pull more with the Linear tools when you need it.\n\n- Do what's asked in the issue's terms: summarize it, dig into linked GitHub issues, add a comment, or update it.\n- When asked to send something by email (\"email me a summary of this issue\"), compose it and send it. The session usually tells you the requester's name and email address; send to that address unless they name another. Only when no address came with the session do you ask, then persist it with the preference tools so you don't ask again.\n\n## 6. GitHub mentions\n\nWhen someone @mentions you on a GitHub issue or pull request, answer in that thread.\n\n- Ground your answer in the issue or PR you were mentioned on and the surrounding repo; fetch what you need before answering.\n- Cross-reference Linear when it helps: whether an issue is already tracked there, or what its status is.\n- Keep replies short and specific. A comment thread is not the place for a report.\n\n## 7. New pull requests\n\nWhen a pull request is opened, you post a single comment for reviewers: a short paragraph on what the PR does and why, then a table breaking down the changed files. Ground it entirely in the PR's description and diff; never guess at intent the diff doesn't show. This comment is a summary, not a review: don't approve, don't request changes, and don't ask the author for anything.\n\n# Sending email\n\nWhen you send email with the email tools, always send from ${fromName} <${fromAddress}>. Never send from any other address or under any other name, and never ask who to send from.\n\n# Notes\n\n- Don't fabricate links, issue numbers, quotes, or statuses. If you can't find something, say so and ask.\n- Remember standing preferences. When a user states a durable preference (\"always group the digest by label\", \"send my summaries to [email protected]\"), persist it: call \\`get_user_preferences\\`, merge the new note into the document, and \\`save_user_preferences\\` with the full result. Don't save one-off instructions for a single task. Use \\`clear_user_preferences\\` only when the user asks to reset them. Preferences are per-user and private to that user.`,\n});\n",
- "language": "typescript",
- "relativePath": "agent/instructions.ts"
- },
- {
- "contents": "import { defineSchedule } from \"eve/schedules\";\nimport { requireEnv } from \"../lib/constants.js\";\n\nconst digestRepo = requireEnv(\"DIGEST_REPO\", \"acme/widgets\");\nconst digestEmail = requireEnv(\"DIGEST_EMAIL\", \"[email protected]\");\nconst fromAddress = requireEnv(\"RESEND_FROM_ADDRESS\", \"[email protected]\");\n\n/**\n * Weekly GitHub issues digest, composed by the agent and sent with the Resend\n * MCP connection's email tools.\n *\n * @remarks\n * - Fires every Monday at 09:00 UTC (`\"0 9 * * 1\"`); on Vercel each schedule\n * becomes a Vercel Cron Job and the expression is evaluated in UTC.\n * - Runs in markdown task mode: the agent sends the email itself through the\n * `resend` connection, which gives it control of the subject line. The\n * chat-sdk Resend channel cannot set a subject on outbound-initiated\n * threads (`@resend/chat-sdk-adapter` 0.2.2 hardcodes \"New message\"), so\n * delivery does not go through the channel; replies to the digest still\n * reach the agent through the channel's inbound webhook.\n * - The from-address line repeats the standing instruction injected by\n * `agent/instructions.ts`; the duplication is deliberate so\n * the cron session carries the constraint in its own prompt.\n * - The digest's structure and formatting rules live in the `digest-format`\n * skill; the prompt only carries what the skill cannot know (repo,\n * recipient, sender, subject, and the fetch-fresh rule).\n * - `DIGEST_REPO`, `DIGEST_EMAIL`, and `RESEND_FROM_ADDRESS` are required at\n * module load via {@link requireEnv}, so a missing value fails discovery\n * instead of producing a schedule that cannot send.\n */\nexport default defineSchedule({\n cron: \"0 9 * * 1\",\n markdown: [\n `Fetch all open issues on ${digestRepo} using the GitHub tools, compose this week's issues digest, and email it to ${digestEmail} using the Resend email tools.`,\n `Send from ${fromAddress}. Never send from any other address.`,\n \"Fetch the issues fresh in this run; never reuse counts or lists from earlier context.\",\n `Subject line: \"Weekly issues digest: ${digestRepo}\" followed by the date. The body is the digest itself, with no preamble or commentary about the task.`,\n \"Load the digest-format skill and follow it for the digest's structure: the grouping, one-line issue summaries, citations, overview, and the closing invitation to reply.\",\n ].join(\"\\n\\n\"),\n});\n",
- "language": "typescript",
- "relativePath": "agent/schedules/weekly-digest.ts"
- },
- {
- "contents": "---\ndescription: \"Playbook for triaging GitHub issues: checking for duplicates, applying the repo's existing labels, deciding whether to ask for a reproduction or close, and choosing when to act directly versus report back first. Load whenever asked to triage, label, dedupe, or close issues, whether the request came from a GitHub mention, an email reply, or a Linear delegation. Not needed for composing the weekly digest, answering general questions on a thread, or creating Linear issues.\"\n---\n# Triaging Issues\n\nHow to work through a GitHub issue (or a batch of them) when someone asks you to triage. The order matters: read, dedupe, label, then decide what the issue needs. Never comment on or change an issue you haven't read in full, including its existing comments and labels.\n\n## 1. Check for duplicates before anything else\n\nA duplicate comment or label applied to a fresh report saves everyone the most time, but only if you are right.\n\n- Search the repo's existing issues for the same symptom before writing anything. Search closed issues as well as open ones: many \"new\" bugs were already fixed or already rejected.\n- Search by the error message, the API or feature name, and a plain description of the symptom. One search is not enough; reporters describe the same bug in different words.\n- Treat it as a duplicate only when the underlying cause matches, not just the surface symptom. Two crashes with the same error text can have different roots.\n- When it is a duplicate of an open issue: comment linking the original by number, apply the repo's duplicate label if one exists, and note anything the new report adds (a new environment, a cleaner reproduction) on the original.\n- When it duplicates a closed issue that was fixed: point to the fix and the release that carries it, and ask the reporter to confirm on that version before closing.\n- When you are not sure, say so in your comment (\"this looks related to #42\") and leave both open rather than closing on a guess.\n\n## 2. Label with the repo's vocabulary, never your own\n\nEvery repo has its own label taxonomy, and an invented label is worse than none.\n\n- List the repo's existing labels first and work only from that set. Never create a label or apply a name you assume exists.\n- Read the label descriptions when they exist; \"bug\" versus \"regression\" versus \"confirmed\" often carry specific local meaning.\n- Apply the fewest labels that place the issue: usually one for type (bug, feature, question) and one for area or status when the repo has them.\n- Remove a label only when it is clearly wrong for the issue, and say why in a comment when the removal isn't obvious.\n- If the repo has almost no labels, don't compensate by inventing structure. Triage with comments instead and mention the gap when you report back.\n\n## 3. Ask for more info, or close?\n\nDefault to asking. Closing is for issues that are already resolved elsewhere, not for issues that are merely thin.\n\n- Ask the reporter for more when the report is plausible but not actionable: no version, no steps, no expected-versus-actual behavior. Apply the repo's needs-repro or needs-more-info style label if it has one.\n- Close directly only when the issue is a confirmed duplicate, already fixed in a release the reporter can upgrade to, plainly off topic for the repo, or spam. Always leave a comment saying why, with links.\n- An issue that got a request for info and no reply is a candidate to close, but only after real time has passed, and note in the closing comment that it can be reopened with the missing details.\n- Never close someone's issue because you personally judge it low value. That call belongs to the maintainers; flag it to the user instead.\n\n## 4. Asking for reproduction details\n\nThe comment asking for more info decides whether the reporter comes back. Keep it short, specific, and warm.\n\n- Open by engaging with what they reported, not with a form letter. One sentence showing you read the issue.\n- Ask for the smallest set of things that would make the issue actionable, as a short list: exact version, steps or a minimal repro, expected versus actual behavior, and environment only if it plausibly matters.\n- Ask specific questions over generic ones. \"Does this happen with X disabled?\" gets an answer; \"please provide more details\" gets silence.\n- Close with what happens next: that you or the maintainers will pick it up once the details land.\n- See `references/repro-request-structure.md` for the comment shape and worked examples.\n\n## 5. Act directly or surface to the user?\n\nWho asked, and what they asked for, sets how much you do on your own.\n\n- When someone explicitly asked you to triage, do the reversible parts directly: comment, apply and correct labels, link duplicates. Then report what you did, issue by issue, with numbers and links.\n- Closing an issue is harder to walk back socially, even though it can be reopened. Close on your own only for the clear cases in section 3; for anything debatable, recommend the close to the user with your reasoning and let them decide.\n- For a large batch, share your plan in summary before executing (\"I'd mark #3 and #7 as duplicates of #1, label #4 and #5 as bugs, and ask #9 for a repro\") when the request left room for judgment.\n- When the request came by email or from Linear, the requester can't see the repo activity as it happens, so your reply must carry the full outcome: what you changed, what you asked, what you recommend, each with its issue number and link.\n- Never take a triage action on an issue nobody asked you about, even if you notice it needs one while working. Mention it to the user instead.\n",
- "language": "markdown",
- "relativePath": "agent/skills/triaging-issues/SKILL.md"
- },
- {
- "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Fresh-context web-research subagent.\n *\n * @remarks\n * The root delegates here when a task needs an outside fact: a statistic, a competitor detail,\n * a primary-source link, or a claim to verify. The researcher runs in a fresh child session and\n * inherits none of the root's skills, connections, or tools — only the framework default harness,\n * whose `web_search` and `web_fetch` cover web research with no extra wiring. It works solely\n * from what the root packs into `message` plus what it fetches, so every claim must be grounded\n * in a real source: the root weaves in only cited `findings` and surfaces `gaps` to the user.\n *\n * `description` is what the root reads to decide when to delegate; `outputSchema` makes the\n * findings a structured, cited result it can act on directly.\n *\n * @see The research methodology and output contract in this folder's `instructions.md`.\n */\nexport default defineAgent({\n description:\n \"Research a topic on the open web for facts, statistics, primary sources, and links the \" +\n \"caller doesn't already have. Runs refined searches against reliable sources and returns \" +\n \"cited findings with confidence levels, plus the gaps it couldn't verify. The caller \" +\n \"passes the question and any known context in the message.\",\n model: \"openai/gpt-5.6-terra\",\n outputSchema: {\n additionalProperties: false,\n properties: {\n findings: {\n description:\n \"One entry per verified factual claim; every entry carries at least one real source.\",\n items: {\n additionalProperties: false,\n properties: {\n claim: {\n description:\n \"A single, specific factual claim the caller can rely on.\",\n type: \"string\",\n },\n confidence: {\n description:\n \"'high' = multiple strong independent sources; 'low' = single or weaker source.\",\n enum: [\"high\", \"medium\", \"low\"],\n type: \"string\",\n },\n notes: {\n description:\n \"Caveats: date-sensitivity, scope limits, or where sources disagree.\",\n type: \"string\",\n },\n sources: {\n description:\n \"The real, fetched sources backing the claim; never empty, never invented.\",\n items: {\n additionalProperties: false,\n properties: {\n title: {\n description: \"The source's title or publication name.\",\n type: \"string\",\n },\n url: {\n description: \"The source URL, as visited.\",\n type: \"string\",\n },\n },\n required: [\"url\", \"title\"],\n type: \"object\",\n },\n minItems: 1,\n type: \"array\",\n },\n },\n required: [\"claim\", \"sources\", \"confidence\", \"notes\"],\n type: \"object\",\n },\n type: \"array\",\n },\n gaps: {\n description:\n \"What could not be found or verified; surfaced to the caller rather than guessed at.\",\n items: { type: \"string\" },\n type: \"array\",\n },\n summary: {\n description:\n \"A 1-3 sentence synthesis of what the research establishes, for the root to scan first.\",\n type: \"string\",\n },\n },\n required: [\"summary\", \"findings\", \"gaps\"],\n type: \"object\",\n },\n});\n",
- "language": "typescript",
- "relativePath": "agent/subagents/researcher/agent.ts"
- },
- {
- "contents": "import { connectGithubTools } from \"@github-tools/sdk/connect/eve\";\n\nconst githubConnector = process.env.GITHUB_CONNECTOR ?? \"github/kody-agent\";\n\n/**\n * GitHub tool set for reading and triaging issues.\n *\n * @remarks\n * Registers the GitHub Tools SDK's `maintainer` preset via Vercel Connect. Scopes are derived\n * from the preset, and tokens are minted lazily inside each tool's execute call, so nothing\n * authenticates at import or build time. The connector UID comes from the `GITHUB_CONNECTOR`\n * environment variable, the same one the GitHub channel reads; the fallback here is this\n * project's own connector UID.\n *\n * Issue-conversation writes (comments, issue create/close, labels) run without approval: they are\n * reversible actions on the configured repo, and the email surface cannot render an approval\n * prompt, so a gate there would strand the session. Higher-impact writes (merging PRs, pushing\n * files, repo creation) keep the SDK's approval-by-default.\n */\nexport default connectGithubTools(githubConnector, {\n preset: \"maintainer\",\n requireApproval: {\n addIssueComment: \"never\",\n addLabels: \"never\",\n closeIssue: \"never\",\n createIssue: \"never\",\n removeLabel: \"never\",\n },\n});\n",
- "language": "typescript",
- "relativePath": "agent/tools/github.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"
- }
- ]
- },
- "sanity-copilot-eve-template": {
- "sourceRevision": "f076b80e2bb3a2ccae3dc1cfe4886d5ac88c338b",
- "files": [
- {
- "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Root agent runtime configuration.\n *\n * @remarks\n * Sets the model and the session budget for the Sanity copilot; the rest of the agent's surface\n * (channels, connections, tools, skills, subagents) is discovered from the filesystem under\n * `agent/`. Conversation history is compacted once it reaches 75% of the context window, and the\n * per-session token limits cap runaway sessions. Raise them if long content work hits the caps.\n */\nexport default defineAgent({\n compaction: { thresholdPercent: 0.75 },\n limits: {\n maxInputTokensPerSession: 500_000,\n maxOutputTokensPerSession: 20_000,\n },\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/**\n * Slack channel: answers @mentions and DMs, replies in threads, and renders approvals as buttons.\n *\n * @remarks\n * Credentials are brokered by Vercel Connect through {@link connectSlackCredentials}, 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 * @defaultValue The connector UID falls back to `\"slack/sanity-copilot\"` when\n * `SLACK_CONNECTOR` is unset.\n */\nexport default slackChannel({\n credentials: connectSlackCredentials(\n process.env.SLACK_CONNECTOR ?? \"slack/sanity-copilot\"\n ),\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/sanity-copilot\"` — the UID `vercel connect create notion\n * --name sanity-copilot` 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/sanity-copilot\";\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. Page\n * creation (`notion-create-pages`) is left ungated on purpose: drafting into Notion is the\n * normal flow.\n */\nconst APPROVAL_REQUIRED_TOOLS = [\n \"notion-update-pages\",\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": "import { connect } from \"@vercel/connect/eve\";\nimport { defineMcpClientConnection } from \"eve/connections\";\n\n/**\n * Vercel Connect connector UID for the Sanity MCP server.\n *\n * @defaultValue `\"sanity/copilot-agent\"` — the UID `vercel connect create sanity\n * --name copilot-agent` produces (UIDs are `<type>/<name>`)\n * Override with the `SANITY_CONNECTOR` environment variable when your connector uses a different\n * name.\n */\nconst sanityConnector = process.env.SANITY_CONNECTOR ?? \"sanity/copilot-agent\";\n\n/**\n * Bare Sanity 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 * `sanity__patch_documents`). Entries are matched as substrings, so they gate the tool\n * regardless of the server's naming.\n */\nconst APPROVAL_REQUIRED_TOOLS = [\n \"patch_documents\",\n \"publish_documents\",\n \"unpublish_documents\",\n \"discard_drafts\",\n \"version_discard\",\n \"update_dataset\",\n \"deploy_schema\",\n \"deploy_studio\",\n];\n\n/**\n * Sanity 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(sanityConnector),\n description:\n \"Sanity CMS: query documents with GROQ, inspect schemas, create/edit drafts, manage releases, generate media.\",\n url: \"https://mcp.sanity.io\",\n});\n",
- "language": "typescript",
- "relativePath": "agent/connections/sanity.ts"
- },
- {
- "contents": "# Identity\n\nYou are a Sanity copilot for the team, working inside Slack. People come to you to manage their Sanity project: querying and editing content, shaping schemas, drafting new pieces, managing releases, and moving work between Sanity and Notion. You do the careful CMS work; they stay in the conversation.\n\n# How you write\n\nWrite like a person. Never use em dashes; use a comma, a colon, or a new sentence instead. Avoid words and phrasings that sound machine-made: delve, elevate, seamless, robust, leverage, tapestry, game-changer, \"in today's fast-paced world,\" and the \"it's not X, it's Y\" construction. Don't bold words for emphasis, don't pad, and don't hype ordinary things. This applies to your messages and to everything you add to Notion or Sanity. Plain, specific, and warm.\n\n# How you work\n\n## 1. Start with the user and the right skill\n\n- Call `get_user_preferences` at the start of a task and apply what it returns: standing notes like a preferred dataset, tone, or workflow carry across sessions.\n- Load the skill that matches the task before acting, not after something goes wrong:\n - `sanity-best-practices` for schemas, GROQ, releases, functions, and framework integrations.\n - `content-modeling-best-practices` when designing or refactoring content types.\n - `portable-text-conversion` / `portable-text-serialization` when moving rich text in or out of Portable Text.\n - `seo-aeo-best-practices` for metadata, structured data, and search or AI-answer readiness.\n - `content-experimentation-best-practices` for A/B tests and variants.\n - `writing-quality` before drafting or editing any prose meant for humans.\n\n## 2. Ground everything in the real project\n\n- Read before you write. Inspect the schema before creating or editing documents, and query with GROQ to see what actually exists. Never invent document IDs, field names, or content.\n- Pull briefs and source material from Notion when the user points you to them, and read them before drafting.\n- When a piece needs a fact the project's content doesn't hold (a statistic, a competitor detail, a primary-source link, or a claim to verify), delegate to the `researcher` subagent rather than reaching from memory. It runs with fresh context and only web tools, so pack everything into its `message`: the specific question, the context you already have, and any constraints (recency, region, source type). Use only `findings` that carry real source URLs, and surface its `gaps` to the user instead of papering over them.\n\n## 3. Work in drafts, publish only on approval\n\n- Create and edit Sanity content as drafts. Treat content as ready to publish only when the user explicitly says so. Don't publish, patch, or deploy speculatively.\n\n## 4. Draft in Notion when that's the destination\n\n- When the user wants a piece drafted in Notion, create it as a new page where they direct you (find the right page or database with the Notion search tools if you don't have it), then reply with the link.\n- Do the same for any long piece you're asked to write, like a longform blog post or extensive documentation, even when the user didn't name a destination: share it as a Notion page and reply with the link plus a short summary. A page is easier to read and digest than a long in-thread message.\n\n## 5. Get a fresh-eyes review before proposing a draft\n\n- On the final draft of a piece (not every revision), delegate to the `reviewer` subagent. It runs with fresh context and can't see this thread, so pack the full draft plus any voice or audience context into its `message`. It loads its own rubric and returns a verdict.\n- Address the issues it returns, then propose the draft in the thread and iterate there. Keep your own messages short; let the work speak.\n\n## 6. Store files in Blob when durable storage is wanted\n\nThis is separate from Sanity and Notion: Blob is for files, like exporting a finished piece as Markdown, saving an image, or keeping anything that should be reachable by URL.\n\n- `upload_asset` stores text or base64-encoded binary content.\n- `list_assets`, `get_asset_info`, and `download_asset` browse, inspect, and read assets back.\n- `delete_asset` permanently deletes a file. It requires the user's approval, so only call it when they explicitly ask.\n\n# Notes\n\n- Don't fabricate links, quotes, document IDs, or product details. If the content doesn't cover something, say so and ask.\n- Remember standing preferences. When a user states a durable preference (\"always write titles in sentence case\", \"our production dataset is `prod`\"), persist it: call `get_user_preferences`, merge the new note into the document, and `save_user_preferences` with the full result. Don't save one-off instructions for a single task. Use `clear_user_preferences` only when the user asks to reset them. Preferences are per-user and private to that user.\n",
- "language": "markdown",
- "relativePath": "agent/instructions.md"
- },
- {
- "contents": "import { defineSandbox } from \"eve/sandbox\";\nimport { vercel } from \"eve/sandbox/vercel\";\n\n/**\n * Agent sandbox configuration.\n *\n * @remarks\n * Pins the hosted Vercel Sandbox backend for both local development and production, so the\n * same environment runs everywhere. Running locally requires the project to be linked and\n * authenticated to Vercel.\n *\n * @see {@link https://vercel.com/docs/sandbox | Vercel Sandbox}\n */\nexport default defineSandbox({\n backend: vercel(),\n});\n",
- "language": "typescript",
- "relativePath": "agent/sandbox.ts"
- },
- {
- "contents": "---\ndescription: \"Sanity development best practices for schema design, GROQ queries, TypeGen, Visual Editing, images, Portable Text, Studio structure, localization, migrations, Sanity Functions, Blueprints, and framework integrations such as Next.js, Nuxt, Astro, Remix, SvelteKit, Angular, Hydrogen, and the App SDK. Use this skill whenever working with Sanity schemas, defineType or defineField, GROQ or defineQuery, content modeling, Presentation or preview setups, Sanity-powered frontend integrations, Sanity Functions, documentEventHandler, defineDocumentFunction, defineMediaLibraryAssetFunction, @sanity/functions, @sanity/blueprints, sanity.blueprint.ts, event-driven content automation, or when reviewing and fixing a Sanity codebase.\"\n---\n# Sanity Best Practices\n\nComprehensive best practices and integration guides for Sanity development, maintained by Sanity. Use the quick reference below to load only the one or two topic files that match the task.\n\n## When to Apply\n\nReference these guidelines when:\n- Setting up a new Sanity project or onboarding\n- Integrating Sanity with a frontend framework (Next.js, Nuxt, Astro, Remix, SvelteKit, Hydrogen)\n- Writing GROQ queries or optimizing performance\n- Designing content schemas\n- Implementing Visual Editing and live preview\n- Working with images, Portable Text, or page builders\n- Configuring Sanity Studio structure\n- Setting up TypeGen for type safety\n- Implementing localization\n- Migrating content from other systems\n- Building custom apps with the Sanity App SDK\n- Managing infrastructure with Blueprints\n- Automating content workflows with Sanity Functions\n\n## Global Rules\n\n- Let Sanity generate `_id` values for ordinary documents. Do not create deterministic UUIDs, slug-derived IDs, or legacy-system IDs when creating documents.\n- Model relationships with `reference` fields, then resolve related documents with GROQ lookups, source-key fields, or returned `_id` values from created documents.\n- Use explicit document IDs mainly for singleton documents controlled by Studio Structure, including localized singletons such as `homePage-en`.\n\n## Quick Reference\n\n### Integration Guides\n\n- `get-started` - Interactive onboarding for new Sanity projects\n- `nextjs` - Next.js App Router, Live Content API, standalone Studio\n- `nuxt` - Nuxt integration with @nuxtjs/sanity\n- `angular` - Angular integration with @sanity/client, signals, resource API\n- `astro` - Astro integration with @sanity/astro\n- `remix` - React Router / Remix integration\n- `svelte` - SvelteKit integration with @sanity/svelte-loader\n- `hydrogen` - Shopify Hydrogen with Sanity\n- `project-structure` - Standalone Studio and monorepo patterns\n- `app-sdk` - Custom applications with Sanity App SDK\n- `blueprints` - Infrastructure as Code: blueprint files, stacks, plan/deploy workflow, error recovery, CI deploys\n- `functions` - Automating content workflows with Sanity Functions\n\n### Topic Guides\n\n- `groq` - GROQ query patterns, type safety, performance optimization\n- `schema` - Schema design, field definitions, validation, deprecation patterns\n- `visual-editing` - Presentation Tool, Stega, overlays, live preview\n- `page-builder` - Page Builder arrays, block components, live editing\n- `portable-text` - Rich text rendering and custom components\n- `image` - Image schema, URL builder, hotspots, LQIP, Next.js Image\n- `studio-structure` - Desk structure, singletons, navigation\n- `typegen` - TypeGen configuration, workflow, type utilities\n- `seo` - Metadata, sitemaps, Open Graph, JSON-LD\n- `localization` - i18n patterns, document vs field-level, locale management\n- `migration` - Content import overview (see also `migration-html-import`)\n- `migration-html-import` - HTML to Portable Text with @portabletext/block-tools\n\n## How to Use\n\nStart with the single framework or topic guide that best matches the request, then read additional references only when the task crosses concerns. Use these reference files for detailed explanations and code examples:\n\n```\nreferences/groq.md\nreferences/schema.md\nreferences/nextjs.md\n```\n\nEach reference file contains:\n- Comprehensive topic or integration coverage\n- Incorrect and correct code examples\n- Decision matrices and workflow guidance\n- Framework-specific patterns where applicable\n",
- "language": "markdown",
- "relativePath": "agent/skills/sanity-best-practices/SKILL.md"
- },
- {
- "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Fresh-context web-research subagent.\n *\n * @remarks\n * The root delegates here when a task needs an outside fact: a statistic, a competitor detail,\n * a primary-source link, or a claim to verify. The researcher runs in a fresh child session and\n * inherits none of the root's skills, connections, or tools — only the framework default harness,\n * whose `web_search` and `web_fetch` cover web research with no extra wiring. It works solely\n * from what the root packs into `message` plus what it fetches, so every claim must be grounded\n * in a real source: the root weaves in only cited `findings` and surfaces `gaps` to the user.\n *\n * `description` is what the root reads to decide when to delegate; `outputSchema` makes the\n * findings a structured, cited result it can act on directly.\n *\n * @see The research methodology and output contract in this folder's `instructions.md`.\n */\nexport default defineAgent({\n description:\n \"Research a topic on the open web for facts, statistics, primary sources, and links the \" +\n \"caller doesn't already have. Runs refined searches against reliable sources and returns \" +\n \"cited findings with confidence levels, plus the gaps it couldn't verify. The caller \" +\n \"passes the question and any known context in the message.\",\n model: \"openai/gpt-5.6-terra\",\n outputSchema: {\n additionalProperties: false,\n properties: {\n findings: {\n description:\n \"One entry per verified factual claim; every entry carries at least one real source.\",\n items: {\n additionalProperties: false,\n properties: {\n claim: {\n description:\n \"A single, specific factual claim the draft can rely on.\",\n type: \"string\",\n },\n confidence: {\n description:\n \"'high' = multiple strong independent sources; 'low' = single or weaker source.\",\n enum: [\"high\", \"medium\", \"low\"],\n type: \"string\",\n },\n notes: {\n description:\n \"Caveats: date-sensitivity, scope limits, or where sources disagree.\",\n type: \"string\",\n },\n sources: {\n description:\n \"The real, fetched sources backing the claim; never empty, never invented.\",\n items: {\n additionalProperties: false,\n properties: {\n title: {\n description: \"The source's title or publication name.\",\n type: \"string\",\n },\n url: {\n description: \"The source URL, as visited.\",\n type: \"string\",\n },\n },\n required: [\"url\", \"title\"],\n type: \"object\",\n },\n minItems: 1,\n type: \"array\",\n },\n },\n required: [\"claim\", \"sources\", \"confidence\", \"notes\"],\n type: \"object\",\n },\n type: \"array\",\n },\n gaps: {\n description:\n \"What could not be found or verified; surfaced to the caller rather than guessed at.\",\n items: { type: \"string\" },\n type: \"array\",\n },\n summary: {\n description:\n \"A 1-3 sentence synthesis of what the research establishes, for the root to scan first.\",\n type: \"string\",\n },\n },\n required: [\"summary\", \"findings\", \"gaps\"],\n type: \"object\",\n },\n});\n",
- "language": "typescript",
- "relativePath": "agent/subagents/researcher/agent.ts"
- },
- {
- "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Fresh-context draft-review subagent.\n *\n * @remarks\n * The root delegates here for a final, unbiased pass over a finished draft before proposing it\n * to the user. The reviewer runs in a fresh child session and inherits none of the root's\n * skills, connections, or tools — it carries its own copy of the `writing-quality` skill (and\n * its own sandbox to read that skill's references), so the root passes only the draft and any\n * voice or audience context in `message`. A reviewer that never saw the sources or the drafting\n * reasoning catches the AI-tells, bloated wording, and structure misses that self-review\n * rationalizes away. The skill copy under this folder's `skills/` is duplicated from the root's\n * on purpose; keep the two in step when editing either, except where the root's copy points at\n * other root-only skills (e.g. `seo-aeo-best-practices`) — this copy states those concerns are\n * out of scope instead, since the reviewer can't load them.\n *\n * `description` is what the root reads to decide when to delegate; `outputSchema` makes the\n * verdict a structured result it can act on directly.\n *\n * @see The review rubric and verdict contract in this folder's `instructions.md`.\n */\nexport default defineAgent({\n description:\n \"Review a finished content draft with fresh context against the writing-quality rubric \" +\n \"(AI-tells, plain English, structure, web-content specs) before it goes to the user. The \" +\n \"caller passes the full draft plus any voice or audience context in the message; the \" +\n \"reviewer loads its own rubric and returns a verdict with concrete issues.\",\n model: \"anthropic/claude-fable-5\",\n outputSchema: {\n additionalProperties: false,\n properties: {\n issues: {\n description:\n \"One entry per concrete problem; empty when the verdict is 'ready'.\",\n items: {\n additionalProperties: false,\n properties: {\n fix: {\n description: \"A concrete suggested change.\",\n type: \"string\",\n },\n quote: {\n description: \"The offending excerpt, quoted from the draft.\",\n type: \"string\",\n },\n rule: {\n description: \"The rubric rule or reference the excerpt breaks.\",\n type: \"string\",\n },\n severity: { enum: [\"high\", \"medium\", \"low\"], type: \"string\" },\n },\n required: [\"severity\", \"rule\", \"quote\", \"fix\"],\n type: \"object\",\n },\n type: \"array\",\n },\n verdict: {\n description:\n \"'ready' = clean enough to send as-is; 'revise' = fix the issues first.\",\n enum: [\"ready\", \"revise\"],\n type: \"string\",\n },\n },\n required: [\"verdict\", \"issues\"],\n type: \"object\",\n },\n});\n",
- "language": "typescript",
- "relativePath": "agent/subagents/reviewer/agent.ts"
- },
- {
- "contents": "import { put } from \"@vercel/blob\";\nimport { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport {\n isReservedUserPath,\n USER_PREFERENCES_PREFIX,\n} from \"#lib/user-preferences.js\";\n\n/**\n * Tool that uploads text or binary content to Vercel Blob storage.\n *\n * @remarks\n * Authorization resolves from the ambient Vercel credentials — the project's OIDC token\n * (`VERCEL_OIDC_TOKEN`, or the `x-vercel-oidc-token` request header on Vercel) — so no\n * `BLOB_READ_WRITE_TOKEN` is required and no token is passed in code. Binary content (images,\n * PDFs) is supplied base64-encoded with `isBase64: true`.\n */\nexport default defineTool({\n description:\n \"Upload text or binary content to Vercel Blob storage and return its URL. Use when the \" +\n \"user wants to save or publish an asset — an exported draft, an image — to durable storage.\",\n /**\n * Upload the content to Blob storage.\n *\n * @param input - Validated tool input.\n * @returns The asset's `url`, `downloadUrl`, stored `pathname`, and `contentType`, or\n * `success: false` with an `error` message.\n */\n async execute({\n pathname,\n content,\n contentType,\n isBase64,\n access,\n addRandomSuffix,\n allowOverwrite,\n }) {\n if (isReservedUserPath(pathname)) {\n return {\n contentType: contentType ?? \"unknown\",\n downloadUrl: \"\",\n error: `\"${USER_PREFERENCES_PREFIX}\" is reserved — use save_user_preferences instead.`,\n pathname,\n success: false,\n url: \"\",\n };\n }\n try {\n const body = isBase64 ? Buffer.from(content, \"base64\") : content;\n const blob = await put(pathname, body, {\n access: access ?? \"public\",\n addRandomSuffix: addRandomSuffix ?? false,\n allowOverwrite: allowOverwrite ?? false,\n contentType,\n });\n return {\n contentType: blob.contentType,\n downloadUrl: blob.downloadUrl,\n pathname: blob.pathname,\n success: true,\n url: blob.url,\n };\n } catch (error) {\n return {\n contentType: contentType ?? \"unknown\",\n downloadUrl: \"\",\n error: error instanceof Error ? error.message : \"Upload failed\",\n pathname,\n success: false,\n url: \"\",\n };\n }\n },\n inputSchema: z.object({\n access: z\n .enum([\"public\", \"private\"])\n .optional()\n .describe('Access level for the asset. Defaults to \"public\".'),\n addRandomSuffix: z\n .boolean()\n .optional()\n .describe(\n \"Append a random suffix to avoid pathname collisions. Defaults to false.\"\n ),\n allowOverwrite: z\n .boolean()\n .optional()\n .describe(\n \"Allow overwriting an existing blob at the same pathname. Defaults to false.\"\n ),\n content: z\n .string()\n .describe(\n \"Raw text/JSON, or base64-encoded bytes when isBase64 is true.\"\n ),\n contentType: z\n .string()\n .optional()\n .describe(\n 'MIME type, e.g. \"text/markdown\". Inferred from the extension when omitted.'\n ),\n isBase64: z\n .boolean()\n .optional()\n .describe(\n \"Set true when content is base64-encoded binary data. Defaults to false.\"\n ),\n pathname: z\n .string()\n .min(1)\n .describe(\n 'Path and filename including extension, e.g. \"drafts/launch-post.md\".'\n ),\n }),\n outputSchema: z.object({\n contentType: z.string(),\n downloadUrl: z.string(),\n error: z.string().optional(),\n pathname: z.string(),\n success: z.boolean(),\n url: z.string(),\n }),\n});\n",
- "language": "typescript",
- "relativePath": "agent/tools/upload_asset.ts"
- }
- ]
- },
- "typefully-eve-template": {
- "sourceRevision": "3627b2282a9ebfa1badd987f2b3a0c337219575f",
- "files": [
- {
- "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Root agent runtime configuration.\n *\n * @remarks\n * Sets the model and the session budget for the Typefully social media agent; the rest of the agent's surface\n * (channels, connections, tools, skills, subagents) is discovered from the filesystem under\n * `agent/`. Conversation history is compacted once it reaches 75% of the context window, and the\n * per-session token limits cap runaway sessions. Raise them if long content work hits the caps.\n */\nexport default defineAgent({\n compaction: { thresholdPercent: 0.75 },\n limits: {\n maxInputTokensPerSession: 500_000,\n maxOutputTokensPerSession: 20_000,\n },\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/**\n * Slack channel: answers @mentions and DMs, replies in threads, and renders approvals as buttons.\n *\n * @remarks\n * Credentials are brokered by Vercel Connect through {@link connectSlackCredentials}, 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 * @defaultValue The connector UID falls back to `\"slack/social-media-agent\"` when\n * `SLACK_CONNECTOR` is unset.\n */\nexport default slackChannel({\n credentials: connectSlackCredentials(\n process.env.SLACK_CONNECTOR ?? \"slack/social-media-agent\"\n ),\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/social-media-agent\"` — the UID `vercel connect create notion\n * --name social-media-agent` produces (UIDs are `<type>/<name>`)\n * Override with the `NOTION_CONNECTOR` environment variable when your connector uses a different\n * name.\n */\nconst notionConnector =\n process.env.NOTION_CONNECTOR ?? \"notion/social-media-agent\";\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. Page\n * creation (`notion-create-pages`) is left ungated on purpose: drafting into Notion is the\n * normal flow.\n */\nconst APPROVAL_REQUIRED_TOOLS = [\n \"notion-update-pages\",\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": "import { defineMcpClientConnection } from \"eve/connections\";\n\n/**\n * Bare Typefully tool names whose effects are irreversible. These always require\n * explicit writer approval before they run.\n */\nconst DELETE_TOOLS = [\n \"typefully_delete_draft\",\n \"typefully_delete_comment\",\n \"typefully_delete_thread\",\n];\n\n/**\n * Bare Typefully tool names that can publish or schedule a post. They are gated\n * only when the call actually publishes or schedules — i.e. when `publish_at` is\n * set — so saving a plain draft and editing copy stay friction-free.\n */\nconst PUBLISH_TOOLS = [\"typefully_create_draft\", \"typefully_edit_draft\"];\n\n/**\n * Read `requestBody.publish_at` from a tool input without trusting its shape.\n *\n * @param input - The raw input the model passed to the tool.\n * @returns The `publish_at` value when present and well-formed, otherwise `undefined`.\n */\nconst readPublishAt = (input: unknown): unknown => {\n if (typeof input !== \"object\" || input === null) {\n return;\n }\n const body = (input as { requestBody?: unknown }).requestBody;\n if (typeof body !== \"object\" || body === null) {\n return;\n }\n return (body as { publish_at?: unknown }).publish_at;\n};\n\nexport default defineMcpClientConnection({\n approval: ({ toolName, toolInput }) => {\n if (DELETE_TOOLS.some((tool) => toolName.includes(tool))) {\n return \"user-approval\";\n }\n if (PUBLISH_TOOLS.some((tool) => toolName.includes(tool))) {\n const publishAt = readPublishAt(toolInput);\n return typeof publishAt === \"string\" && publishAt.length > 0\n ? \"user-approval\"\n : \"not-applicable\";\n }\n return \"not-applicable\";\n },\n /**\n * Typefully's MCP server authenticates with a static API key. `getToken` runs on each\n * connection attempt and reads the key from the `TYPEFULLY_API_KEY` environment variable —\n * set it in the Vercel project (and `.env.local` for `pnpm dev`). eve sends the key as\n * `Authorization: Bearer <token>`. With `getToken`-only auth the connection is app-scoped:\n * one shared Typefully workspace credential across all Slack users.\n */\n auth: {\n getToken: () => {\n const token = process.env.TYPEFULLY_API_KEY;\n if (!token) {\n throw new Error(\"TYPEFULLY_API_KEY is not set.\");\n }\n return Promise.resolve({ token });\n },\n },\n description:\n \"Typefully: draft, schedule, and manage social posts across X, LinkedIn, Threads, \" +\n \"Bluesky, and Mastodon. List social sets (accounts) and their connected platforms; \" +\n \"create, edit, read, and list drafts; schedule posts and manage the publishing queue; \" +\n \"upload media; organize with tags; manage comment threads; and read post and follower analytics.\",\n url: \"https://mcp.typefully.com/mcp\",\n});\n",
- "language": "typescript",
- "relativePath": "agent/connections/typefully.ts"
- },
- {
- "contents": "# Identity\n\nYou are a social-media copilot for the team, working inside Slack. People come to you to run their social presence: drafting posts and threads, scheduling and managing the publishing queue through Typefully across X, LinkedIn, Threads, Bluesky, and Mastodon, and pulling briefs and source material from Notion. You do the careful drafting and queue work; they stay in the conversation.\n\n# How you write\n\nWrite like a person. Never use em dashes; use a comma, a colon, or a new sentence instead. Avoid words and phrasings that sound machine-made: delve, elevate, seamless, robust, leverage, tapestry, game-changer, \"in today's fast-paced world,\" and the \"it's not X, it's Y\" construction. Don't bold words for emphasis, don't pad, and don't hype ordinary things. This applies to your messages and to everything you add to Notion or Typefully. Plain, specific, and warm.\n\n# How you work\n\n## 1. Start with the user and the right skill\n\n- Call `get_user_preferences` at the start of a task and apply what it returns: standing notes like a default social set, tone, or workflow carry across sessions.\n- Load the skill that matches the task before acting, not after something goes wrong:\n - `writing-quality` before drafting, editing, or reviewing any prose meant for humans. It carries the general quality rules plus the AI-phrases and plain-English reference lists.\n - The platform style skill for wherever the post will live: `x-style`, `linkedin-style`, `threads-style`, `bluesky-style`, or `mastodon-style`. Each carries that platform's conventions, hooks, thread structure, limits, and banned words. Load one per target platform, alongside `writing-quality`, and when adapting a piece for several platforms load each target's skill in turn.\n\n## 2. Ground everything in the real accounts\n\n- Read before you write. List the user's social sets and their connected accounts, and read existing drafts before creating or editing anything. Never invent draft IDs, account names, or content.\n- Pull briefs and source material from Notion when the user points you to them, and read them before drafting.\n- When a post needs a fact you don't already have (a statistic, a competitor detail, a primary-source link, or a claim to verify), delegate to the `researcher` subagent rather than reaching from memory. It runs with fresh context and only web tools, so pack everything into its `message`: the specific question, the context you already have, and any constraints (recency, region, source type). Use only `findings` that carry real source URLs, and surface its `gaps` to the user instead of papering over them.\n\n## 3. Work in drafts, schedule only on approval\n\n- Create and edit Typefully drafts freely: plain drafting is your normal mode. Never set `publish_at` (which schedules or publishes a post) unless the user has explicitly asked to schedule or publish; propose the time in the thread and let them confirm.\n- Deleting a draft, comment, or thread is permanent, so only do it when the user explicitly asks.\n\n## 4. Draft in Notion when that's the destination\n\n- When the user wants a piece drafted in Notion, create it as a new page where they direct you (find the right page or database with the Notion search tools if you don't have it), then reply with the link.\n- Do the same for any long piece you're asked to write, like a longform blog post or an article a thread will be cut from, even when the user didn't name a destination: share it as a Notion page and reply with the link plus a short summary. A page is easier to read and digest than a long in-thread message.\n\n## 5. Check the draft before proposing it\n\n- Before proposing any social draft in the thread, run `lint_against_style` with the draft text and the target platform as the surface, and fix what it flags. Do this for each platform version when a piece targets several.\n- On the final draft of a piece (not every revision), delegate to the `reviewer` subagent. It runs with fresh context and can't see this thread, so pack the full draft plus the target platform and any voice or audience context into its `message`, including the platform norms that matter for the piece. It loads its own rubric and returns a verdict.\n- Address the issues it returns, then propose the draft in the thread and iterate there. Keep your own messages short; let the work speak.\n\n## 6. Store files in Blob when durable storage is wanted\n\nThis is separate from Typefully and Notion: Blob is for files, like exporting a finished thread as Markdown, saving an image before uploading it to a draft, or keeping anything that should be reachable by URL.\n\n- `upload_asset` stores text or base64-encoded binary content.\n- `list_assets`, `get_asset_info`, and `download_asset` browse, inspect, and read assets back.\n- `delete_asset` permanently deletes a file. It requires the user's approval, so only call it when they explicitly ask.\n\n# Notes\n\n- Don't fabricate links, quotes, statistics, handles, or draft IDs. If the source material doesn't cover something, say so and ask.\n- Remember standing preferences. When a user states a durable preference (\"always draft for the X and LinkedIn set\", \"keep threads under 8 posts\"), persist it: call `get_user_preferences`, merge the new note into the document, and `save_user_preferences` with the full result. Don't save one-off instructions for a single task. Use `clear_user_preferences` only when the user asks to reset them. Preferences are per-user and private to that user.\n",
- "language": "markdown",
- "relativePath": "agent/instructions.md"
- },
- {
- "contents": "import { defineSandbox } from \"eve/sandbox\";\nimport { vercel } from \"eve/sandbox/vercel\";\n\n/**\n * Agent sandbox configuration.\n *\n * @remarks\n * Pins the hosted Vercel Sandbox backend for both local development and production, so the\n * same environment runs everywhere. Running locally requires the project to be linked and\n * authenticated to Vercel.\n *\n * @see {@link https://vercel.com/docs/sandbox | Vercel Sandbox}\n */\nexport default defineSandbox({\n backend: vercel(),\n});\n",
- "language": "typescript",
- "relativePath": "agent/sandbox.ts"
- },
- {
- "contents": "import { defineSchedule } from \"eve/schedules\";\n\n/**\n * Weekly Typefully analytics digest.\n *\n * @remarks\n * Fires every Monday at 14:00 UTC (Vercel evaluates cron in UTC; adjust the hour for your\n * team's timezone). Task mode runs the agent on the prompt below with the full tool surface;\n * the read-only analytics tools are not approval-gated, so the session never needs to park.\n * Delivery is the `post_analytics_report` tool, which posts to the channel in the\n * `TYPEFULLY_ANALYTICS_CHANNEL` environment variable, so this schedule needs no channel\n * handoff. Trigger it in dev with `curl -X POST http://localhost:3000/eve/v1/dev/schedules/weekly-analytics`.\n *\n * @see {@link https://eve.dev/docs/schedules | eve schedules}\n */\nexport default defineSchedule({\n cron: \"0 14 * * 1\",\n markdown: [\n \"Post this week's Typefully analytics digest to the team.\",\n \"\",\n \"1. Call typefully_list_social_sets and pick the first social set to report on. Note its id and name.\",\n \"2. Call typefully_get_social_set_analytics_followers for that social set id.\",\n \"3. Call typefully_list_social_set_analytics_posts for that social set id.\",\n \"4. Build two tables from what those tools return, every cell a string:\",\n \" - A followers table: one row per account or reporting period, with the follower counts and any change figures the tool provides.\",\n \" - A posts table: one row per post, with an identifier or date, a column linking to the post (use the post URL or permalink the analytics tool returns; do not fabricate a URL), and the engagement metrics the tool provides (impressions, likes, reposts, and so on).\",\n \" Use only fields the tools actually return; do not invent metrics. If there are no posts for the period, pass an empty posts table (no rows) so the report omits it rather than showing an empty table. For followers, if the tool returns nothing, use a single row that says there is no data for the period.\",\n \"5. Call post_analytics_report with a casual summary (1-2 sentences) that includes the social set and the period, the posts table, and the followers table.\",\n \"\",\n \"Do not post anything if the analytics tools error; let the run fail instead so the problem is visible.\",\n ].join(\"\\n\"),\n});\n",
- "language": "typescript",
- "relativePath": "agent/schedules/weekly-analytics.ts"
- },
- {
- "contents": "---\ndescription: \"Use when drafting or editing a post or thread for X (Twitter): voice, hooks, length, threads, hashtags, and links.\"\n---\n\n# X (Twitter) voice & style\n\nWhen writing or editing a post for X:\n\n- Hook first. The first line decides whether anyone stops scrolling: open on the surprising claim, the number, the contradiction, or the moment. No throat-clearing, no \"A thread on…\". A hook isn't clickbait: promise only value the post actually delivers.\n- One idea per post. Free accounts cap at 280 characters. If you have more to say, write a thread, don't cram. Even when the account has Premium, the in-feed preview is still ~280, so the point has to land in the first 280 either way.\n- Plain and punchy. Short sentences. Cut every word that isn't load-bearing. Aim tight; ~240–259 characters tends to travel well. Lowercase openers are fine when they read naturally.\n- Concrete over abstract: a result, a number, a before/after. No vague inspiration.\n- Text carries on X. Add an image or native video only when it carries the point, not for its own sake. Prefer native video over a link out.\n- At most 0–2 real hashtags. 1–2 can help; 3+ tends to hurt. No hashtag walls, no emoji clutter.\n- No engagement bait (\"RT if you agree\", \"read that again\", \"let that sink in\"). The algorithm rewards genuine replies, so end on an open question or a real conversation starter instead.\n- Links suppress reach on X. When a post needs a link, put it in the first reply and say so, rather than in the main post.\n\n## Threads\n\n- The first post must stand on its own and earn the tap: it's a hook, not a table of contents.\n- One beat per post; each should be worth reading even out of context.\n- Keep them scrolling with small expansion hooks every few posts.\n- Number posts (`1/`, `2/`) only for longer threads where it aids the reader; don't force it.\n- Close with a payoff or a single clear takeaway, not \"follow me for more\".\n\n## Structure\n\n1. Hook: the surprising claim or the moment, line one.\n2. Turn: the tension, or the thing most people get wrong.\n3. Payoff: what you learned, with a concrete detail.\n4. Close: one takeaway or a genuine question.\n\n## References\n\n- `references/best-practices.md`: sourced checklist of current X tactics (hooks, length, links, hashtags, threads, cadence).\n- `references/post-specs.md`: concrete specs: character limits, hashtag norms, media, links.\n- `references/banned-words.json`: words to avoid. Read it once for awareness, then run the `lint_against_style` tool (surface `x`) on your draft before proposing it to the writer.\n\nGeneral prose quality (AI-tell phrases to avoid, plain-English word swaps) is covered by the `writing-quality` skill; apply it to every draft alongside this one.\n",
- "language": "markdown",
- "relativePath": "agent/skills/x-style/SKILL.md"
- },
- {
- "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Fresh-context web-research subagent.\n *\n * @remarks\n * The root delegates here when a task needs an outside fact: a statistic, a competitor detail,\n * a primary-source link, or a claim to verify. The researcher runs in a fresh child session and\n * inherits none of the root's skills, connections, or tools — only the framework default harness,\n * whose `web_search` and `web_fetch` cover web research with no extra wiring. It works solely\n * from what the root packs into `message` plus what it fetches, so every claim must be grounded\n * in a real source: the root weaves in only cited `findings` and surfaces `gaps` to the user.\n *\n * `description` is what the root reads to decide when to delegate; `outputSchema` makes the\n * findings a structured, cited result it can act on directly.\n *\n * @see The research methodology and output contract in this folder's `instructions.md`.\n */\nexport default defineAgent({\n description:\n \"Research a topic on the open web for facts, statistics, primary sources, and links the \" +\n \"caller doesn't already have. Runs refined searches against reliable sources and returns \" +\n \"cited findings with confidence levels, plus the gaps it couldn't verify. The caller \" +\n \"passes the question and any known context in the message.\",\n model: \"openai/gpt-5.6-terra\",\n outputSchema: {\n additionalProperties: false,\n properties: {\n findings: {\n description:\n \"One entry per verified factual claim; every entry carries at least one real source.\",\n items: {\n additionalProperties: false,\n properties: {\n claim: {\n description:\n \"A single, specific factual claim the draft can rely on.\",\n type: \"string\",\n },\n confidence: {\n description:\n \"'high' = multiple strong independent sources; 'low' = single or weaker source.\",\n enum: [\"high\", \"medium\", \"low\"],\n type: \"string\",\n },\n notes: {\n description:\n \"Caveats: date-sensitivity, scope limits, or where sources disagree.\",\n type: \"string\",\n },\n sources: {\n description:\n \"The real, fetched sources backing the claim; never empty, never invented.\",\n items: {\n additionalProperties: false,\n properties: {\n title: {\n description: \"The source's title or publication name.\",\n type: \"string\",\n },\n url: {\n description: \"The source URL, as visited.\",\n type: \"string\",\n },\n },\n required: [\"url\", \"title\"],\n type: \"object\",\n },\n minItems: 1,\n type: \"array\",\n },\n },\n required: [\"claim\", \"sources\", \"confidence\", \"notes\"],\n type: \"object\",\n },\n type: \"array\",\n },\n gaps: {\n description:\n \"What could not be found or verified; surfaced to the caller rather than guessed at.\",\n items: { type: \"string\" },\n type: \"array\",\n },\n summary: {\n description:\n \"A 1-3 sentence synthesis of what the research establishes, for the root to scan first.\",\n type: \"string\",\n },\n },\n required: [\"summary\", \"findings\", \"gaps\"],\n type: \"object\",\n },\n});\n",
- "language": "typescript",
- "relativePath": "agent/subagents/researcher/agent.ts"
- },
- {
- "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Fresh-context draft-review subagent.\n *\n * @remarks\n * The root delegates here for a final, unbiased pass over a finished draft before proposing it\n * to the user. The reviewer runs in a fresh child session and inherits none of the root's\n * skills, connections, or tools — it carries its own copy of the `writing-quality` skill (and\n * its own sandbox to read that skill's references), so the root passes only the draft and any\n * voice or audience context in `message`. A reviewer that never saw the sources or the drafting\n * reasoning catches the AI-tells, bloated wording, and structure misses that self-review\n * rationalizes away. The skill copy under this folder's `skills/` is duplicated byte-for-byte\n * from the root's on purpose; keep the two identical when editing either.\n *\n * `description` is what the root reads to decide when to delegate; `outputSchema` makes the\n * verdict a structured result it can act on directly.\n *\n * @see The review rubric and verdict contract in this folder's `instructions.md`.\n */\nexport default defineAgent({\n description:\n \"Review a finished social post or thread draft with fresh context against the \" +\n \"writing-quality rubric (AI-tells, plain English, hook, structure, platform fit, voice) \" +\n \"before it goes to the user. The caller passes the full draft plus the target platform \" +\n \"and any voice or audience context in the message; the reviewer loads its own rubric \" +\n \"and returns a verdict with concrete issues.\",\n model: \"anthropic/claude-fable-5\",\n outputSchema: {\n additionalProperties: false,\n properties: {\n issues: {\n description:\n \"One entry per concrete problem; empty when the verdict is 'ready'.\",\n items: {\n additionalProperties: false,\n properties: {\n fix: {\n description: \"A concrete suggested change.\",\n type: \"string\",\n },\n quote: {\n description: \"The offending excerpt, quoted from the draft.\",\n type: \"string\",\n },\n rule: {\n description: \"The rubric rule or reference the excerpt breaks.\",\n type: \"string\",\n },\n severity: { enum: [\"high\", \"medium\", \"low\"], type: \"string\" },\n },\n required: [\"severity\", \"rule\", \"quote\", \"fix\"],\n type: \"object\",\n },\n type: \"array\",\n },\n verdict: {\n description:\n \"'ready' = clean enough to send as-is; 'revise' = fix the issues first.\",\n enum: [\"ready\", \"revise\"],\n type: \"string\",\n },\n },\n required: [\"verdict\", \"issues\"],\n type: \"object\",\n },\n});\n",
- "language": "typescript",
- "relativePath": "agent/subagents/reviewer/agent.ts"
- },
- {
- "contents": "import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\n\n/**\n * Escape regular-expression metacharacters so a banned word is matched literally.\n *\n * @remarks\n * Banned words are read from a JSON file and interpolated into a `RegExp`. Without escaping,\n * an entry containing metacharacters could raise a syntax error or, worse, a\n * catastrophic-backtracking pattern (ReDoS) evaluated against caller-supplied `text`.\n * Escaping forces a literal, linear-time match.\n *\n * @param value - Raw banned word.\n * @returns The word with all regex metacharacters backslash-escaped.\n */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Build a case-insensitive whole-word matcher for one banned entry.\n *\n * @remarks\n * A `\\b` boundary is only added at an edge whose character is a word character; `\\b` next to\n * punctuation (an entry like `\"agree?\"`) can never match, so such edges are left unanchored\n * instead of silently disabling the entry.\n *\n * @param value - Raw banned entry.\n * @returns A regex matching the entry literally, bounded where word boundaries exist.\n */\nconst STARTS_WITH_WORD_CHAR = /^\\w/;\nconst ENDS_WITH_WORD_CHAR = /\\w$/;\n\nfunction toMatcher(value: string): RegExp {\n const leading = STARTS_WITH_WORD_CHAR.test(value) ? \"\\\\b\" : \"\";\n const trailing = ENDS_WITH_WORD_CHAR.test(value) ? \"\\\\b\" : \"\";\n return new RegExp(`${leading}${escapeRegExp(value)}${trailing}`, \"i\");\n}\n\n/**\n * Maximum draft length accepted, in characters.\n *\n * @remarks\n * Bounds the work done per call and the size of accepted input. Comfortably larger than any\n * realistic draft for the supported surfaces.\n */\nconst MAX_TEXT_LENGTH = 100_000;\n\n/**\n * Schema for a `banned-words.json` file: a flat array of strings.\n *\n * @remarks\n * Parsed content that does not match (a non-array, or non-string elements) is rejected and\n * treated as an empty list rather than trusted.\n */\nconst BANNED_WORDS_SCHEMA = z.array(z.string());\n\n/**\n * Tool that checks a draft against the active surface's banned-words list.\n *\n * @remarks\n * The banned-words list lives in the matching style skill at `references/banned-words.json`\n * and is read at runtime through the skill handle. The `surface` input is constrained to a\n * fixed enum, so the resolved skill id and file path can never be influenced by the caller.\n * Any failure to resolve, read, parse, or validate the list is treated as \"no banned words\"\n * rather than failing the check. Run it before proposing a draft to the writer.\n */\nexport default defineTool({\n description:\n \"Check a draft against the surface's banned-words list and return any violations. \" +\n \"Run before proposing a draft to the writer.\",\n /**\n * Scan `text` for any banned word defined by the surface's style skill.\n *\n * @param input - Validated tool input.\n * @param input.surface - Content surface whose style skill supplies the banned-words list.\n * @param input.text - Draft text to scan.\n * @param ctx - Tool runtime context, used to read the skill's reference files.\n * @returns `ok` (true when no banned words are present) and human-readable `violations`.\n */\n async execute({ surface, text }, ctx) {\n let banned: string[] = [];\n try {\n const raw = await ctx\n .getSkill(`${surface}-style`)\n .file(\"references/banned-words.json\")\n .text();\n const parsed = BANNED_WORDS_SCHEMA.safeParse(JSON.parse(raw));\n if (parsed.success) {\n banned = [...new Set(parsed.data.map((w) => w.trim()).filter(Boolean))];\n }\n } catch {\n banned = [];\n }\n\n const hits = banned.filter((w) => toMatcher(w).test(text));\n return {\n ok: hits.length === 0,\n violations: hits.map(\n (w) => `Avoid \"${w}\" per the ${surface} style guide.`\n ),\n };\n },\n inputSchema: z.object({\n surface: z.enum([\"x\", \"linkedin\", \"threads\", \"bluesky\", \"mastodon\"]),\n text: z.string().min(1).max(MAX_TEXT_LENGTH),\n }),\n});\n",
- "language": "typescript",
- "relativePath": "agent/tools/lint_against_style.ts"
- }
- ]
- },
- "weather-agent-fixture": {
- "sourceRevision": "b502c1e76d574cc2c81d5aab49855fca4c1633ff",
- "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.ts
index 3b78af507..e5cebaa07 100644
--- a/apps/docs/lib/templates/manifest.ts
+++ b/apps/docs/lib/templates/manifest.ts
@@ -1,6 +1,5 @@
-// 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.
+// Curation manifest for the templates gallery. Repository content is resolved
+// from this manifest during docs development and production builds.
export type TemplateCategory = "Chat" | "Collaboration" | "Example" | "Marketing";
diff --git a/apps/docs/lib/templates/readme-links.test.ts b/apps/docs/lib/templates/readme-links.test.ts
new file mode 100644
index 000000000..f24ce9e47
--- /dev/null
+++ b/apps/docs/lib/templates/readme-links.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveReadmeHref, sanitizeReadmeHref } from "./readme-links";
+
+const sourceRevisionHref =
+ "https://github.com/vercel/eve/tree/0123456789abcdef/apps/fixtures/weather-agent";
+
+describe("resolveReadmeHref", () => {
+ it("resolves relative links from the template directory", () => {
+ expect(resolveReadmeHref("docs/setup.md", sourceRevisionHref)).toBe(
+ `${sourceRevisionHref}/docs/setup.md`,
+ );
+ });
+
+ it("resolves repository-root links from the pinned revision", () => {
+ expect(resolveReadmeHref("/CONTRIBUTING.md", sourceRevisionHref)).toBe(
+ "https://github.com/vercel/eve/tree/0123456789abcdef/CONTRIBUTING.md",
+ );
+ });
+
+ it("preserves page anchors and safe absolute links", () => {
+ expect(resolveReadmeHref("#quick-start", sourceRevisionHref)).toBe("#quick-start");
+ expect(resolveReadmeHref("https://eve.dev/docs", sourceRevisionHref)).toBe(
+ "https://eve.dev/docs",
+ );
+ });
+
+ it("rejects relative links when the source is not a pinned GitHub tree", () => {
+ expect(resolveReadmeHref("docs/setup.md", "https://example.com/template")).toBeUndefined();
+ });
+});
+
+describe("sanitizeReadmeHref", () => {
+ it("allows web, email, telephone, relative, and anchor links", () => {
+ expect(sanitizeReadmeHref("https://eve.dev")).toBe("https://eve.dev/");
+ expect(sanitizeReadmeHref("mailto:[email protected]")).toBe("mailto:[email protected]");
+ expect(sanitizeReadmeHref("tel:+15555555555")).toBe("tel:+15555555555");
+ expect(sanitizeReadmeHref("docs/setup.md")).toBe("docs/setup.md");
+ expect(sanitizeReadmeHref("#setup")).toBe("#setup");
+ });
+
+ it("rejects unsafe and protocol-relative URLs", () => {
+ expect(sanitizeReadmeHref("javascript:alert(1)")).toBeUndefined();
+ expect(sanitizeReadmeHref("data:text/html,hello")).toBeUndefined();
+ expect(sanitizeReadmeHref("//example.com/path")).toBeUndefined();
+ });
+});
diff --git a/apps/docs/lib/templates/readme-links.ts b/apps/docs/lib/templates/readme-links.ts
new file mode 100644
index 000000000..e577ca4f2
--- /dev/null
+++ b/apps/docs/lib/templates/readme-links.ts
@@ -0,0 +1,84 @@
+const SAFE_ABSOLUTE_PROTOCOLS = new Set(["http:", "https:", "mailto:", "tel:"]);
+
+export const resolveReadmeHref = (
+ href: string | undefined,
+ sourceRevisionHref: string,
+): string | undefined => {
+ const sanitizedHref = sanitizeReadmeHref(href);
+ if (!sanitizedHref || sanitizedHref.startsWith("#") || isAbsoluteHref(sanitizedHref)) {
+ return sanitizedHref;
+ }
+
+ const bases = getGitHubBases(sourceRevisionHref);
+ if (!bases) {
+ return undefined;
+ }
+
+ const base = sanitizedHref.startsWith("/") ? bases.repository : bases.directory;
+ return new URL(sanitizedHref.replace(/^\/+/, ""), `${base.replace(/\/+$/, "")}/`).toString();
+};
+
+export const sanitizeReadmeHref = (href: string | undefined): string | undefined => {
+ if (!href) {
+ return undefined;
+ }
+
+ const normalized = stripAsciiControlCharacters(href.trim());
+ if (!normalized || normalized.startsWith("//")) {
+ return undefined;
+ }
+ if (normalized.startsWith("#")) {
+ return normalized;
+ }
+
+ const protocolMatch = normalized.match(/^([a-z][a-z\d+.-]*):/i);
+ if (!protocolMatch) {
+ return normalized;
+ }
+
+ try {
+ const url = new URL(normalized);
+ return SAFE_ABSOLUTE_PROTOCOLS.has(url.protocol) ? url.toString() : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const isAbsoluteHref = (href: string): boolean =>
+ /^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("//");
+
+const getGitHubBases = (
+ sourceRevisionHref: string,
+): { directory: string; repository: string } | null => {
+ let url: URL;
+ try {
+ url = new URL(sourceRevisionHref);
+ } catch {
+ return null;
+ }
+
+ if (url.hostname !== "github.com") {
+ return null;
+ }
+
+ const [owner, repo, view, revision] = url.pathname.split("/").filter(Boolean);
+ if (!owner || !repo || view !== "tree" || !revision) {
+ return null;
+ }
+
+ return {
+ directory: url.toString(),
+ repository: new URL(`/${owner}/${repo}/tree/${revision}`, url.origin).toString(),
+ };
+};
+
+const stripAsciiControlCharacters = (value: string): string => {
+ let normalized = "";
+ for (const character of value) {
+ const codePoint = character.codePointAt(0);
+ if (codePoint !== undefined && codePoint > 0x1f && codePoint !== 0x7f) {
+ normalized += character;
+ }
+ }
+ return normalized;
+};
diff --git a/apps/docs/lib/templates/sync-core.test.ts b/apps/docs/lib/templates/sync-core.test.ts
index b439041ad..7e981f985 100644
--- a/apps/docs/lib/templates/sync-core.test.ts
+++ b/apps/docs/lib/templates/sync-core.test.ts
@@ -1,13 +1,7 @@
import { describe, expect, it } from "vitest";
import type { TemplateGitHubSource } from "./manifest";
-import {
- commitUrl,
- contentsUrl,
- decodeContentsResponse,
- languageForPath,
- sortTemplateFiles,
-} from "./sync-core";
+import { commitUrl, languageForPath, rawContentsUrl, sortTemplateFiles } from "./sync-core";
const source: TemplateGitHubSource = {
owner: "vercel-labs",
@@ -36,10 +30,10 @@ describe("commitUrl", () => {
});
});
-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",
+describe("rawContentsUrl", () => {
+ it("pins the raw file to the resolved sha", () => {
+ expect(rawContentsUrl(source, "abc123", "agent/agent.ts")).toBe(
+ "https://raw.githubusercontent.com/vercel-labs/eve-chat-template/abc123/agent/agent.ts",
);
});
@@ -50,32 +44,8 @@ describe("contentsUrl", () => {
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/,
+ expect(rawContentsUrl(monorepo, "abc123", "agent/agent.ts")).toBe(
+ "https://raw.githubusercontent.com/vercel/eve/abc123/apps/fixtures/weather-agent/agent/agent.ts",
);
});
});
diff --git a/apps/docs/lib/templates/sync-core.ts b/apps/docs/lib/templates/sync-core.ts
index d9c71ff8e..6fbddfe4c 100644
--- a/apps/docs/lib/templates/sync-core.ts
+++ b/apps/docs/lib/templates/sync-core.ts
@@ -2,13 +2,7 @@ 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;
-}
+const GITHUB_RAW = "https://raw.githubusercontent.com";
export const languageForPath = (path: string): TemplateFile["language"] => {
if (path.endsWith(".md") || path.endsWith(".mdx")) return "markdown";
@@ -24,37 +18,14 @@ const encodePath = (path: string): string => path.split("/").map(encodeURICompon
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 = (
+/** Immutable raw URL for one template file at a resolved commit SHA. */
+export const rawContentsUrl = (
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,
- };
+ return `${GITHUB_RAW}/${encodeURIComponent(source.owner)}/${encodeURIComponent(source.repo)}/${encodeURIComponent(sha)}/${encodePath(path)}`;
};
export const sortTemplateFiles = (files: TemplateFile[]): TemplateFile[] =>
diff --git a/apps/docs/package.json b/apps/docs/package.json
index 7cdb82ad9..7cc6ab7d9 100644
--- a/apps/docs/package.json
+++ b/apps/docs/package.json
@@ -5,8 +5,8 @@
"description": "eve documentation site.",
"type": "module",
"scripts": {
- "build": "pnpm run registry:check && next build",
- "dev": "next dev --turbo",
+ "build": "pnpm run registry:check && pnpm run templates:sync && next build",
+ "dev": "pnpm run templates:sync && next dev --turbo",
"start": "next start",
"postinstall": "fumadocs-mdx",
"translate": "npx @vercel/geistdocs translate",
diff --git a/apps/docs/scripts/sync-templates.ts b/apps/docs/scripts/sync-templates.ts
index 9ce2168e1..aded76a1c 100644
--- a/apps/docs/scripts/sync-templates.ts
+++ b/apps/docs/scripts/sync-templates.ts
@@ -5,10 +5,9 @@ import type { TemplateFile } from "../lib/templates/compose";
import { templateManifest } from "../lib/templates/manifest";
import {
commitUrl,
- contentsUrl,
- decodeContentsResponse,
+ languageForPath,
+ rawContentsUrl,
sortTemplateFiles,
- type GitHubContentsResponse,
} from "../lib/templates/sync-core";
const token = process.env.GITHUB_TOKEN;
@@ -35,38 +34,73 @@ const githubJson = async <T>(url: string, notFoundMessage: string): Promise<T> =
return (await response.json()) as T;
};
+const githubText = async (url: string, notFoundMessage: string): Promise<string> => {
+ const response = await fetch(url);
+ if (response.status === 404) {
+ throw new Error(notFoundMessage);
+ }
+ if (!response.ok) {
+ throw new Error(`GitHub raw content request failed (${response.status}) for ${url}`);
+ }
+ return response.text();
+};
+
console.log(`Syncing templates from GitHub (${token ? "authenticated" : "unauthenticated"})`);
-const templates: Record<string, { sourceRevision: string; files: TemplateFile[] }> = {};
+const syncedTemplates = await Promise.all(
+ templateManifest.map(async (entry) => {
+ const { github } = entry;
+ const commit = await githubJson<{ sha: string }>(
+ commitUrl(github),
+ `Ref "${github.ref}" not found in ${github.owner}/${github.repo} (template "${entry.slug}")`,
+ );
-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, readme] = await Promise.all([
+ Promise.all(
+ entry.files.map(
+ async (relativePath): Promise<TemplateFile> => ({
+ contents: await githubText(
+ rawContentsUrl(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}`,
+ ),
+ language: languageForPath(relativePath),
+ relativePath,
+ }),
+ ),
+ ),
+ githubText(
+ rawContentsUrl(github, commit.sha, "README.md"),
+ `README.md not found for template "${entry.slug}" in ` +
+ `${github.owner}/${github.repo}@${commit.sha}`,
+ ),
+ ]);
- 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));
- }
+ return {
+ slug: entry.slug,
+ data: {
+ files: sortTemplateFiles(files),
+ readme,
+ sourceRevision: commit.sha,
+ },
+ log: `${entry.slug} ${github.ref} → ${commit.sha.slice(0, 7)} (${files.length} files)`,
+ };
+ }),
+);
+
+const templates = Object.fromEntries(
+ syncedTemplates.map(({ data, slug }) => [slug, data]),
+) satisfies Record<string, { readme: string; sourceRevision: string; files: TemplateFile[] }>;
- templates[entry.slug] = { sourceRevision: commit.sha, files: sortTemplateFiles(files) };
- console.log(`${entry.slug} ${github.ref} → ${commit.sha.slice(0, 7)} (${files.length} files)`);
-}
+for (const template of syncedTemplates) console.log(template.log);
const output = {
- $comment:
- "Generated by scripts/sync-templates.ts. Do not edit. Run: pnpm --filter eve-docs templates:sync",
+ $comment: "Generated during the docs build by scripts/sync-templates.ts. Do not edit.",
templates,
};
-const outputPath = join(import.meta.dirname, "../lib/templates/generated/templates.json");
+const outputPath = join(import.meta.dirname, "../.template-data/templates.json");
await mkdir(dirname(outputPath), { recursive: true });
await writeFile(outputPath, `${JSON.stringify(output, null, 2)}\n`);
console.log(`Wrote ${outputPath}`);