forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
2175 lines (1952 loc) · 77.5 KB
/
Copy pathindex.ts
File metadata and controls
2175 lines (1952 loc) · 77.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Integration Package Generator
*
* Scaffolds a new integration package in showcase/integrations/<slug>/
* with all required files, demo stubs, and deployment configs.
*
* Usage:
* npx tsx create-integration/index.ts \
* --name "Anthropic (Claude Agent SDK)" \
* --slug anthropic-claude-sdk \
* --category provider-sdk \
* --language python \
* --features agentic-chat,hitl-in-chat,tool-rendering
*/
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import yaml from "yaml";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, "..", "..");
// Both directories are overridable via env so tests can run the generator
// against an isolated tmpdir — without overrides the generator's writes
// collided with sibling suites reading the real `showcase/integrations/` tree
// (ENOENT on partial state) and with concurrent `git checkout HEAD --`
// invocations on `.github/workflows/*.yml` (`.git/index.lock` races). An
// env var (vs a CLI flag) keeps the public flag surface unchanged and is
// trivial for test harnesses to set via `execFileSync`'s `env` option.
const PACKAGES_DIR =
process.env.CREATE_INTEGRATION_PACKAGES_DIR ??
path.join(ROOT, "integrations");
const WORKFLOWS_DIR =
process.env.CREATE_INTEGRATION_WORKFLOWS_DIR ??
path.resolve(ROOT, "..", ".github", "workflows");
const FEATURE_REGISTRY_PATH = path.join(
ROOT,
"shared",
"feature-registry.json",
);
interface Feature {
id: string;
name: string;
category: string;
description: string;
}
interface CLIArgs {
name: string;
slug: string;
category: Category;
language: Language;
features: string[];
extraDeps: string[];
}
const CATEGORIES = [
"popular",
"agent-framework",
"enterprise-platform",
"provider-sdk",
"protocol",
"emerging",
"starter",
] as const;
type Category = (typeof CATEGORIES)[number];
const LANGUAGES = ["python", "typescript", "dotnet"] as const;
type Language = (typeof LANGUAGES)[number];
/**
* Probe a filesystem path and classify the result so callers can
* distinguish "not present" from "present but unreadable". Using
* fs.existsSync collapses ENOENT and EACCES/EPERM/EIO into a bare
* boolean, which means a permissions or I/O fault masquerades as
* "missing" and leads to silently wrong branches (skip-update,
* overwrite, etc.). statSync + errno discrimination keeps the three
* outcomes distinct so callers can warn/exit/proceed appropriately.
*/
function probePath(p: string): "missing" | "exists" | "unreadable" {
try {
fs.statSync(p);
return "exists";
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code === "ENOENT") return "missing";
return "unreadable";
}
}
/**
* Escape regex metacharacters in a string so it can be safely embedded
* into a RegExp source. Used by updateWorkflows() to anchor slug-based
* idempotency checks to full-line matches — a bare `includes(slug)`
* collides across unrelated lines and against longer sibling slugs
* (e.g. `includes("- foo")` matches `"- foo-bar"`), which silently
* skips the insert and produces a broken workflow file.
*/
function escapeRegex(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Normalize a feature registry id (e.g. `"agentic-chat"`) into the
* agent-id convention used by deployed showcase backends, which
* register under underscore-separated ids (e.g. `"agentic_chat"`). The
* feature registry keys the demo tree with hyphens; the real backend
* agents are keyed with underscores. Callers that emit the agent id
* into runtime code (generateSmokeRoute, generateDemoPage, ...) must
* apply this rewrite so the emitted default lines up with the backend
* convention; a hyphen/underscore mismatch surfaces as a 404 /
* "agent not found" at smoke-test time, not at generator time.
*
* Emits a one-shot operator warning when the rewrite actually fires
* (hyphen present in the input) so that a generator run producing a
* rewritten default is visible in the console, matching the stronger
* warning generateSmokeRoute already emitted before this helper was
* factored out.
*/
function toAgentId(featureId: string, context: string): string {
const agentId = featureId.replace(/-/g, "_");
if (agentId !== featureId) {
console.warn(
`[create-integration] ${context}: rewrote feature id "${featureId}" → agentId="${agentId}" (hyphens → underscores). ` +
`Verify this matches the real agent id your backend registers.`,
);
}
return agentId;
}
export function parseArgs(): CLIArgs {
const args = process.argv.slice(2);
const parsed: Record<string, string> = {};
// Track which flags have already been seen so a duplicate occurrence
// (`--slug a --slug b`) is rejected loudly instead of silently
// overwriting the earlier value. Matches the strict-parser contract
// that capture-previews.ts and validate-parity.ts call out in their
// comments when they mirror this behaviour.
const seen = new Set<string>();
// Walk the argv in lockstep. Every `--flag` MUST be followed by a value
// that does not itself start with `--`; anything else is a usage error
// we surface immediately rather than silently dropping the flag (which
// would then trip the missing-required-flag check with a misleading
// message about the wrong flag).
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (!arg.startsWith("--")) {
console.error(
`Error: Unexpected positional argument '${arg}'. All arguments must be --flag value pairs.`,
);
process.exit(1);
}
const key = arg.slice(2);
const val = args[i + 1];
if (val === undefined || val.startsWith("--")) {
console.error(
`Error: Flag --${key} expects a value but got ${
val === undefined ? "end-of-args" : `another flag (${val})`
}.`,
);
process.exit(1);
}
if (seen.has(key)) {
console.error(`Error: --${key} specified more than once.`);
process.exit(1);
}
seen.add(key);
parsed[key] = val;
i++;
}
// Validate --name shape before any consumer interpolates it unescaped
// into JSX/markdown/YAML (page.tsx, README, MDX, manifest.yaml). A name
// like "Hello <script>alert(1)</script>" would otherwise inject raw
// JSX/markdown into generated files. The character class is a
// deliberately permissive superset for human-readable display names.
if (parsed.name !== undefined) {
if (parsed.name.length < 1) {
console.error(`Error: --name must be at least 1 character.`);
process.exit(1);
}
if (!/^[A-Za-z0-9 .\-/()[\]]+$/.test(parsed.name)) {
console.error(
`Error: Invalid --name '${parsed.name}'. Allowed characters: letters, digits, spaces, and . - / ( ) [ ]`,
);
process.exit(1);
}
}
// Validate --slug shape before any consumer interpolates it into
// filesystem paths (path.join(PACKAGES_DIR, slug)) or YAML/shell
// workflow blocks. Without this guard, a value like "../../etc/foo"
// escapes the packages directory and a value containing "/" creates
// nested subdirectories. The regex mirrors the format every existing
// deployed slug already follows (lowercase alnum with hyphen
// separators starting with a letter or digit).
if (parsed.slug !== undefined && !/^[a-z0-9][a-z0-9-]*$/.test(parsed.slug)) {
console.error(
`Invalid slug '${parsed.slug}'. Slugs must match /^[a-z0-9][a-z0-9-]*$/ (lowercase alphanumeric, hyphen-separated, starting with a letter or digit).`,
);
process.exit(1);
}
if (
!parsed.name ||
!parsed.slug ||
!parsed.category ||
!parsed.language ||
!parsed.features
) {
console.error(
"Usage: create-integration --name <name> --slug <slug> --category <category> --language <language> --features <comma-separated> [--deps <comma-separated>]",
);
console.error("\nRequired flags:");
console.error(
" --name Display name (e.g. 'Anthropic (Claude Agent SDK)')",
);
console.error(" --slug URL-safe ID (e.g. 'anthropic-claude-sdk')");
console.error(` --category One of: ${CATEGORIES.join(", ")}`);
console.error(` --language One of: ${LANGUAGES.join(", ")}`);
console.error(
" --features Comma-separated feature IDs (e.g. 'agentic-chat,hitl-in-chat,tool-rendering')",
);
console.error("\nOptional flags:");
console.error(
" --deps Extra npm dependencies (e.g. '@ag-ui/mastra,@mastra/core')",
);
process.exit(1);
}
// Validate that category and language are in the allowed literal unions;
// the rest of the generator branches on these values and a typo used to
// silently produce broken output (unknown category → registry lookup
// miss; unknown language → skipped runtime files).
if (!(CATEGORIES as readonly string[]).includes(parsed.category)) {
console.error(
`Error: Unknown --category '${parsed.category}'. One of: ${CATEGORIES.join(", ")}`,
);
process.exit(1);
}
if (!(LANGUAGES as readonly string[]).includes(parsed.language)) {
console.error(
`Error: Unknown --language '${parsed.language}'. One of: ${LANGUAGES.join(", ")}`,
);
process.exit(1);
}
return {
name: parsed.name,
slug: parsed.slug,
category: parsed.category as Category,
language: parsed.language as Language,
// Filter empty strings so trailing/leading commas (e.g. "a,b," or ",a")
// don't produce an empty-string entry that the registry lookup rejects
// with a confusing "Unknown feature id ''" error.
features: parsed.features
.split(",")
.map((f) => f.trim())
.filter((f) => f.length > 0),
extraDeps: parsed.deps
? parsed.deps
.split(",")
.map((d) => d.trim())
.filter((d) => d.length > 0)
: [],
};
}
/**
* Read + parse + shape-check the feature registry JSON. Exported so
* unit tests can exercise the error branches (ENOENT, invalid JSON,
* shape-invalid top level) without spawning a subprocess.
*/
export function loadFeatureRegistry(): Feature[] {
let raw: string;
try {
raw = fs.readFileSync(FEATURE_REGISTRY_PATH, "utf-8");
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(
`Failed to read feature registry at ${FEATURE_REGISTRY_PATH}: ${msg}`,
{ cause: err },
);
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(
`Feature registry at ${FEATURE_REGISTRY_PATH} is not valid JSON: ${msg}`,
{ cause: err },
);
}
if (
parsed === null ||
typeof parsed !== "object" ||
!Array.isArray((parsed as { features?: unknown }).features)
) {
throw new Error(
`Feature registry at ${FEATURE_REGISTRY_PATH} must be a JSON object with a 'features' array.`,
);
}
return (parsed as { features: Feature[] }).features;
}
function writeFile(filePath: string, content: string) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content);
console.log(` Created: ${path.relative(ROOT, filePath)}`);
}
function generateManifest(args: CLIArgs, features: Feature[]): string {
const demos = args.features.map((featureId) => {
const feature = features.find((f) => f.id === featureId);
const name = feature?.name || featureId;
const description = feature?.description || "";
const tags = [feature?.category || "general"].filter(Boolean);
return {
id: featureId,
name,
description,
tags,
route: `/demos/${featureId}`,
};
});
const manifest = {
name: args.name,
slug: args.slug,
category: args.category,
language: args.language,
logo: `/logos/${args.slug}.svg`,
description: `CopilotKit integration with ${args.name}`,
partner_docs: null,
repo: `https://github.com/CopilotKit/CopilotKit/tree/main/showcase/integrations/${args.slug}`,
copilotkit_version: "2.0.0",
// backend_url is intentionally omitted — generate-registry.ts synthesizes
// it at build time from `SHOWCASE_BACKEND_HOST_PATTERN` + slug.
deployed: false,
generative_ui: ["constrained-explicit"],
interaction_modalities: ["chat"],
features: args.features,
demos,
managed_platform: undefined as { name: string; url: string } | undefined,
};
const MANAGED_PLATFORMS: Record<string, { name: string; url: string }> = {
LangGraph: { name: "LangGraph Platform", url: "https://langsmith.com" },
Mastra: { name: "Mastra Cloud", url: "https://mastra.ai/cloud" },
CrewAI: { name: "CrewAI Enterprise", url: "https://crewai.com/amp" },
Agno: { name: "Agent OS", url: "https://os.agno.com" },
AG2: { name: "Agent OS", url: "https://ag2.ai/product" },
Strands: {
name: "AWS Bedrock AgentCore",
url: "https://aws.amazon.com/bedrock/agents/",
},
};
for (const [prefix, platform] of Object.entries(MANAGED_PLATFORMS)) {
if (args.name.startsWith(prefix)) {
manifest.managed_platform = platform;
break;
}
}
return yaml.stringify(manifest);
}
function generatePackageJson(args: CLIArgs): string {
return (
JSON.stringify(
{
name: `@copilotkit/showcase-${args.slug}`,
version: "0.1.0",
private: true,
scripts: {
dev:
args.language === "typescript"
? "next dev --turbopack"
: 'concurrently "next dev --turbopack" "python -m uvicorn agent_server:app --host 0.0.0.0 --port 8000 --reload"',
build: "next build",
start: "next start",
lint: "next lint",
"test:e2e": "playwright test",
},
dependencies: {
"@ag-ui/client": "^0.0.43",
"@copilotkit/react-core": "next",
"@copilotkit/runtime": "next",
next: "^15.0.0",
react: "^19.0.0",
"react-dom": "^19.0.0",
zod: "^3.24.0",
...Object.fromEntries(args.extraDeps.map((d) => [d, "latest"])),
},
devDependencies: {
"@playwright/test": "^1.50.0",
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
typescript: "^5.7.0",
tailwindcss: "^4.0.0",
"@tailwindcss/postcss": "^4.0.0",
postcss: "^8.5.0",
...(args.language !== "typescript" ? { concurrently: "^9.1.0" } : {}),
},
},
null,
2,
) + "\n"
);
}
function generateLayout(): string {
return `import type { Metadata } from "next";
import "@copilotkit/react-core/v2/styles.css";
import "./globals.css";
export const metadata: Metadata = {
title: "CopilotKit Showcase",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<script
dangerouslySetInnerHTML={{
__html: \`
console.log('[showcase] Demo loaded:', window.location.href);
console.log('[showcase] In iframe:', window.self !== window.top);
window.addEventListener('error', function(e) {
console.error('[showcase] Uncaught error:', e.message, e.filename, e.lineno);
});
window.addEventListener('unhandledrejection', function(e) {
console.error('[showcase] Unhandled rejection:', e.reason);
});
\`,
}}
/>
{children}
</body>
</html>
);
}
`;
}
function generatePostcssConfig(): string {
return `/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
`;
}
function generateGlobalsCss(): string {
return `@import "tailwindcss";
@import "@copilotkit/react-core/v2/styles.css";
:root {
--copilot-kit-background-color: #f8f9fa;
--copilot-kit-primary-color: #0066ff;
}
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
min-height: 100vh;
}
`;
}
function generateIndexPage(args: CLIArgs, features: Feature[]): string {
const demoLinks = args.features
.map((featureId) => {
const feature = features.find((f) => f.id === featureId);
const name = feature?.name || featureId;
const desc = feature?.description || "";
return ` <a key="${featureId}" href="/demos/${featureId}" className="demo-card">
<h3>${name}</h3>
<p>${desc}</p>
</a>`;
})
.join("\n");
return `export default function Home() {
return (
<main style={{ padding: "2rem", maxWidth: "800px", margin: "0 auto" }}>
<h1>${args.name}</h1>
<p>Integration ID: ${args.slug}</p>
<h2 style={{ marginTop: "2rem" }}>Demos</h2>
<div style={{ display: "grid", gap: "1rem", marginTop: "1rem" }}>
${demoLinks}
</div>
</main>
);
}
`;
}
function generateDemoPage(
featureId: string,
feature: Feature | undefined,
): string {
// The generated body only references `CopilotKit`, `CopilotChat`, and
// `useConfigureSuggestions` — the rest of the v2 hooks (and `z` from
// zod) were imported eagerly so operators had an autocomplete-friendly
// starting point. With `strict: true` tsconfig + Next's ESLint the
// generated package failed lint/typecheck out of the box on every
// unused-import warning. Derive the import list from the body instead
// so the emitted file is clean from the first build while preserving
// the "hooks available" comment block as an author-facing reference.
// Normalize the agent prop to the backend's underscore-id convention.
// The feature registry keys the demo tree with hyphens, but real
// deployed packages (e.g. showcase/integrations/langgraph-fastapi/src/app/
// demos/agentic-chat/page.tsx) register their backend agent under
// `agent="agentic_chat"`. Emitting the raw featureId here produces a
// generated page that 404s against every deployed backend; normalize
// via the shared toAgentId helper so the emitted agent prop matches
// the same rewrite generateSmokeRoute already applied to
// SMOKE_AGENT_ID. Shared helper → one source of truth for the
// convention.
const agentId = toAgentId(featureId, "generateDemoPage");
const body = `export default function ${toPascalCase(featureId)}Demo() {
return (
<DemoErrorBoundary demoName="${feature?.name || featureId}">
<CopilotKit runtimeUrl="/api/copilotkit" agent="${agentId}">
<DemoContent />
</CopilotKit>
</DemoErrorBoundary>
);
}
function DemoContent() {
// TODO: Implement ${feature?.name || featureId} demo
// See the LangGraph Python reference implementation for patterns
//
// IMPORTANT: Use inline styles for any UI rendered inside the chat
// (useRenderTool, useHumanInTheLoop callbacks). Tailwind classes get
// purged by Tailwind v4 in this context. See STYLING-GUIDE.md.
//
// Key hooks available:
// useFrontendTool({ name, description, parameters: z.object({...}), handler })
// useRenderTool({ name: "tool_name", render: ({ args }) => <Component /> })
// useHumanInTheLoop({ name, description, parameters, handler: ({ args, respond }) => ... })
// useAgentContext({ description, value })
// useConfigureSuggestions({ suggestions: [{ title, message }] })
// useInterrupt({ render: ({ event, resolve }) => <Component /> })
useConfigureSuggestions({
suggestions: [
{ title: "Get started", message: "Hello! What can you do?" },
],
});
return (
<div className="flex justify-center items-center h-screen w-full">
<div className="h-full w-full md:w-4/5 md:h-4/5 rounded-lg">
<CopilotChat
className="h-full rounded-2xl max-w-6xl mx-auto"
/>
</div>
</div>
);
}
`;
// Candidate hooks exported from @copilotkit/react-core/v2. `CopilotChat`
// is always emitted (the body unconditionally renders it). Every other
// hook is included only when the body's *executable code* references
// it as an identifier, so additions to the body in the future
// automatically pick up the right imports without reviving dead ones.
//
// The "Key hooks available:" documentation block names every hook
// inside `//` comments — we strip JS line and block comments before
// scanning so those reference-only mentions don't force the imports
// back in. Word boundaries also matter: a bare `includes("z")`
// matches any line containing the letter z (`organize`, `size`, ...).
const codeOnly = body
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/\/\/.*$/gm, "");
const v2Candidates = [
"useFrontendTool",
"useRenderTool",
"useAgentContext",
"useConfigureSuggestions",
"useHumanInTheLoop",
"useInterrupt",
] as const;
const v2Imports = [
"CopilotChat",
...v2Candidates.filter((h) => new RegExp(`\\b${h}\\b`).test(codeOnly)),
];
const zUsed = /\bz\b/.test(codeOnly);
const importLines = [
`import React from "react";`,
`import { CopilotKit } from "@copilotkit/react-core";`,
`import {\n${v2Imports.map((n) => ` ${n},`).join("\n")}\n} from "@copilotkit/react-core/v2";`,
...(zUsed ? [`import { z } from "zod";`] : []),
`import { DemoErrorBoundary } from "../error-boundary";`,
];
return `"use client";
${importLines.join("\n")}
${body}`;
}
// Accumulates feature ids that hit the default/placeholder branches of
// getDemoInteraction / getDemoTechnicalDetails. main() surfaces this set
// at the end of the run so operators see exactly which demos need
// authoring before shipping the generated package.
const unauthoredDemoFeatures = new Set<string>();
function getDemoInteraction(featureId: string): string {
switch (featureId) {
case "tool-rendering":
return `- "What's the weather like in San Francisco?"
- "Check the weather in Tokyo and New York"
- "Can you look up the current conditions in London?"`;
case "hitl-in-chat":
return `- "Plan a trip to Mars in 5 steps"
- "Please plan a pasta dish in 10 steps"
- "Draft a product launch checklist in 7 steps"
The agent proposes a plan as a **StepSelector** card with a checkbox per step. Toggle individual steps on or off (the selected count updates as "N/N selected"), then click **Perform Steps (N)** / **Confirm (N)** to approve, or **Reject** to cancel. The card reflects the final decision ("Accepted" / "Rejected") and disables its buttons afterward.`;
case "gen-ui-tool-based":
return `- "What's the weather forecast for this week in San Francisco?"
- "Show me the weather in Paris"
- "Compare the weather in Tokyo and London"
The agent generates structured data via tools, and the frontend renders it as rich UI components.`;
default:
// Unauthored demos land here. Previously returned a bare "TODO" line
// that was easy to miss in review. Keep the content generator-safe
// (callers expect a string) but make the placeholder self-describing
// and include the feature id so search-and-replace is unambiguous.
// Also record the id so main() can warn about unauthored demos at
// the end of the run rather than relying on reviewers to spot TODOs.
unauthoredDemoFeatures.add(featureId);
return `- TODO(${featureId}): authoring required. Known authored ids: ${KNOWN_AUTHORED_FEATURE_IDS.join(
", ",
)}. See getDemoInteraction in showcase/scripts/create-integration/index.ts.`;
}
}
// Feature ids that have authored per-demo content in the switches above
// and below. When adding a new id to the registry with custom content,
// add it here and to both switches in the same change.
const KNOWN_AUTHORED_FEATURE_IDS = [
"tool-rendering",
"hitl-in-chat",
"gen-ui-tool-based",
] as const;
function getDemoTechnicalDetails(featureId: string): string {
switch (featureId) {
case "tool-rendering":
return `- **Backend tools** are defined in the agent (e.g., \`get_weather\`) and called by the LLM when the user's query matches
- **\`useRenderTool\`** on the frontend registers a React component that renders whenever the agent calls that tool
- The render function receives \`args\` (input parameters), \`result\` (tool output), and \`status\` ("executing" or "complete") so the UI can show loading states
- The tool result is displayed as a rich UI card instead of plain text — demonstrating how agent actions can produce structured, visual output`;
case "hitl-in-chat":
return `- **Human-in-the-Loop (HITL)** lets the agent pause and hand control back to the user to review a proposed plan before continuing
- The agent calls a tool (e.g. \`generate_task_steps\`) whose payload is a list of steps; the frontend renders a **StepSelector** card rather than executing immediately
- \`useHumanInTheLoop\` (frontend-tool flow) or \`useInterrupt\` (interrupt flow, imported from \`@copilotkit/react-core/v2\`) registers a \`render\` that receives \`{ args, respond, status }\` — the StepSelector keeps local state for which steps are enabled and calls \`respond({ accepted, steps })\` on Confirm / Reject (CopilotKit v2 API; existing showcase packages use v1 \`useLangGraphInterrupt\` for the interrupt-flow demo alongside v2 hooks like \`useHumanInTheLoop\` — new integrations generated by \`create-integration\` default to the v2 \`useInterrupt\`.)
- The card exposes per-step checkboxes, a live "N/N selected" count, and Confirm / Reject buttons; after a decision the buttons disable and the card shows "Accepted" or "Rejected" so the outcome is auditable in the transcript
- This pattern is essential for plan-style flows — multi-step actions where the user needs to curate, edit, or veto what the agent is about to do before any of it runs`;
case "gen-ui-tool-based":
return `- **Generative UI** means the agent's tool calls produce structured data that the frontend renders as custom React components
- Unlike plain text responses, the agent returns tool results with typed parameters (city, temperature, conditions)
- \`useRenderTool\` maps each tool name to a React component, so \`get_weather\` renders a weather card with icons, temperature displays, and forecast details
- The agent decides when to call the tool based on context — it can mix tool-based UI generation with regular text responses
- This pattern enables agents to create dynamic, data-driven interfaces on demand`;
default:
// See getDemoInteraction's default for rationale. Keep the two
// switches in lockstep.
unauthoredDemoFeatures.add(featureId);
return `- TODO(${featureId}): technical details unauthored. Known authored ids: ${KNOWN_AUTHORED_FEATURE_IDS.join(
", ",
)}. Add a switch case in getDemoTechnicalDetails (and the peer getDemoInteraction) when documenting this demo.`;
}
}
function generateDemoReadme(
featureId: string,
feature: Feature | undefined,
): string {
return `# ${feature?.name || featureId}
## What This Demo Shows
${feature?.description || "TODO: Add description"}
## How to Interact
Try asking your Copilot to:
${getDemoInteraction(featureId)}
## Technical Details
What's happening technically:
${getDemoTechnicalDetails(featureId)}
## Building With This
If you're extending this demo or building something similar, here are key things to know:
### Styling Inside the Chat
Content rendered inside CopilotKit's chat area (via \`useRenderTool\`, \`useHumanInTheLoop\`, \`useFrontendTool\`) runs inside CopilotKit's component tree. Standard Tailwind classes may not work here because Tailwind v4 can't statically detect them.
**Use inline styles** for any UI rendered inside the chat:
\`\`\`tsx
// Do this
<div style={{ padding: "24px", borderRadius: "12px", background: "#fff" }}>
// Not this — Tailwind may purge these classes
<div className="p-6 rounded-xl bg-white">
\`\`\`
### Chat Layout
Wrap \`CopilotChat\` in a constraining div for proper spacing:
\`\`\`tsx
<div className="flex justify-center items-center h-screen w-full">
<div className="h-full w-full md:w-4/5 md:h-4/5 rounded-lg">
<CopilotChat className="h-full rounded-2xl max-w-6xl mx-auto" />
</div>
</div>
\`\`\`
### Overriding CopilotKit Styles
CopilotKit uses \`cpk:\` prefixed classes internally. To override them, create a **separate CSS file** (not in globals.css — Tailwind purges it):
\`\`\`css
/* copilotkit-overrides.css */
.copilotKitInput {
border-radius: 0.75rem;
border: 1px solid var(--copilot-kit-separator-color) !important;
}
\`\`\`
Import it in \`layout.tsx\` after \`globals.css\`.
### Images and Icons
- Don't reference local image files from agent-generated content (they won't exist). Add \`onError\` fallbacks.
- Use emoji instead of SVG icons inside chat messages (\`fill="currentColor"\` renders unpredictably in the chat context).
See the full [Styling Guide](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/STYLING-GUIDE.md) for more details.
`;
}
function generateRuntimeRoute(args: CLIArgs): string {
if (args.language === "typescript") {
return `import { NextRequest } from "next/server";
import {
CopilotRuntime,
ExperimentalEmptyAdapter,
copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
// TODO: Import the appropriate agent adapter for ${args.name}
// Examples:
// import { LangGraphAgent } from "@copilotkit/runtime/langgraph";
// import { MastraAgent } from "@ag-ui/mastra";
export const POST = async (req: NextRequest) => {
const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
endpoint: "/api/copilotkit",
serviceAdapter: new ExperimentalEmptyAdapter(),
runtime: new CopilotRuntime({
// TODO: Configure agents for ${args.name}
// agents: { default: new YourAgent({ ... }) },
}),
});
return handleRequest(req);
};
`;
}
return `import { NextRequest } from "next/server";
import {
CopilotRuntime,
ExperimentalEmptyAdapter,
copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
// The agent backend runs as a separate process on port 8000.
// This runtime proxies CopilotKit requests to it via AG-UI protocol.
const AGENT_URL = process.env.AGENT_URL || "http://localhost:8000";
export const POST = async (req: NextRequest) => {
const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
endpoint: "/api/copilotkit",
serviceAdapter: new ExperimentalEmptyAdapter(),
runtime: new CopilotRuntime({
// TODO: Configure the agent adapter for ${args.name}
// The adapter should point to AGENT_URL
}),
});
return handleRequest(req);
};
`;
}
function generateHealthRoute(args: CLIArgs): string {
const isLangGraph = args.name.startsWith("LangGraph");
const isInProcess = args.language === "typescript" && !isLangGraph;
const agentUrl = isInProcess
? ""
: isLangGraph
? "http://localhost:8123"
: "http://localhost:8000";
// LangGraph Platform (dev server default `:8123`) exposes `/ok`; our
// custom FastAPI backends expose `/health`. Individual starters may
// override the port (e.g. `examples/v2/interrupts-langgraph` uses
// `:8125`) — the template's constant below is only the default for
// newly-generated packages.
const probePath = isLangGraph ? "/ok" : "/health";
return `import { NextRequest, NextResponse } from "next/server";
// Baked at generation time (template-literal substitution) so the
// generated route can skip the fetch entirely for TypeScript in-process
// integrations rather than probing a bogus URL.
const IS_IN_PROCESS = ${isInProcess ? "true" : "false"};
// Resolve env first so we can distinguish "unset" (unconfigured) from
// "set but unreachable" (down). The baked fallback "${agentUrl}" keeps
// local dev working out-of-the-box but is only used when nothing is set.
const RAW_AGENT_URL = process.env.AGENT_URL || process.env.LANGGRAPH_DEPLOYMENT_URL;
const AGENT_URL = RAW_AGENT_URL || "${agentUrl}";
export async function GET(req: NextRequest) {
// Check agent backend reachability
let agentStatus: "unknown" | "in-process" | "ok" | "error" | "down" | "unconfigured" = "unknown";
let agentDetail = "";
if (IS_IN_PROCESS) {
// No out-of-process agent to probe; the runtime lives in this
// Next.js process, so treat it as healthy unconditionally.
agentStatus = "in-process";
} else if (!RAW_AGENT_URL) {
// Neither AGENT_URL nor LANGGRAPH_DEPLOYMENT_URL is set — surface this
// as a distinct status so operators can tell "missing config" apart
// from "network/backend down" without digging through logs.
agentStatus = "unconfigured";
agentDetail = "AGENT_URL / LANGGRAPH_DEPLOYMENT_URL env var not set";
} else {
try {
const res = await fetch(\`\${AGENT_URL}${probePath}\`, { signal: AbortSignal.timeout(3000) });
agentStatus = res.ok ? "ok" : "error";
agentDetail = \`HTTP \${res.status}\`;
} catch (err) {
agentStatus = "down";
agentDetail = err instanceof Error ? err.message : String(err);
// Log the underlying error so operators can see timeout vs DNS
// vs connection-refused without needing a debug token.
console.error(\`[health] agent probe failed (\${AGENT_URL}${probePath}): \${agentDetail}\`);
}
}
// Public response: safe to expose
const publicResponse: Record<string, unknown> = {
status: "ok",
integration: "${args.slug}",
agent: agentStatus,
timestamp: new Date().toISOString(),
};
// Extended diagnostics: only with debug token
const token = req.headers.get("x-debug-token") || req.nextUrl.searchParams.get("debug");
const expectedToken = process.env.SHOWCASE_DEBUG_TOKEN;
if (token && expectedToken && token === expectedToken) {
publicResponse.diagnostics = {
agent_url: IS_IN_PROCESS ? "(in-process)" : AGENT_URL,
agent_detail: agentDetail || undefined,
env: {
OPENAI_API_KEY: process.env.OPENAI_API_KEY ? "set" : "NOT SET",
ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY ? "set" : "NOT SET",
NODE_ENV: process.env.NODE_ENV,
PORT: process.env.PORT,
},
};
}
const httpStatus = agentStatus === "ok" || agentStatus === "in-process" ? 200 : 503;
return NextResponse.json(publicResponse, { status: httpStatus });
}
`;
}
function generateDebugRoute(args: CLIArgs): string {
const isLangGraph = args.name.startsWith("LangGraph");
// LangGraph Platform exposes /ok; our backends expose /health
const probePath = isLangGraph ? "/ok" : "/health";
return `import { NextRequest, NextResponse } from "next/server";
// Request log (in-memory ring buffer, last 50 requests)
const requestLog: Array<{ time: string; method: string; path: string; status: number; durationMs: number }> = [];
const MAX_LOG_SIZE = 50;
export function logRequest(method: string, path: string, status: number, durationMs: number) {
requestLog.push({ time: new Date().toISOString(), method, path, status, durationMs });
if (requestLog.length > MAX_LOG_SIZE) requestLog.shift();
}
export async function GET(req: NextRequest) {
// Token-gated: SHOWCASE_DEBUG_TOKEN must be set in env and matched
const token = req.headers.get("x-debug-token") || req.nextUrl.searchParams.get("token");
const expectedToken = process.env.SHOWCASE_DEBUG_TOKEN;
if (!expectedToken || !token || token !== expectedToken) {
return NextResponse.json({ error: "unauthorized" }, { status: 403 });
}
// Distinguish "env var not set" (unconfigured) from "set but unreachable"
// (down). Previously we fell back to the literal string "unknown" and
// then fetched "unknown${probePath}", which always TypeError'd and was
// reported as agent=down — indistinguishable from a real network failure.
const RAW_AGENT_URL = process.env.AGENT_URL || process.env.LANGGRAPH_DEPLOYMENT_URL;
const AGENT_URL = RAW_AGENT_URL || "unknown";
// Agent connectivity
let agentStatus = "unknown";
let agentDetail = "";
if (!RAW_AGENT_URL) {
agentStatus = "unconfigured";
agentDetail = "AGENT_URL / LANGGRAPH_DEPLOYMENT_URL env var not set";
} else {
try {
const res = await fetch(\`\${AGENT_URL}${probePath}\`, { signal: AbortSignal.timeout(3000) });
agentStatus = res.ok ? "ok" : "error";
agentDetail = \`HTTP \${res.status}\`;
} catch (e: unknown) {
agentStatus = "down";
agentDetail = e instanceof Error ? e.message : String(e);
console.error(\`[debug] agent probe failed (\${AGENT_URL}${probePath}): \${agentDetail}\`);
}
}
const uptime = process.uptime();
const mem = process.memoryUsage();
return NextResponse.json({
integration: "${args.slug}",
uptime: \`\${Math.floor(uptime / 60)}m \${Math.floor(uptime % 60)}s\`,
agent: { url: AGENT_URL, status: agentStatus, detail: agentDetail },
memory: {
rss: \`\${Math.round(mem.rss / 1024 / 1024)}MB\`,
heapUsed: \`\${Math.round(mem.heapUsed / 1024 / 1024)}MB\`,
},
env: {
NODE_ENV: process.env.NODE_ENV,
OPENAI_API_KEY: process.env.OPENAI_API_KEY ? "set" : "NOT SET",
ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY ? "set" : "NOT SET",
LANGSMITH_API_KEY: process.env.LANGSMITH_API_KEY ? "set" : "NOT SET",
},
recentRequests: requestLog.slice(-20),
nodeVersion: process.version,
});
}
`;
}
function generateErrorBoundary(): string {
return `"use client";
import React from "react";