Skip to content
TypeScript

fix(web,mobile): render Codex citations and artifact templates (#8584)

Yash Singhc1e70b5f8c93
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index 6eaa7aadfd6..d485aa8279f 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -1,4 +1,8 @@
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
+import {
+ appendCodexArtifactTemplateUsePrompt,
+ type CodexArtifactTemplate,
+} from "@t3tools/client-runtime/codex-artifact-templates";
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import type { LegendListRef } from "@legendapp/list/react-native";
@@ -260,6 +264,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
+ const draftMessageRef = useRef(props.draftMessage);
+ draftMessageRef.current = props.draftMessage;
const composerOverlayRef = useRef<View>(null);
const listRef = useRef<LegendListRef>(null);
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
@@ -601,6 +607,22 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
composerEditorRef.current?.blur();
}, []);
+ const handleUseArtifactTemplate = useCallback(
+ (template: CodexArtifactTemplate) => {
+ const currentDraft = draftMessageRef.current;
+ const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
+ if (nextDraft !== currentDraft) {
+ draftMessageRef.current = nextDraft;
+ props.onChangeDraftMessage(nextDraft);
+ }
+ requestAnimationFrame(() => {
+ composerEditorRef.current?.focus();
+ composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
+ });
+ },
+ [props.onChangeDraftMessage],
+ );
+
const handleScrollToEnd = useCallback(() => {
void Haptics.selectionAsync();
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
@@ -677,6 +699,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
onEndFollowEnabledChange={setEndFollowEnabled}
skills={selectedProviderSkills}
+ onUseArtifactTemplate={handleUseArtifactTemplate}
loadEarlier={props.loadEarlier ?? null}
/>
</View>
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index a3e6c8b620c..1da3f35cb59 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -10,12 +10,20 @@ import type {
ThreadId,
TurnId,
} from "@t3tools/contracts";
+import {
+ codexArtifactTemplatePresentationLabel,
+ type CodexArtifactTemplate,
+} from "@t3tools/client-runtime/codex-artifact-templates";
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
+import {
+ renderCodexFileCitationsAsMarkdown,
+ splitCodexArtifactTemplateMarkdown,
+} from "@t3tools/client-runtime/codex-markdown-directives";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
-import { SymbolView } from "../../components/AppSymbol";
+import { SymbolView, type AppSymbolName } from "../../components/AppSymbol";
import { HeaderHeightContext } from "@react-navigation/elements";
import { useFocusEffect, useNavigation } from "@react-navigation/native";
import {
@@ -190,6 +198,7 @@ export interface ThreadFeedProps {
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
+ readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: {
readonly loading: boolean;
@@ -568,6 +577,115 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
);
});
+const ARTIFACT_TEMPLATE_SYMBOL_BY_KIND: Record<
+ CodexArtifactTemplate["artifactKind"],
+ AppSymbolName
+> = {
+ document: "doc.text",
+ presentation: "chart.bar.xaxis",
+ spreadsheet: "chart.bar.xaxis",
+ site: "safari",
+ "google-docs": "doc.text",
+ "google-slides": "chart.bar.xaxis",
+ "google-sheets": "chart.bar.xaxis",
+ image: "camera",
+ email: "text.bubble",
+ slack: "text.bubble",
+};
+
+function ArtifactTemplateCard(props: {
+ readonly template: CodexArtifactTemplate;
+ readonly onUse?: ((template: CodexArtifactTemplate) => void) | undefined;
+}) {
+ return (
+ <View className="my-2 min-w-0 flex-row items-center gap-3 rounded-2xl border border-border bg-card px-3 py-3">
+ <View className="relative h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-border bg-subtle">
+ <SymbolView
+ name={ARTIFACT_TEMPLATE_SYMBOL_BY_KIND[props.template.artifactKind]}
+ size={20}
+ tintColorClassName="accent-foreground-muted"
+ type="monochrome"
+ />
+ <View className="absolute -right-1 -bottom-1 h-4 w-4 items-center justify-center rounded-full bg-fuchsia-500">
+ <SymbolView
+ name={{ ios: "sparkles", android: "auto_awesome" }}
+ size={9}
+ tintColor="white"
+ type="monochrome"
+ />
+ </View>
+ </View>
+ <View className="min-w-0 flex-1">
+ <Text className="font-t3-bold text-sm text-foreground" numberOfLines={1}>
+ {props.template.displayName}
+ </Text>
+ <Text className="text-xs text-foreground-muted">
+ {codexArtifactTemplatePresentationLabel(props.template.artifactKind)}
+ </Text>
+ </View>
+ {props.onUse ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Use ${props.template.displayName} template`}
+ className="min-h-9 justify-center rounded-lg border border-border bg-subtle px-3 active:opacity-65"
+ onPress={() => props.onUse?.(props.template)}
+ >
+ <Text className="font-t3-bold text-xs text-foreground">Use template</Text>
+ </Pressable>
+ ) : null}
+ </View>
+ );
+}
+
+const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
+ readonly markdown: string;
+ readonly markdownStyles: MarkdownStyleSet;
+ readonly onLinkPress: (href: string) => void;
+ readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
+ readonly renderImage: MarkdownImageRenderer;
+ readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
+}) {
+ const segments = useMemo(
+ () => splitCodexArtifactTemplateMarkdown(props.markdown),
+ [props.markdown],
+ );
+
+ return segments.map((segment) => {
+ if (segment.kind === "artifact-template") {
+ return (
+ <ArtifactTemplateCard
+ key={`artifact-template:${segment.sourceOffset}`}
+ template={segment.template}
+ onUse={props.onUseArtifactTemplate}
+ />
+ );
+ }
+ if (segment.markdown.trim().length === 0) return null;
+
+ const markdown = renderCodexFileCitationsAsMarkdown(segment.markdown);
+ return hasNativeSelectableMarkdownText() ? (
+ <SelectableMarkdownText
+ key={`markdown:${segment.sourceOffset}`}
+ markdown={markdown}
+ skills={props.skills}
+ textStyle={props.markdownStyles.nativeTextStyle}
+ onLinkPress={props.onLinkPress}
+ renderImage={props.renderImage}
+ />
+ ) : (
+ <Markdown
+ key={`markdown:${segment.sourceOffset}`}
+ options={{ gfm: true }}
+ renderers={props.markdownStyles.renderers}
+ styles={props.markdownStyles.styles}
+ theme={props.markdownStyles.theme}
+ >
+ {markdown}
+ </Markdown>
+ );
+ });
+});
+
function MarkdownCodeBlock(props: {
readonly backgroundColor: string;
readonly borderColor: string;
@@ -1099,7 +1217,7 @@ function useMarkdownStyles(
function renderFeedEntry(
info: { item: ThreadFeedEntry; index: number },
- props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
+ props: Pick<ThreadFeedProps, "environmentId" | "onUseArtifactTemplate" | "skills"> & {
readonly copiedRowId: string | null;
readonly expandedWorkRows: Record<string, boolean>;
readonly terminalAssistantMessageIds: ReadonlySet<string>;
@@ -1162,6 +1280,7 @@ function renderFeedEntry(
if (entry.type === "message") {
const { message } = entry;
const isUser = message.role === "user";
+ const renderedText = message.text;
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
const attachments = message.attachments ?? [];
@@ -1171,7 +1290,7 @@ function renderFeedEntry(
// children during the unclamped pass and never moves them once the width
// is clamped, so the paragraphs around the block end up drawn on top of
// each other. Pinning the width removes that pass.
- const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
+ const hasWideBlock = hasWideMarkdownBlock(renderedText, WIDE_MARKDOWN_BLOCK_OPTIONS);
const assistantTurnStillInProgress =
message.role === "assistant" &&
props.unsettledTurnId !== null &&
@@ -1251,7 +1370,7 @@ function renderFeedEntry(
// Skip empty assistant messages (no text, no attachments) — they would
// render as an orphaned timestamp and break adjacent activity-group merging.
- if (message.text.trim().length === 0 && attachments.length === 0) {
+ if (renderedText.trim().length === 0 && attachments.length === 0) {
return null;
}
@@ -1261,25 +1380,15 @@ function renderFeedEntry(
className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}
{...(enterAnimated ? { entering: FadeIn.duration(220) } : {})}
>
- {message.text.trim().length > 0 ? (
- hasNativeSelectableMarkdownText() ? (
- <SelectableMarkdownText
- markdown={message.text}
- skills={props.skills}
- textStyle={styles.nativeTextStyle}
- onLinkPress={props.onMarkdownLinkPress}
- renderImage={props.renderMarkdownImage}
- />
- ) : (
- <Markdown
- options={{ gfm: true }}
- renderers={styles.renderers}
- styles={styles.styles}
- theme={styles.theme}
- >
- {message.text}
- </Markdown>
- )
+ {renderedText.trim().length > 0 ? (
+ <AssistantMarkdownContent
+ markdown={renderedText}
+ markdownStyles={styles}
+ onLinkPress={props.onMarkdownLinkPress}
+ onUseArtifactTemplate={props.onUseArtifactTemplate}
+ renderImage={props.renderMarkdownImage}
+ skills={props.skills}
+ />
) : null}
{attachments.map((attachment) => {
return isImageAttachment(attachment) ? (
@@ -1304,7 +1413,7 @@ function renderFeedEntry(
<View className="mt-1 flex-row items-center gap-1">
<CopyTextButton
accessibilityLabel="Copy message"
- text={message.text}
+ text={renderedText}
tintColor={iconSubtleColor}
buttonSize={28}
iconSize={13}
@@ -2192,6 +2301,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
reviewCommentBubbleWidth,
userBubbleMaxWidth,
skills: props.skills,
+ onUseArtifactTemplate: props.onUseArtifactTemplate,
})}
</Animated.View>
),
@@ -2214,6 +2324,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleWorkGroup,
onToggleWorkRow,
props.environmentId,
+ props.onUseArtifactTemplate,
props.skills,
renderMarkdownImage,
],
diff --git a/apps/web/src/components/ChatMarkdown.test.tsx b/apps/web/src/components/ChatMarkdown.test.tsx
index 2ca9ad4ae31..7e32e48d585 100644
--- a/apps/web/src/components/ChatMarkdown.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.test.tsx
@@ -102,6 +102,214 @@ describe("ChatMarkdown file option chips", () => {
expect(html).toContain('aria-haspopup="menu"');
expect(html).toContain("select-text");
});
+
+ it.each([true, false])(
+ "renders Codex file citations as file chips with parseRawHtml=%s",
+ (parseRawHtml) => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={
+ 'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx" purpose="output"}.'
+ }
+ lineBreaks={!parseRawHtml}
+ parseRawHtml={parseRawHtml}
+ />,
+ );
+
+ expect(html).not.toContain("codex-file-citation");
+ expect(html).toContain("chat-markdown-file-link");
+ expect(html).toContain(
+ 'data-markdown-copy="[report.xlsx](/tmp/project/outputs/report.xlsx)"',
+ );
+ expect(html).toContain("report.xlsx");
+ },
+ );
+
+ it("leaves an unfinished streaming citation visible until it is complete", () => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={'Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"'}
+ isStreaming
+ />,
+ );
+
+ expect(html).toContain(":codex-file-citation");
+ expect(html).not.toContain("chat-markdown-file-link");
+ });
+
+ it("leaves malformed and similarly named file directives literal", () => {
+ for (const text of [
+ ':codex-file-citation{purpose="output"}',
+ ':codex-file-citation-extra{path="/tmp/project/outputs/report.xlsx"}',
+ ]) {
+ const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
+
+ expect(html).toContain(text.replaceAll('"', "&quot;"));
+ expect(html).not.toContain("chat-markdown-file-link");
+ }
+ });
+
+ it("preserves Codex file citation examples inside code", () => {
+ const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={`Example: \`${directive}\`\n\n\`\`\`text\n${directive}\n\`\`\``}
+ />,
+ );
+
+ expect(html.match(/:codex-file-citation/g)).toHaveLength(2);
+ expect(html).not.toContain("chat-markdown-file-link");
+ });
+
+ it("preserves escaped Codex file citations as literal text", () => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={'Example: \\:codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
+ />,
+ );
+
+ expect(html).toContain(":codex-file-citation");
+ expect(html).not.toContain("chat-markdown-file-link");
+ });
+
+ it("does not create a nested link for citations inside link text", () => {
+ const directive = ':codex-file-citation{path="/tmp/project/outputs/report.xlsx"}';
+ const html = renderToStaticMarkup(
+ <ChatMarkdown cwd="/tmp/project" text={`[See ${directive}](https://example.com)`} />,
+ );
+ const renderedText = html.replace(/<[^>]+>/g, "");
+
+ expect(renderedText).toContain("codex-file-citation");
+ expect(html).not.toContain("chat-markdown-file-link");
+ });
+
+ it("renders file citations created by over-indented list recovery", () => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={'- Created :codex-file-citation{path="/tmp/project/outputs/report.xlsx"}'}
+ />,
+ );
+
+ expect(html).not.toContain("<pre>");
+ expect(html).toContain("Created ");
+ expect(html).toContain("chat-markdown-file-link");
+ expect(html).toContain("report.xlsx");
+ });
+
+ it("disambiguates Codex citations with the same basename", () => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={
+ 'Changed :codex-file-citation{path="/tmp/project/src/index.ts"} and :codex-file-citation{path="/tmp/project/test/index.ts"}.'
+ }
+ />,
+ );
+
+ expect(html).toContain("index.ts · project/src");
+ expect(html).toContain("index.ts · project/test");
+ });
+
+ it("preserves rejected citations created by over-indented list recovery", () => {
+ const malformedHtml = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={'Leading text before list.\n\n- Bad :codex-file-citation{purpose="output"}'}
+ />,
+ );
+ const nestedLinkHtml = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={
+ 'Leading text before list.\n\n- [Bad :codex-file-citation{path="/tmp/project/report.xlsx"}](https://example.com)'
+ }
+ />,
+ );
+ const nestedLinkText = nestedLinkHtml.replace(/<[^>]+>/g, "");
+
+ expect(malformedHtml).toContain(
+ "<li>Bad :codex-file-citation{purpose=&quot;output&quot;}</li>",
+ );
+ expect(nestedLinkText).toContain(
+ "Bad :codex-file-citation{path=&quot;/tmp/project/report.xlsx&quot;}",
+ );
+ });
+});
+
+const ARTIFACT_TEMPLATE_DIRECTIVE =
+ '::artifact-template{skill_name="artifact-template-hello-world" skill_directory="/Users/test/.codex/skills/artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
+
+describe("ChatMarkdown artifact-template cards", () => {
+ it.each([true, false])("renders the Codex result card with parseRawHtml=%s", (parseRawHtml) => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={ARTIFACT_TEMPLATE_DIRECTIVE}
+ parseRawHtml={parseRawHtml}
+ onUseArtifactTemplate={() => undefined}
+ />,
+ );
+
+ expect(html).not.toContain("::artifact-template");
+ expect(html).toContain("chat-markdown-artifact-template");
+ expect(html).toContain('data-artifact-kind="document"');
+ expect(html).toContain('data-markdown-copy="Hello World (Document template)\n\n"');
+ expect(html).toContain('data-skill-name="artifact-template-hello-world"');
+ expect(html).toContain("Hello World");
+ expect(html).toContain("Document template");
+ expect(html).toContain("Use template");
+ expect(html).not.toContain("<p><div");
+ });
+
+ it("renders a passive card outside a composer-backed timeline", () => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown cwd="/tmp/project" text={ARTIFACT_TEMPLATE_DIRECTIVE} />,
+ );
+
+ expect(html).toContain("chat-markdown-artifact-template");
+ expect(html).not.toContain("Use template");
+ });
+
+ it("leaves malformed and unfinished artifact-template directives literal", () => {
+ const malformed =
+ '::artifact-template{skill_name="artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
+ const unfinished = ARTIFACT_TEMPLATE_DIRECTIVE.slice(0, -1);
+
+ for (const text of [malformed, unfinished]) {
+ const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
+ expect(html).toContain("::artifact-template");
+ expect(html).not.toContain("chat-markdown-artifact-template");
+ }
+ });
+
+ it("leaves escaped and similarly named artifact-template directives literal", () => {
+ for (const text of [
+ `\\${ARTIFACT_TEMPLATE_DIRECTIVE}`,
+ ARTIFACT_TEMPLATE_DIRECTIVE.replace("::artifact-template", "::artifact-template-extra"),
+ ]) {
+ const html = renderToStaticMarkup(<ChatMarkdown cwd="/tmp/project" text={text} />);
+
+ expect(html).toContain("::artifact-template");
+ expect(html).not.toContain("chat-markdown-artifact-template");
+ }
+ });
+
+ it("preserves artifact-template examples inside code", () => {
+ const html = renderToStaticMarkup(
+ <ChatMarkdown
+ cwd="/tmp/project"
+ text={`\`${ARTIFACT_TEMPLATE_DIRECTIVE}\`\n\n\`\`\`text\n${ARTIFACT_TEMPLATE_DIRECTIVE}\n\`\`\``}
+ />,
+ );
+
+ expect(html.match(/::artifact-template/g)).toHaveLength(2);
+ expect(html).not.toContain("chat-markdown-artifact-template");
+ });
});
describe("shouldUseMarkdownFileBrowserPrimaryAction", () => {
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 84fcca40072..a055759e638 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -3,15 +3,23 @@ import {
CheckIcon,
ChevronRightIcon,
CopyIcon,
+ FileSpreadsheetIcon,
+ FileTextIcon,
GlobeIcon,
+ ImageIcon,
InfoIcon,
LightbulbIcon,
+ MailIcon,
Maximize2Icon,
+ MessageSquareIcon,
MessageSquareWarningIcon,
Minimize2Icon,
OctagonAlertIcon,
+ PresentationIcon,
+ SparklesIcon,
TriangleAlertIcon,
WrapTextIcon,
+ type LucideIcon,
} from "lucide-react";
import type {
EnvironmentId,
@@ -24,6 +32,11 @@ import {
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
+import {
+ codexArtifactTemplatePresentationLabel,
+ type CodexArtifactTemplate,
+ type CodexArtifactTemplateKind,
+} from "@t3tools/client-runtime/codex-artifact-templates";
import {
classifyMarkdownImageSource,
markdownImageSourceFragment,
@@ -55,6 +68,12 @@ import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import remarkBreaks from "remark-breaks";
import remarkGfm from "remark-gfm";
import { remarkGithubAlerts } from "../markdown-github-alerts";
+import {
+ artifactTemplateFromHastProperties,
+ CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
+ remarkCodexDirectives,
+ renderCodexFileCitationsAsMarkdown,
+} from "@t3tools/client-runtime/codex-markdown-directives";
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
@@ -156,6 +175,8 @@ interface ChatMarkdownProps {
lineBreaks?: boolean;
/** Parse sanitized raw HTML instead of displaying its source text. */
parseRawHtml?: boolean;
+ /** Append a prompt that invokes a newly created artifact-template skill. */
+ onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
imageBaseDir?: string | undefined;
onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
}
@@ -191,6 +212,64 @@ export function shouldUseMarkdownFileBrowserPrimaryAction(input: {
const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
+const ARTIFACT_TEMPLATE_ICON_BY_KIND = {
+ document: FileTextIcon,
+ presentation: PresentationIcon,
+ spreadsheet: FileSpreadsheetIcon,
+ site: GlobeIcon,
+ "google-docs": FileTextIcon,
+ "google-slides": PresentationIcon,
+ "google-sheets": FileSpreadsheetIcon,
+ image: ImageIcon,
+ email: MailIcon,
+ slack: MessageSquareIcon,
+} satisfies Record<CodexArtifactTemplateKind, LucideIcon>;
+
+function CodexArtifactTemplateCard(props: {
+ readonly template: CodexArtifactTemplate;
+ readonly onUse?: ((template: CodexArtifactTemplate) => void) | undefined;
+}) {
+ const Icon = ARTIFACT_TEMPLATE_ICON_BY_KIND[props.template.artifactKind];
+ const presentationLabel = codexArtifactTemplatePresentationLabel(props.template.artifactKind);
+
+ return (
+ <div
+ role="group"
+ aria-label={`${props.template.displayName} template`}
+ className="chat-markdown-artifact-template my-[0.65rem] flex w-full min-w-0 items-center gap-3 rounded-xl border border-border/70 bg-card/60 px-3 py-2.5 text-foreground shadow-xs"
+ data-artifact-kind={props.template.artifactKind}
+ data-markdown-copy={`${props.template.displayName} (${presentationLabel})\n\n`}
+ data-skill-name={props.template.skillName}
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <span className="relative flex size-9 shrink-0 items-center justify-center rounded-lg border border-border/70 bg-background text-muted-foreground shadow-xs">
+ <Icon aria-hidden className="size-5" />
+ <span className="absolute -right-1 -bottom-1 flex size-4 items-center justify-center rounded-full border border-background bg-fuchsia-500 text-white shadow-xs">
+ <SparklesIcon aria-hidden className="size-2.5" />
+ </span>
+ </span>
+ <span className="min-w-0">
+ <span className="block truncate text-sm font-medium text-foreground">
+ {props.template.displayName}
+ </span>
+ <span className="block text-xs text-muted-foreground">{presentationLabel}</span>
+ </span>
+ </div>
+ {props.onUse ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="shrink-0"
+ onClick={() => props.onUse?.(props.template)}
+ >
+ Use template
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
@@ -280,6 +359,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
+ div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
img: [...(defaultSchema.attributes?.img ?? []), "dataLocalSrc", "dataMarkdownTitle"],
},
protocols: {
@@ -293,6 +373,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS = [
remarkGfm,
remarkGithubAlerts,
remarkNormalizeListItemIndentation,
+ remarkCodexDirectives,
remarkPreserveCodeMeta,
remarkNormalizeLinksAndTagInlineCode,
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
@@ -301,6 +382,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
remarkGfm,
remarkGithubAlerts,
remarkNormalizeListItemIndentation,
+ remarkCodexDirectives,
remarkBreaks,
remarkPreserveCodeMeta,
remarkNormalizeLinksAndTagInlineCode,
@@ -1727,6 +1809,7 @@ function ChatMarkdown({
className,
lineBreaks = false,
parseRawHtml = true,
+ onUseArtifactTemplate,
imageBaseDir,
onImageExpand,
}: ChatMarkdownProps) {
@@ -1793,7 +1876,7 @@ function ChatMarkdown({
string,
NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>
>();
- for (const href of extractMarkdownLinkHrefs(text)) {
+ for (const href of extractMarkdownLinkHrefs(renderCodexFileCitationsAsMarkdown(text))) {
const normalizedHref = normalizeMarkdownLinkHrefKey(href);
if (metaByHref.has(normalizedHref)) continue;
const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd);
@@ -2037,6 +2120,15 @@ function ChatMarkdown({
};
return {
+ div({ node, children, ...props }) {
+ const artifactTemplate = artifactTemplateFromHastProperties(node?.properties);
+ if (artifactTemplate) {
+ return (
+ <CodexArtifactTemplateCard template={artifactTemplate} onUse={onUseArtifactTemplate} />
+ );
+ }
+ return <div {...props}>{children}</div>;
+ },
p({ node: _node, children, ...props }) {
return <p {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</p>;
},
@@ -2332,6 +2424,7 @@ function ChatMarkdown({
isStreaming,
markdownFileLinkMetaByHref,
onTaskListChange,
+ onUseArtifactTemplate,
onImageExpand,
openFileInPanel,
openInPreferredEditor,
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index d4a5bfe74c0..59563eb841a 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -9,6 +9,7 @@ import {
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import type { Thread, ThreadShell } from "../types";
+import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";
import {
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
@@ -36,6 +37,7 @@ import {
scheduleEnvironmentReconnectWarning,
shoulderTabReserve,
startNewThreadForProject,
+ codexArtifactTemplatePromptToAppend,
shouldDockDraftHeroForSubmission,
shouldReleaseTimelineAnchorForToolActivity,
shouldShowBranchMismatchBanner,
@@ -72,6 +74,20 @@ const environmentId = EnvironmentId.make("environment-local");
const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
const now = "2026-03-29T00:00:00.000Z";
+const helloWorldTemplate: CodexArtifactTemplate = {
+ artifactKind: "document",
+ displayName: "Hello World",
+ skillDirectory: "/Users/test/.codex/skills/artifact-template-hello-world",
+ skillName: "artifact-template-hello-world",
+};
+
+describe("artifact template composer insertion", () => {
+ it("does not insert an already-present prompt", () => {
+ const prompt = "Create a document using this $artifact-template-hello-world about…";
+
+ expect(codexArtifactTemplatePromptToAppend(prompt, helloWorldTemplate)).toBeNull();
+ });
+});
describe("shoulderTabReserve", () => {
it("ignores the top drawer when measuring the shoulder tab band", () => {
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index b0f5dacc078..259f1c15c01 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -12,6 +12,11 @@ import {
type ThreadId,
type TurnId,
} from "@t3tools/contracts";
+import {
+ appendCodexArtifactTemplateUsePrompt,
+ codexArtifactTemplateUsePrompt,
+ type CodexArtifactTemplate,
+} from "@t3tools/client-runtime/codex-artifact-templates";
import {
type ChatMessage,
isImageAttachment,
@@ -39,6 +44,14 @@ export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
+export function codexArtifactTemplatePromptToAppend(
+ currentDraft: string,
+ template: CodexArtifactTemplate,
+): string | null {
+ return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
+ ? null
+ : codexArtifactTemplateUsePrompt(template);
+}
export function shoulderTabReserve(overlay: HTMLElement): number {
if (overlay.querySelector(".chat-composer-tasks-tab")) return 0;
const tab = overlay.querySelector<HTMLElement>(".chat-composer-shoulder-tab");
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index a7b585ec6bd..bc70cff005f 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -29,6 +29,7 @@ import {
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
+import { type CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";
import {
changeRequestAutoSettles,
effectiveSettled,
@@ -376,6 +377,7 @@ import {
revokeUserMessagePreviewUrls,
shouldWriteThreadErrorToCurrentServerThread,
startNewThreadForProject,
+ codexArtifactTemplatePromptToAppend,
waitForStartedServerThread,
} from "./ChatView.logic";
import type { ThreadSyncPhase } from "../threadSync";
@@ -3126,6 +3128,25 @@ function ChatViewContent(props: ChatViewProps) {
focusComposer();
});
}, [focusComposer]);
+ const useArtifactTemplate = useCallback(
+ (template: CodexArtifactTemplate) => {
+ const composer = composerRef.current;
+ if (!composer) return;
+
+ const currentDraft = composer.getSendContext().prompt;
+ const prompt = codexArtifactTemplatePromptToAppend(currentDraft, template);
+ if (prompt !== null && !composer.insertTextAtEnd(prompt, { ensureLeadingBoundary: true })) {
+ toastManager.add({
+ type: "error",
+ title: "Unable to add to chat",
+ description: "The composer is busy; try again once it is ready.",
+ });
+ return;
+ }
+ scheduleComposerFocus();
+ },
+ [composerRef, scheduleComposerFocus],
+ );
const addTerminalContextToDraft = useCallback(
(selection: TerminalContextSelection) => {
composerRef.current?.addTerminalContext(selection);
@@ -7237,6 +7258,7 @@ function ChatViewContent(props: ChatViewProps) {
onOpenTurnDiff={onOpenTurnDiff}
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
onRevertUserMessage={onRevertUserMessage}
+ onUseArtifactTemplate={useArtifactTemplate}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
onFileOpen={openFileAttachment}
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index 81c9fdacdb9..e9dd9bad053 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -270,6 +270,23 @@ describe("resolveAssistantMessageCopyState", () => {
visible: false,
});
});
+
+ it("copies the rendered representation of Codex directives", () => {
+ expect(
+ resolveAssistantMessageCopyState({
+ showCopyButton: true,
+ text: [
+ 'Created :codex-file-citation{path="outputs/report.xlsx" purpose="output"}.',
+ "",
+ '::artifact-template{skill_name="artifact-template-hello-world" skill_directory="/Users/test/.codex/skills/artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}',
+ ].join("\n"),
+ streaming: false,
+ }),
+ ).toEqual({
+ text: "Created [report.xlsx](<outputs/report.xlsx>).\n\nHello World (Document template)",
+ visible: true,
+ });
+ });
});
describe("deriveMessagesTimelineRows", () => {
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index d398583430f..d2b7b6a82eb 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -1,4 +1,5 @@
import * as Equal from "effect/Equal";
+import { renderCodexDirectivesForCopy } from "@t3tools/client-runtime/codex-markdown-directives";
import {
formatDuration,
workEntryDisplayIndicatesToolFailure,
@@ -439,9 +440,10 @@ export function resolveAssistantMessageCopyState({
streaming: boolean;
}) {
const hasText = text !== null && text.trim().length > 0;
+ const visible = showCopyButton && hasText && !streaming;
return {
- text: hasText ? text : null,
- visible: showCopyButton && hasText && !streaming,
+ text: hasText ? (visible ? renderCodexDirectivesForCopy(text) : text) : null,
+ visible,
};
}
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 6be501fe121..b207ebc7368 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -7,6 +7,7 @@ import {
type TurnId,
} from "@t3tools/contracts";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
+import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";
import { commandProgramName } from "@t3tools/client-runtime/work-log/command-label";
import type { AgentPanelModel } from "@t3tools/client-runtime/state/subagentRuntime";
import {
@@ -16,6 +17,7 @@ import {
const EMPTY_AGENT_PANEL_MODEL = emptyAgentPanelModel();
const NOOP_OPEN_AGENTS = () => {};
+const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import {
@@ -154,6 +156,7 @@ interface TimelineRowSharedState {
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
activeThreadEnvironmentId: EnvironmentId;
onRevertUserMessage: (messageId: MessageId) => void;
+ onUseArtifactTemplate: (template: CodexArtifactTemplate) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
onFileOpen: (attachment: ChatFileAttachment) => void;
openingVideoAttachmentId: string | null;
@@ -235,6 +238,7 @@ interface MessagesTimelineProps {
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
revertTurnCountByUserMessageId: Map<MessageId, number>;
onRevertUserMessage: (messageId: MessageId) => void;
+ onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
onFileOpen?: (attachment: ChatFileAttachment) => void;
@@ -282,6 +286,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onOpenTurnDiff,
revertTurnCountByUserMessageId,
onRevertUserMessage,
+ onUseArtifactTemplate = NOOP_USE_ARTIFACT_TEMPLATE,
isRevertingCheckpoint,
onImageExpand,
onFileOpen = NOOP_OPEN_ATTACHMENT,
@@ -543,6 +548,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
skills,
activeThreadEnvironmentId,
onRevertUserMessage,
+ onUseArtifactTemplate,
onImageExpand,
onFileOpen,
openingVideoAttachmentId,
@@ -561,6 +567,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
skills,
activeThreadEnvironmentId,
onRevertUserMessage,
+ onUseArtifactTemplate,
onImageExpand,
onFileOpen,
openingVideoAttachmentId,
@@ -1253,6 +1260,7 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
isStreaming={Boolean(row.message.streaming)}
lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
skills={ctx.skills}
+ onUseArtifactTemplate={ctx.onUseArtifactTemplate}
onImageExpand={ctx.onImageExpand}
/>
<AssistantChangedFilesSection
diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts
index 7265e8b6043..af2a2912c91 100644
--- a/apps/web/src/markdown-clipboard.test.ts
+++ b/apps/web/src/markdown-clipboard.test.ts
@@ -22,6 +22,7 @@ class FakeElement {
constructor(
readonly tagName: string,
private readonly classNames: ReadonlyArray<string> = [],
+ private readonly attributes: Readonly<Record<string, string>> = {},
) {}
get localName(): string {
@@ -37,12 +38,12 @@ class FakeElement {
return this;
}
- getAttribute(): string | null {
- return null;
+ getAttribute(name: string): string | null {
+ return this.attributes[name] ?? null;
}
- hasAttribute(): boolean {
- return false;
+ hasAttribute(name: string): boolean {
+ return Object.hasOwn(this.attributes, name);
}
}
@@ -92,4 +93,19 @@ describe("serializeRenderedMarkdownFragment", () => {
expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
});
+
+ it("uses a rendered card's explicit Markdown copy representation", () => {
+ const card = new FakeElement("DIV", [], {
+ "data-markdown-copy": "Hello World (Document template)\n\n",
+ }).append(
+ new FakeElement("SPAN").append(new FakeText("Hello World")),
+ new FakeElement("SPAN").append(new FakeText("Document template")),
+ new FakeElement("BUTTON").append(new FakeText("Use template")),
+ );
+ const container = new FakeElement("DIV").append(card);
+
+ expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
+ "Hello World (Document template)",
+ );
+ });
});
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 865a9e4f26e..eb63e831341 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -19,6 +19,18 @@
"types": "./src/markdownImages.ts",
"default": "./src/markdownImages.ts"
},
+ "./codex-file-citations": {
+ "types": "./src/codexFileCitations.ts",
+ "default": "./src/codexFileCitations.ts"
+ },
+ "./codex-artifact-templates": {
+ "types": "./src/codexArtifactTemplates.ts",
+ "default": "./src/codexArtifactTemplates.ts"
+ },
+ "./codex-markdown-directives": {
+ "types": "./src/codexMarkdownDirectives.ts",
+ "default": "./src/codexMarkdownDirectives.ts"
+ },
"./errors": {
"types": "./src/errors/index.ts",
"default": "./src/errors/index.ts"
@@ -175,10 +187,16 @@
"dependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
- "effect": "catalog:"
+ "effect": "catalog:",
+ "mdast-util-directive": "^3.1.0",
+ "micromark-extension-directive": "^4.0.0",
+ "micromark-util-character": "^2.1.1",
+ "remark-parse": "^11.0.0",
+ "unified": "^11.0.5"
},
"devDependencies": {
"@effect/vitest": "catalog:",
+ "micromark-util-types": "^2.0.2",
"vite-plus": "catalog:"
}
}
diff --git a/packages/client-runtime/src/codexArtifactTemplates.test.ts b/packages/client-runtime/src/codexArtifactTemplates.test.ts
new file mode 100644
index 00000000000..d92236104a5
--- /dev/null
+++ b/packages/client-runtime/src/codexArtifactTemplates.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ appendCodexArtifactTemplateUsePrompt,
+ codexArtifactTemplatePresentationLabel,
+ codexArtifactTemplateUsePrompt,
+ resolveCodexArtifactTemplate,
+ type CodexArtifactTemplate,
+} from "./codexArtifactTemplates.js";
+
+const HELLO_WORLD_TEMPLATE: CodexArtifactTemplate = {
+ artifactKind: "document",
+ displayName: "Hello World",
+ skillDirectory: "/Users/test/.codex/skills/artifact-template-hello-world",
+ skillName: "artifact-template-hello-world",
+};
+
+describe("artifact template presentation", () => {
+ it("shares labels and copy text across clients", () => {
+ expect(codexArtifactTemplatePresentationLabel("document")).toBe("Document template");
+ });
+});
+
+describe("resolveCodexArtifactTemplate", () => {
+ it("accepts the template metadata emitted by Codex", () => {
+ expect(
+ resolveCodexArtifactTemplate({
+ artifact_kind: "document",
+ display_name: " Hello World ",
+ skill_directory: "/Users/test/.codex/skills/artifact-template-hello-world",
+ skill_name: "artifact-template-hello-world",
+ }),
+ ).toEqual(HELLO_WORLD_TEMPLATE);
+ });
+
+ it.each([
+ String.raw`C:\Users\test\.codex\skills\artifact-template-hello-world`,
+ String.raw`\\server\share\artifact-template-hello-world`,
+ "//server/share/artifact-template-hello-world",
+ ])("accepts absolute Windows skill directories: %s", (skillDirectory) => {
+ expect(
+ resolveCodexArtifactTemplate({
+ artifact_kind: "image",
+ display_name: "Reference image",
+ gallery_kind: "product-design",
+ skill_directory: skillDirectory,
+ skill_name: "artifact-template-reference-image",
+ }),
+ ).toMatchObject({
+ artifactKind: "image",
+ galleryKind: "product-design",
+ skillDirectory,
+ });
+ });
+
+ it.each([
+ { artifact_kind: "unknown" },
+ { display_name: " " },
+ { skill_directory: "relative/template" },
+ { skill_name: "hello-world" },
+ { gallery_kind: null },
+ { gallery_kind: "unknown" },
+ ])("rejects malformed template metadata: %o", (override) => {
+ expect(
+ resolveCodexArtifactTemplate({
+ artifact_kind: "document",
+ display_name: "Hello World",
+ skill_directory: "/templates/hello-world",
+ skill_name: "artifact-template-hello-world",
+ ...override,
+ }),
+ ).toBeNull();
+ });
+});
+
+describe("codexArtifactTemplateUsePrompt", () => {
+ it("builds the same document follow-up shape as Codex", () => {
+ expect(codexArtifactTemplateUsePrompt(HELLO_WORLD_TEMPLATE)).toBe(
+ "Create a document using this $artifact-template-hello-world about…",
+ );
+ });
+
+ it("uses the artifact-specific image wording", () => {
+ expect(
+ codexArtifactTemplateUsePrompt({
+ ...HELLO_WORLD_TEMPLATE,
+ artifactKind: "image",
+ }),
+ ).toBe("Create an image using this $artifact-template-hello-world of…");
+ });
+});
+
+describe("appendCodexArtifactTemplateUsePrompt", () => {
+ const prompt = "Create a document using this $artifact-template-hello-world about…";
+
+ it("adds the prompt to an empty draft", () => {
+ expect(appendCodexArtifactTemplateUsePrompt("", HELLO_WORLD_TEMPLATE)).toBe(prompt);
+ });
+
+ it("preserves existing draft text", () => {
+ expect(appendCodexArtifactTemplateUsePrompt("Write about otters", HELLO_WORLD_TEMPLATE)).toBe(
+ `Write about otters ${prompt}`,
+ );
+ });
+
+ it.each([prompt, `${prompt}\n`, `Notes\n\n${prompt}`])(
+ "does not append the same final prompt twice: %s",
+ (draft) => {
+ expect(appendCodexArtifactTemplateUsePrompt(draft, HELLO_WORLD_TEMPLATE)).toBe(draft);
+ },
+ );
+
+ it("does not mistake text containing the prompt for a final prompt", () => {
+ const draft = `${prompt}\nAdditional instructions`;
+ expect(appendCodexArtifactTemplateUsePrompt(draft, HELLO_WORLD_TEMPLATE)).toBe(
+ `${draft} ${prompt}`,
+ );
+ });
+});
diff --git a/packages/client-runtime/src/codexArtifactTemplates.ts b/packages/client-runtime/src/codexArtifactTemplates.ts
new file mode 100644
index 00000000000..ad46a7d6c2b
--- /dev/null
+++ b/packages/client-runtime/src/codexArtifactTemplates.ts
@@ -0,0 +1,136 @@
+export const CODEX_ARTIFACT_TEMPLATE_KINDS = [
+ "document",
+ "presentation",
+ "spreadsheet",
+ "site",
+ "google-docs",
+ "google-slides",
+ "google-sheets",
+ "image",
+ "email",
+ "slack",
+] as const;
+
+export type CodexArtifactTemplateKind = (typeof CODEX_ARTIFACT_TEMPLATE_KINDS)[number];
+
+export const CODEX_ARTIFACT_TEMPLATE_GALLERY_KINDS = ["imagegen", "product-design"] as const;
+
+export type CodexArtifactTemplateGalleryKind =
+ (typeof CODEX_ARTIFACT_TEMPLATE_GALLERY_KINDS)[number];
+
+export interface CodexArtifactTemplate {
+ readonly artifactKind: CodexArtifactTemplateKind;
+ readonly displayName: string;
+ readonly galleryKind?: CodexArtifactTemplateGalleryKind;
+ readonly skillDirectory: string;
+ readonly skillName: string;
+}
+
+export const CODEX_ARTIFACT_TEMPLATE_LABEL_BY_KIND = {
+ document: "Document template",
+ presentation: "Presentation template",
+ spreadsheet: "Spreadsheet template",
+ site: "Site template",
+ "google-docs": "Google Doc template",
+ "google-slides": "Google Slides template",
+ "google-sheets": "Google Sheet template",
+ image: "Image template",
+ email: "Email template",
+ slack: "Slack template",
+} satisfies Record<CodexArtifactTemplateKind, string>;
+
+export type CodexArtifactTemplateAttributes = Readonly<Record<string, string | null | undefined>>;
+
+const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
+const WINDOWS_UNC_PATH_REGEX = /^(?:\\\\[^\\]+\\[^\\]+|\/\/[^/]+\/[^/]+)/;
+
+function isCodexArtifactTemplateKind(value: unknown): value is CodexArtifactTemplateKind {
+ return CODEX_ARTIFACT_TEMPLATE_KINDS.some((kind) => kind === value);
+}
+
+function isCodexArtifactTemplateGalleryKind(
+ value: unknown,
+): value is CodexArtifactTemplateGalleryKind {
+ return CODEX_ARTIFACT_TEMPLATE_GALLERY_KINDS.some((kind) => kind === value);
+}
+
+function isAbsoluteSkillDirectory(value: string): boolean {
+ return (
+ (value.startsWith("/") && !value.startsWith("//")) ||
+ WINDOWS_DRIVE_PATH_REGEX.test(value) ||
+ WINDOWS_UNC_PATH_REGEX.test(value)
+ );
+}
+
+/** Mirrors the Codex result-card schema so malformed directives remain literal Markdown. */
+export function resolveCodexArtifactTemplate(
+ attributes: CodexArtifactTemplateAttributes | null | undefined,
+): CodexArtifactTemplate | null {
+ const artifactKind = attributes?.artifact_kind;
+ const displayNameValue = attributes?.display_name;
+ const displayName = typeof displayNameValue === "string" ? displayNameValue.trim() : undefined;
+ const galleryKind = attributes?.gallery_kind;
+ const skillDirectory = attributes?.skill_directory;
+ const skillName = attributes?.skill_name;
+
+ if (
+ !isCodexArtifactTemplateKind(artifactKind) ||
+ !displayName ||
+ typeof skillDirectory !== "string" ||
+ !isAbsoluteSkillDirectory(skillDirectory) ||
+ typeof skillName !== "string" ||
+ !skillName.startsWith("artifact-template-") ||
+ (galleryKind !== undefined && !isCodexArtifactTemplateGalleryKind(galleryKind))
+ ) {
+ return null;
+ }
+
+ return {
+ artifactKind,
+ displayName,
+ ...(galleryKind === undefined ? {} : { galleryKind }),
+ skillDirectory,
+ skillName,
+ };
+}
+
+const USE_PROMPT_BY_KIND: Record<CodexArtifactTemplateKind, (skill: string) => string> = {
+ document: (skill) => `Create a document using this ${skill} about…`,
+ presentation: (skill) => `Create a presentation using the ${skill} template about…`,
+ spreadsheet: (skill) => `Create a spreadsheet using this ${skill} about…`,
+ site: (skill) => `Create a Site using this ${skill} about…`,
+ "google-docs": (skill) => `Create a Google Doc using this ${skill} about…`,
+ "google-slides": (skill) => `Create a Google Slides presentation using this ${skill} about…`,
+ "google-sheets": (skill) => `Create a Google Sheet using this ${skill} about…`,
+ image: (skill) => `Create an image using this ${skill} of…`,
+ email: (skill) => `Draft an email using this ${skill} about…`,
+ slack: (skill) => `Draft a Slack message using this ${skill} about…`,
+};
+
+export function codexArtifactTemplateUsePrompt(template: CodexArtifactTemplate): string {
+ return USE_PROMPT_BY_KIND[template.artifactKind](`$${template.skillName}`);
+}
+
+export function codexArtifactTemplatePresentationLabel(kind: CodexArtifactTemplateKind): string {
+ return CODEX_ARTIFACT_TEMPLATE_LABEL_BY_KIND[kind];
+}
+
+export function appendCodexArtifactTemplateUsePrompt(
+ draft: string,
+ template: CodexArtifactTemplate,
+): string {
+ const prompt = codexArtifactTemplateUsePrompt(template);
+ const trimmedDraft = draft.trimEnd();
+ const promptStart = trimmedDraft.length - prompt.length;
+ const alreadyEndsWithPrompt =
+ promptStart >= 0 &&
+ trimmedDraft.slice(promptStart) === prompt &&
+ (promptStart === 0 || /\s/.test(trimmedDraft[promptStart - 1] ?? ""));
+
+ if (alreadyEndsWithPrompt) {
+ return draft;
+ }
+
+ const needsLeadingSpace = draft.length > 0 && !/\s$/.test(draft);
+ return `${draft}${needsLeadingSpace ? " " : ""}${prompt}`;
+}
diff --git a/packages/client-runtime/src/codexFileCitations.test.ts b/packages/client-runtime/src/codexFileCitations.test.ts
new file mode 100644
index 00000000000..d132a5480ca
--- /dev/null
+++ b/packages/client-runtime/src/codexFileCitations.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { codexFileCitationMarkdown, resolveCodexFileCitationLink } from "./codexFileCitations.js";
+
+describe("resolveCodexFileCitationLink", () => {
+ it("resolves the attributes emitted by Codex", () => {
+ expect(
+ resolveCodexFileCitationLink({
+ path: "/workspace/outputs/issue-2387-sparse-diagonal.xlsx",
+ purpose: "output",
+ }),
+ ).toEqual({
+ path: "/workspace/outputs/issue-2387-sparse-diagonal.xlsx",
+ href: "/workspace/outputs/issue-2387-sparse-diagonal.xlsx",
+ label: "issue-2387-sparse-diagonal.xlsx",
+ });
+ });
+
+ it("carries the first cited line into the file href", () => {
+ expect(
+ resolveCodexFileCitationLink({
+ path: "src/main.ts",
+ line_range_start: "42",
+ line_range_end: "48",
+ git_url: "https://example.com/main.ts",
+ }),
+ ).toEqual({
+ path: "src/main.ts",
+ href: "src/main.ts#L42",
+ label: "main.ts",
+ lineRangeStart: 42,
+ });
+ });
+
+ it("rejects missing paths and invalid line numbers", () => {
+ expect(resolveCodexFileCitationLink({ purpose: "output" })).toBeNull();
+ expect(
+ resolveCodexFileCitationLink({ path: "src/main.ts", line_range_start: "not-a-line" }),
+ ).toEqual({
+ path: "src/main.ts",
+ href: "src/main.ts",
+ label: "main.ts",
+ });
+ });
+
+ it("preserves URL syntax characters in file paths", () => {
+ expect(
+ resolveCodexFileCitationLink({
+ path: "reports/100% #1? draft.md",
+ line_range_start: "7",
+ }),
+ ).toEqual({
+ path: "reports/100% #1? draft.md",
+ href: "reports/100%25 %231%3F draft.md#L7",
+ label: "100% #1? draft.md",
+ lineRangeStart: 7,
+ });
+ });
+});
+
+describe("codexFileCitationMarkdown", () => {
+ it("produces a portable Markdown link", () => {
+ const citation = resolveCodexFileCitationLink({ path: "reports/profit and loss.xlsx" });
+ expect(citation && codexFileCitationMarkdown(citation)).toBe(
+ "[profit and loss.xlsx](<reports/profit and loss.xlsx>)",
+ );
+ });
+
+ it("escapes Markdown syntax in the visible filename", () => {
+ const citation = resolveCodexFileCitationLink({
+ path: "reports/*draft*_[copy]`<&.txt",
+ });
+ expect(citation && codexFileCitationMarkdown(citation)).toBe(
+ "[\\*draft\\*\\_\\[copy\\]\\`\\<\\&.txt](<reports/*draft*_[copy]`%3C&.txt>)",
+ );
+ });
+});
diff --git a/packages/client-runtime/src/codexFileCitations.ts b/packages/client-runtime/src/codexFileCitations.ts
new file mode 100644
index 00000000000..b5042f0806e
--- /dev/null
+++ b/packages/client-runtime/src/codexFileCitations.ts
@@ -0,0 +1,55 @@
+export interface CodexFileCitationLink {
+ readonly path: string;
+ readonly href: string;
+ readonly label: string;
+ readonly lineRangeStart?: number;
+}
+
+export type CodexFileCitationAttributes = Readonly<Record<string, string | null | undefined>>;
+
+function positiveInteger(value: string | null | undefined): number | undefined {
+ if (value === null || value === undefined || value.trim().length === 0) return undefined;
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
+}
+
+function citationLabel(path: string): string {
+ const normalized = path.replaceAll("\\", "/").replace(/\/+$/, "");
+ return normalized.slice(normalized.lastIndexOf("/") + 1) || normalized || "File";
+}
+
+function markdownDestinationPath(path: string): string {
+ return path.replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("?", "%3F");
+}
+
+export function resolveCodexFileCitationLink(
+ attributes: CodexFileCitationAttributes | null | undefined,
+): CodexFileCitationLink | null {
+ const path = attributes?.path?.trim();
+ if (!path) return null;
+
+ const lineRangeStart = positiveInteger(attributes?.line_range_start);
+ const destinationPath = markdownDestinationPath(path);
+ return {
+ path,
+ href: lineRangeStart === undefined ? destinationPath : `${destinationPath}#L${lineRangeStart}`,
+ label: citationLabel(path),
+ ...(lineRangeStart === undefined ? {} : { lineRangeStart }),
+ };
+}
+
+function markdownLabel(value: string): string {
+ return value.replace(/[\\[\]*_`<&]/g, "\\$&");
+}
+
+function markdownDestination(value: string): string {
+ return value
+ .replaceAll("<", "%3C")
+ .replaceAll(">", "%3E")
+ .replaceAll("\r", "%0D")
+ .replaceAll("\n", "%0A");
+}
+
+export function codexFileCitationMarkdown(citation: CodexFileCitationLink): string {
+ return `[${markdownLabel(citation.label)}](<${markdownDestination(citation.href)}>)`;
+}
diff --git a/packages/client-runtime/src/codexMarkdownDirectives.test.ts b/packages/client-runtime/src/codexMarkdownDirectives.test.ts
new file mode 100644
index 00000000000..b2a22901eac
--- /dev/null
+++ b/packages/client-runtime/src/codexMarkdownDirectives.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it } from "vite-plus/test";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+
+import {
+ remarkCodexDirectives,
+ renderCodexDirectivesForCopy,
+ renderCodexFileCitationsAsMarkdown,
+ splitCodexArtifactTemplateMarkdown,
+} from "./codexMarkdownDirectives.js";
+
+interface TestNode {
+ readonly type: string;
+ readonly value?: string;
+ readonly url?: string;
+ readonly position?: {
+ readonly start: { readonly offset?: number };
+ readonly end: { readonly offset?: number };
+ };
+ readonly data?: {
+ readonly hName?: string;
+ readonly hProperties?: Readonly<Record<string, unknown>>;
+ };
+ readonly children?: readonly TestNode[];
+}
+
+const FILE_CITATION = ':codex-file-citation{path="outputs/report.xlsx" purpose="output"}';
+const ARTIFACT_TEMPLATE =
+ '::artifact-template{skill_name="artifact-template-hello-world" skill_directory="/Users/test/.codex/skills/artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}';
+
+function parse(markdown: string): TestNode {
+ const processor = unified().use(remarkParse).use(remarkCodexDirectives);
+ return processor.runSync(processor.parse(markdown), { value: markdown }) as TestNode;
+}
+
+function parseOrdinaryMarkdown(markdown: string): TestNode {
+ return unified().use(remarkParse).parse(markdown) as TestNode;
+}
+
+describe("remarkCodexDirectives", () => {
+ it("renders a file citation as a link without changing its source position", () => {
+ const markdown = `Created ${FILE_CITATION}.`;
+ const link = parse(markdown).children?.[0]?.children?.[1];
+
+ expect(link).toMatchObject({
+ type: "link",
+ url: "outputs/report.xlsx",
+ children: [{ type: "text", value: "report.xlsx" }],
+ position: {
+ start: { offset: markdown.indexOf(FILE_CITATION) },
+ end: { offset: markdown.indexOf(FILE_CITATION) + FILE_CITATION.length },
+ },
+ });
+ });
+
+ it("renders an artifact template as semantic block metadata", () => {
+ expect(parse(ARTIFACT_TEMPLATE).children?.[0]).toMatchObject({
+ type: "paragraph",
+ children: [],
+ data: {
+ hName: "div",
+ hProperties: {
+ dataCodexArtifactTemplate: "true",
+ dataArtifactKind: "document",
+ dataDisplayName: "Hello World",
+ dataSkillName: "artifact-template-hello-world",
+ },
+ },
+ });
+ });
+
+ it.each([
+ "Meeting at 10:30",
+ "Open src/main.ts:42",
+ "Use :hover and :tada:",
+ "::note",
+ ":::note\ncontent\n:::",
+ ':codex-file-citation-extra{path="outputs/report.xlsx"}',
+ "::artifact-template-extra",
+ ])("does not change unrelated colon syntax: %s", (markdown) => {
+ expect(parse(markdown)).toEqual(parseOrdinaryMarkdown(markdown));
+ });
+
+ it.each([
+ ':codex-file-citation{purpose="output"}',
+ '::artifact-template{skill_name="artifact-template-hello-world"}',
+ ])("keeps malformed supported directives literal: %s", (markdown) => {
+ expect(parse(markdown)).toEqual(parseOrdinaryMarkdown(markdown));
+ });
+});
+
+describe("native Markdown adapters", () => {
+ it("uses the same parser to render file citations as portable links", () => {
+ expect(renderCodexFileCitationsAsMarkdown(`Created ${FILE_CITATION}.`)).toBe(
+ "Created [report.xlsx](<outputs/report.xlsx>).",
+ );
+ });
+
+ it.each([
+ `\\${FILE_CITATION}`,
+ `\`${FILE_CITATION}\``,
+ `\`\`\`text\n${FILE_CITATION}\n\`\`\``,
+ `[See ${FILE_CITATION}](https://example.com)`,
+ ])("does not render excluded citation syntax: %s", (markdown) => {
+ expect(renderCodexFileCitationsAsMarkdown(markdown)).toBe(markdown);
+ });
+
+ it("splits artifact cards from surrounding native Markdown", () => {
+ expect(splitCodexArtifactTemplateMarkdown(`Before\n\n${ARTIFACT_TEMPLATE}\n\nAfter`)).toEqual([
+ { kind: "markdown", markdown: "Before\n\n", sourceOffset: 0 },
+ {
+ kind: "artifact-template",
+ sourceOffset: 8,
+ template: {
+ artifactKind: "document",
+ displayName: "Hello World",
+ skillDirectory: "/Users/test/.codex/skills/artifact-template-hello-world",
+ skillName: "artifact-template-hello-world",
+ },
+ },
+ {
+ kind: "markdown",
+ markdown: "\n\nAfter",
+ sourceOffset: 8 + ARTIFACT_TEMPLATE.length,
+ },
+ ]);
+ });
+
+ it("leaves malformed and code artifact-template examples in Markdown", () => {
+ const malformed = '::artifact-template{display_name="Hello World"}';
+ const code = `\`${ARTIFACT_TEMPLATE}\``;
+ expect(splitCodexArtifactTemplateMarkdown(malformed)).toEqual([
+ { kind: "markdown", markdown: malformed, sourceOffset: 0 },
+ ]);
+ expect(splitCodexArtifactTemplateMarkdown(code)).toEqual([
+ { kind: "markdown", markdown: code, sourceOffset: 0 },
+ ]);
+ });
+});
+
+describe("directive copy adapter", () => {
+ it("copies the Markdown representations shown by citation chips and template cards", () => {
+ expect(renderCodexDirectivesForCopy(`Created ${FILE_CITATION}.\n\n${ARTIFACT_TEMPLATE}`)).toBe(
+ "Created [report.xlsx](<outputs/report.xlsx>).\n\nHello World (Document template)",
+ );
+ });
+
+ it("leaves excluded and malformed directive source unchanged", () => {
+ const markdown = [
+ `\`${FILE_CITATION}\``,
+ '::artifact-template{display_name="Hello World"}',
+ ].join("\n\n");
+
+ expect(renderCodexDirectivesForCopy(markdown)).toBe(markdown);
+ });
+});
diff --git a/packages/client-runtime/src/codexMarkdownDirectives.ts b/packages/client-runtime/src/codexMarkdownDirectives.ts
new file mode 100644
index 00000000000..64a981a6b79
--- /dev/null
+++ b/packages/client-runtime/src/codexMarkdownDirectives.ts
@@ -0,0 +1,388 @@
+import { directiveFromMarkdown } from "mdast-util-directive";
+import { directive } from "micromark-extension-directive";
+import {
+ markdownLineEnding,
+ unicodePunctuation,
+ unicodeWhitespace,
+} from "micromark-util-character";
+import type { Construct, Extension, Tokenizer } from "micromark-util-types";
+import remarkParse from "remark-parse";
+import { unified, type Processor } from "unified";
+
+import {
+ codexArtifactTemplatePresentationLabel,
+ resolveCodexArtifactTemplate,
+ type CodexArtifactTemplate,
+} from "./codexArtifactTemplates.ts";
+import { codexFileCitationMarkdown, resolveCodexFileCitationLink } from "./codexFileCitations.ts";
+
+const COLON = 58;
+const DASH = 45;
+const UNDERSCORE = 95;
+const CODEX_FILE_CITATION_NAME = "codex-file-citation";
+const CODEX_ARTIFACT_TEMPLATE_NAME = "artifact-template";
+
+export const CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES = [
+ "dataCodexArtifactTemplate",
+ "dataArtifactKind",
+ "dataDisplayName",
+ "dataGalleryKind",
+ "dataSkillDirectory",
+ "dataSkillName",
+] as const;
+
+interface MarkdownPosition {
+ readonly start: { readonly offset?: number };
+ readonly end: { readonly offset?: number };
+}
+
+interface MarkdownAstNode {
+ type?: string;
+ name?: string;
+ value?: string;
+ url?: string;
+ attributes?: Readonly<Record<string, string | null>>;
+ position?: MarkdownPosition;
+ data?: {
+ codexArtifactTemplate?: CodexArtifactTemplate;
+ codexFileCitationMarkdown?: string;
+ hName?: string;
+ hProperties?: Record<string, unknown>;
+ };
+ children?: MarkdownAstNode[];
+}
+
+interface MarkdownFile {
+ readonly value: unknown;
+}
+
+export type CodexArtifactTemplateMarkdownSegment =
+ | { readonly kind: "markdown"; readonly markdown: string; readonly sourceOffset: number }
+ | {
+ readonly kind: "artifact-template";
+ readonly sourceOffset: number;
+ readonly template: CodexArtifactTemplate;
+ };
+
+function asConstruct(value: Construct | Construct[] | undefined, label: string): Construct {
+ const construct = Array.isArray(value) ? value[0] : value;
+ if (!construct) throw new Error(`Missing ${label} directive construct`);
+ return construct;
+}
+
+function directiveNameEnds(code: number | null): boolean {
+ return (
+ code === null ||
+ markdownLineEnding(code) ||
+ unicodeWhitespace(code) ||
+ (unicodePunctuation(code) && code !== DASH && code !== UNDERSCORE)
+ );
+}
+
+function directiveNameGate(markerCount: number, name: string): Construct {
+ const tokenize: Tokenizer = (effects, ok, nok) => {
+ let markerIndex = 0;
+ let nameIndex = 0;
+
+ return marker;
+
+ function marker(code: number | null) {
+ if (code !== COLON) return nok(code);
+ if (markerIndex === 0) effects.enter("data");
+ effects.consume(code);
+ markerIndex += 1;
+ return markerIndex === markerCount ? nameCharacter : marker;
+ }
+
+ function nameCharacter(code: number | null) {
+ if (code !== name.charCodeAt(nameIndex)) return nok(code);
+ effects.consume(code);
+ nameIndex += 1;
+ return nameIndex === name.length ? afterName : nameCharacter;
+ }
+
+ function afterName(code: number | null) {
+ effects.exit("data");
+ return directiveNameEnds(code) ? ok(code) : nok(code);
+ }
+ };
+
+ return { partial: true, tokenize };
+}
+
+function restrictedDirective(construct: Construct, markerCount: number, name: string): Construct {
+ const gate = directiveNameGate(markerCount, name);
+ return {
+ ...construct,
+ tokenize(effects, ok, nok) {
+ return effects.check(gate, construct.tokenize.call(this, effects, ok, nok), nok);
+ },
+ };
+}
+
+function codexDirectiveSyntax(): Extension {
+ const genericSyntax = directive();
+ const textDirective = asConstruct(genericSyntax.text?.[COLON], CODEX_FILE_CITATION_NAME);
+ const flowDirectives = genericSyntax.flow?.[COLON];
+ const leafDirective = Array.isArray(flowDirectives)
+ ? flowDirectives.find((construct) => construct.concrete !== true)
+ : flowDirectives;
+ if (!leafDirective)
+ throw new Error(`Missing ${CODEX_ARTIFACT_TEMPLATE_NAME} directive construct`);
+
+ return {
+ text: {
+ [COLON]: restrictedDirective(textDirective, 1, CODEX_FILE_CITATION_NAME),
+ },
+ flow: {
+ [COLON]: restrictedDirective(leafDirective, 2, CODEX_ARTIFACT_TEMPLATE_NAME),
+ },
+ };
+}
+
+const CODEX_DIRECTIVE_SYNTAX = codexDirectiveSyntax();
+const CODEX_DIRECTIVE_FROM_MARKDOWN = directiveFromMarkdown();
+
+function sourceForNode(node: MarkdownAstNode, source: string): string {
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ return start === undefined || end === undefined ? "" : source.slice(start, end);
+}
+
+function sourceForDirective(node: MarkdownAstNode, source: string, marker: ":" | "::"): string {
+ const prefix = `${marker}${node.name ?? ""}`;
+ const slicedSource = sourceForNode(node, source);
+ if (slicedSource.startsWith(prefix)) return slicedSource;
+
+ const attributes = Object.entries(node.attributes ?? {}).map(([name, value]) =>
+ value === null ? name : `${name}=${JSON.stringify(value)}`,
+ );
+ return `${prefix}${attributes.length === 0 ? "" : `{${attributes.join(" ")}}`}`;
+}
+
+function restoreTextDirective(node: MarkdownAstNode, source: string): void {
+ node.type = "text";
+ node.value = sourceForDirective(node, source, ":");
+ delete node.name;
+ delete node.attributes;
+ delete node.url;
+ delete node.data;
+ delete node.children;
+}
+
+function restoreLeafDirective(node: MarkdownAstNode, source: string): void {
+ const value = sourceForDirective(node, source, "::");
+ node.type = "paragraph";
+ node.children = [
+ { type: "text", value, ...(node.position === undefined ? {} : { position: node.position }) },
+ ];
+ delete node.name;
+ delete node.attributes;
+ delete node.value;
+ delete node.url;
+ delete node.data;
+}
+
+function renderFileCitation(node: MarkdownAstNode, source: string, insideLink: boolean): void {
+ const citation = resolveCodexFileCitationLink(node.attributes);
+ if (!citation || insideLink) {
+ restoreTextDirective(node, source);
+ return;
+ }
+
+ node.type = "link";
+ node.url = citation.href;
+ node.children = [{ type: "text", value: citation.label }];
+ node.data = { codexFileCitationMarkdown: codexFileCitationMarkdown(citation) };
+ delete node.name;
+ delete node.attributes;
+ delete node.value;
+}
+
+function renderArtifactTemplate(node: MarkdownAstNode, source: string): void {
+ const template = resolveCodexArtifactTemplate(node.attributes);
+ if (!template) {
+ restoreLeafDirective(node, source);
+ return;
+ }
+
+ node.type = "paragraph";
+ node.children = [];
+ node.data = {
+ codexArtifactTemplate: template,
+ hName: "div",
+ hProperties: {
+ dataCodexArtifactTemplate: "true",
+ dataArtifactKind: template.artifactKind,
+ dataDisplayName: template.displayName,
+ ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }),
+ dataSkillDirectory: template.skillDirectory,
+ dataSkillName: template.skillName,
+ },
+ };
+ delete node.name;
+ delete node.attributes;
+ delete node.value;
+ delete node.url;
+}
+
+function transformCodexDirectives(node: MarkdownAstNode, source: string, insideLink = false): void {
+ if (node.type === "textDirective" && node.name === CODEX_FILE_CITATION_NAME) {
+ renderFileCitation(node, source, insideLink);
+ return;
+ }
+ if (node.type === "leafDirective" && node.name === CODEX_ARTIFACT_TEMPLATE_NAME) {
+ renderArtifactTemplate(node, source);
+ return;
+ }
+
+ const childrenInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
+ for (const child of node.children ?? []) {
+ transformCodexDirectives(child, source, childrenInsideLink);
+ }
+}
+
+/** Adds grammar only for the two directives emitted by Codex, then renders them as mdast. */
+function attachCodexDirectives(this: Processor) {
+ const data = this.data();
+ const micromarkExtensions = data.micromarkExtensions ?? (data.micromarkExtensions = []);
+ const fromMarkdownExtensions = data.fromMarkdownExtensions ?? (data.fromMarkdownExtensions = []);
+ micromarkExtensions.push(CODEX_DIRECTIVE_SYNTAX);
+ fromMarkdownExtensions.push(CODEX_DIRECTIVE_FROM_MARKDOWN);
+
+ return (tree: unknown, file: MarkdownFile) => {
+ transformCodexDirectives(tree as MarkdownAstNode, String(file.value));
+ };
+}
+
+export const remarkCodexDirectives = attachCodexDirectives;
+
+const directiveParser = unified().use(remarkParse).use(remarkCodexDirectives).freeze();
+
+function parseCodexMarkdown(markdown: string): MarkdownAstNode {
+ return directiveParser.runSync(directiveParser.parse(markdown), {
+ value: markdown,
+ }) as MarkdownAstNode;
+}
+
+interface DirectiveMatch {
+ readonly start: number;
+ readonly end: number;
+ readonly markdown?: string;
+ readonly template?: CodexArtifactTemplate;
+}
+
+function collectDirectiveMatches(node: MarkdownAstNode, matches: DirectiveMatch[]): void {
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (start !== undefined && end !== undefined) {
+ if (node.data?.codexFileCitationMarkdown !== undefined) {
+ matches.push({ start, end, markdown: node.data.codexFileCitationMarkdown });
+ return;
+ }
+ if (node.data?.codexArtifactTemplate !== undefined) {
+ matches.push({ start, end, template: node.data.codexArtifactTemplate });
+ return;
+ }
+ }
+ for (const child of node.children ?? []) collectDirectiveMatches(child, matches);
+}
+
+function renderDirectiveMatches(
+ markdown: string,
+ replacementFor: (match: DirectiveMatch) => string | undefined,
+): string {
+ const matches: DirectiveMatch[] = [];
+ collectDirectiveMatches(parseCodexMarkdown(markdown), matches);
+ let rendered = markdown;
+ for (const match of matches.sort((left, right) => right.start - left.start)) {
+ const replacement = replacementFor(match);
+ if (replacement !== undefined) {
+ rendered = rendered.slice(0, match.start) + replacement + rendered.slice(match.end);
+ }
+ }
+ return rendered;
+}
+
+/** Native Markdown renderers use this adapter because they cannot consume a Remark tree. */
+export function renderCodexFileCitationsAsMarkdown(markdown: string): string {
+ if (!markdown.includes(`:${CODEX_FILE_CITATION_NAME}`)) return markdown;
+
+ return renderDirectiveMatches(markdown, (match) => match.markdown);
+}
+
+/** Matches the Markdown emitted when users copy rendered Codex directive UI. */
+export function renderCodexDirectivesForCopy(markdown: string): string {
+ if (
+ !markdown.includes(`:${CODEX_FILE_CITATION_NAME}`) &&
+ !markdown.includes(`::${CODEX_ARTIFACT_TEMPLATE_NAME}`)
+ ) {
+ return markdown;
+ }
+
+ return renderDirectiveMatches(markdown, (match) => {
+ if (match.markdown !== undefined) return match.markdown;
+ if (match.template === undefined) return undefined;
+ return `${match.template.displayName} (${codexArtifactTemplatePresentationLabel(match.template.artifactKind)})`;
+ });
+}
+
+/** Native renderers split cards out because they cannot host a view inside Markdown text. */
+export function splitCodexArtifactTemplateMarkdown(
+ markdown: string,
+): ReadonlyArray<CodexArtifactTemplateMarkdownSegment> {
+ if (!markdown.includes(`::${CODEX_ARTIFACT_TEMPLATE_NAME}`)) {
+ return [{ kind: "markdown", markdown, sourceOffset: 0 }];
+ }
+
+ const matches: DirectiveMatch[] = [];
+ collectDirectiveMatches(parseCodexMarkdown(markdown), matches);
+ const templates = matches
+ .filter(
+ (match): match is DirectiveMatch & { readonly template: CodexArtifactTemplate } =>
+ match.template !== undefined,
+ )
+ .sort((left, right) => left.start - right.start);
+ if (templates.length === 0) {
+ return [{ kind: "markdown", markdown, sourceOffset: 0 }];
+ }
+
+ const segments: CodexArtifactTemplateMarkdownSegment[] = [];
+ let cursor = 0;
+ for (const match of templates) {
+ if (match.start > cursor) {
+ segments.push({
+ kind: "markdown",
+ markdown: markdown.slice(cursor, match.start),
+ sourceOffset: cursor,
+ });
+ }
+ segments.push({
+ kind: "artifact-template",
+ sourceOffset: match.start,
+ template: match.template,
+ });
+ cursor = match.end;
+ }
+ if (cursor < markdown.length) {
+ segments.push({ kind: "markdown", markdown: markdown.slice(cursor), sourceOffset: cursor });
+ }
+ return segments;
+}
+
+export function artifactTemplateFromHastProperties(
+ properties: Readonly<Record<string, unknown>> | null | undefined,
+): CodexArtifactTemplate | null {
+ if (properties?.dataCodexArtifactTemplate !== "true") return null;
+ const stringProperty = (name: string) => {
+ const value = properties[name];
+ return typeof value === "string" ? value : undefined;
+ };
+ return resolveCodexArtifactTemplate({
+ artifact_kind: stringProperty("dataArtifactKind"),
+ display_name: stringProperty("dataDisplayName"),
+ gallery_kind: stringProperty("dataGalleryKind"),
+ skill_directory: stringProperty("dataSkillDirectory"),
+ skill_name: stringProperty("dataSkillName"),
+ });
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b3d835358ef..ef8a70fbaa1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -784,10 +784,28 @@ importers:
effect:
specifier: 4.0.0-beta.103
version: 4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)
+ mdast-util-directive:
+ specifier: ^3.1.0
+ version: 3.1.0
+ micromark-extension-directive:
+ specifier: ^4.0.0
+ version: 4.0.0
+ micromark-util-character:
+ specifier: ^2.1.1
+ version: 2.1.1
+ remark-parse:
+ specifier: ^11.0.0
+ version: 11.0.0
+ unified:
+ specifier: ^11.0.5
+ version: 11.0.5
devDependencies:
'@effect/vitest':
specifier: 4.0.0-beta.103
version: 4.0.0-beta.103(patch_hash=a16b1e870d8c29e4a98b17cc4c638a4ff471753d8ca3487f78a22b759caf951b)([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))
+ micromark-util-types:
+ specifier: ^2.0.2
+ version: 2.0.2
vite-plus:
specifier: 'catalog:'
@@ -7726,6 +7744,9 @@ packages:
resolution: {integrity: sha512-scTllyX6pnYNZH/AIp/0ePz6s4cZtARxImwoPJ7kS42n+MnVsI4XbnG6d4ibehRIldYMWM2LD7ImQblVhUejVQ==}
+ resolution: {integrity: sha512-I3fNFt+DHmpWCYAT7quoM6lHf9wuqtI+oCOfvILnoicNIqjh5E3dEJWiXuYME2gNe8vl1iMQwyUHa7bgFmak6Q==}
+
resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}
@@ -7923,6 +7944,9 @@ packages:
resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}
+ resolution: {integrity: sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg==}
+
resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}
@@ -17805,6 +17829,20 @@ snapshots:
unist-util-visit: 5.1.0
optional: true
+ dependencies:
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ ccount: 2.0.1
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ parse-entities: 4.0.2
+ stringify-entities: 4.0.4
+ unist-util-visit-parents: 6.0.2
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/mdast': 4.0.4
@@ -18347,6 +18385,16 @@ snapshots:
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
+ dependencies:
+ devlop: 1.1.0
+ micromark-factory-space: 2.0.1
+ micromark-factory-whitespace: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+ parse-entities: 4.0.2
+
dependencies:
micromark-util-character: 2.1.1