@frankieai/core 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -32,6 +32,13 @@ function describeTool(toolName, input) {
32
32
  const skill = typeof input === "object" && input !== null ? input["skill"] : void 0;
33
33
  return typeof skill === "string" && skill.trim() ? `Using skill: ${skill.trim()}` : "Using a skill";
34
34
  }
35
+ const builtIn = /^frankie__([a-z0-9]+)__(.+)$/.exec(toolName);
36
+ if (builtIn) {
37
+ const [, group, action] = builtIn;
38
+ if (group === "docs") return "Search the docs";
39
+ if (group === "escalate") return "Escalate to a person";
40
+ return humanise(action ?? toolName);
41
+ }
35
42
  const mcp = /^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(toolName);
36
43
  if (mcp) {
37
44
  const [, server, tool] = mcp;
@@ -83,16 +90,21 @@ function toolDescriptions(config, toolIds) {
83
90
  for (const source of config.apis) {
84
91
  for (const capability of source.capabilities) {
85
92
  const id = `api__${source.name}__${capability.operationId.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 48)}`;
86
- if (wanted.has(id)) found.set(id, `${capability.method} ${capability.path}` + (capability.summary ? ` \u2014 ${capability.summary}` : ""));
93
+ if (wanted.has(id)) {
94
+ found.set(id, {
95
+ description: `${capability.method} ${capability.path}` + (capability.summary ? ` \u2014 ${capability.summary}` : ""),
96
+ ...capability.inputs ? { inputs: capability.inputs } : {}
97
+ });
98
+ }
87
99
  }
88
100
  }
89
101
  for (const source of config.mcpServers) {
90
102
  for (const tool of source.discoveredTools) {
91
103
  const id = `mcp__${source.name}__${tool.name}`;
92
- if (wanted.has(id)) found.set(id, tool.description || tool.name);
104
+ if (wanted.has(id)) found.set(id, { description: tool.description || tool.name, ...tool.inputs ? { inputs: tool.inputs } : {} });
93
105
  }
94
106
  }
95
- return toolIds.map((id) => ({ id, description: found.get(id) ?? id }));
107
+ return toolIds.map((id) => ({ id, ...found.get(id) ?? { description: id } }));
96
108
  }
97
109
  function suggestedPromptsFromSkills(config) {
98
110
  const seen = /* @__PURE__ */ new Set();
@@ -130,6 +142,8 @@ function draftSkill(goal, tools) {
130
142
  "",
131
143
  "Required inputs: note what each tool below needs, and ask the user for anything missing before calling it.",
132
144
  "",
145
+ "Quality bar: what makes a good result, not just a valid request. List the optional fields a complete item has (a description, a level, a length\u2026) and what a good value looks like; draft them from the conversation, ask for facts only the user knows, and show the full item for confirmation before saving.",
146
+ "",
133
147
  "Steps:",
134
148
  ...tools.map((tool, index) => `${index + 1}. ${tool.id}${tool.label ? ` \u2014 ${tool.label}` : ""}`),
135
149
  "Call only the tool that matches the user's actual request; respect the signed-in user's own permissions and confirm before any consequential write.",
@@ -235,7 +249,19 @@ var featuresConfigSchema = z2.object({
235
249
  * Internal dashboard mode: help administer existing workspaces, tools and
236
250
  * conversations without restarting the onboarding procedure.
237
251
  */
238
- configurationAssistant: z2.boolean().default(false)
252
+ configurationAssistant: z2.boolean().default(false),
253
+ /**
254
+ * Human escalation: give the agent a built-in tool to hand a conversation to
255
+ * the workspace's team when it can't resolve something or the visitor asks
256
+ * for a person. Each escalation is recorded on the conversation (a dashboard
257
+ * inbox) and, when `webhookUrl` is set, POSTed there (Slack, Zapier, a
258
+ * ticketing intake…). For support/landing-page agents.
259
+ */
260
+ escalation: z2.object({
261
+ enabled: z2.boolean().default(false),
262
+ /** Optional HTTPS endpoint that receives each escalation as JSON. */
263
+ webhookUrl: z2.string().url().startsWith("https://").max(2e3).optional()
264
+ }).prefault({})
239
265
  }).prefault({});
240
266
  var mcpServerSchema = z2.object({
241
267
  name: z2.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/i, "MCP server names must be alphanumeric with - or _"),
@@ -249,7 +275,8 @@ var mcpServerSchema = z2.object({
249
275
  enabled: z2.boolean().default(true),
250
276
  /** Explicit tool selection. Omitted keeps legacy all-tools behavior; [] disables all. */
251
277
  selectedTools: z2.array(z2.string().min(1)).optional(),
252
- discoveredTools: z2.array(z2.object({ name: z2.string(), description: z2.string().optional() })).default([]),
278
+ /** Tools the server listed at discovery; `inputs` summarizes each one's input schema for skill writing. */
279
+ discoveredTools: z2.array(z2.object({ name: z2.string(), description: z2.string().optional(), inputs: z2.string().optional() })).default([]),
253
280
  /** `http` covers streamable HTTP; `sse` is the legacy transport. */
254
281
  transport: z2.enum(["http", "sse"]).default("http"),
255
282
  url: z2.string().url(),
@@ -269,6 +296,14 @@ var apiCapabilitySchema = z2.object({
269
296
  method: z2.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
270
297
  path: z2.string().min(1),
271
298
  summary: z2.string().optional(),
299
+ /**
300
+ * One line naming what the operation takes — its path/query parameters and
301
+ * the request body's top-level fields, each marked required where the spec
302
+ * says so, with its description or allowed values. This is what lets a
303
+ * skill say which inputs to collect before calling the tool (and which it
304
+ * must never invent), instead of "check the tool's own parameters".
305
+ */
306
+ inputs: z2.string().optional(),
272
307
  /**
273
308
  * True when this is a write operation the spec requires auth for, but the
274
309
  * source has no way to authorize it as the specific calling user — no
@@ -469,6 +504,58 @@ var brandingConfigSchema = z2.object({
469
504
  avatarUrl: z2.string().url().optional(),
470
505
  launcherLabel: z2.string().default("Need a hand?")
471
506
  });
507
+ var knowledgeSourceSchema = z2.object({
508
+ url: z2.string().url().startsWith("https://").max(2e3)
509
+ });
510
+ var knowledgeBaseSchema = z2.object({
511
+ enabled: z2.boolean().default(false),
512
+ sources: z2.array(knowledgeSourceSchema).max(20).default([]),
513
+ /** Cap on pages fetched per source during a crawl. */
514
+ maxPages: z2.number().int().positive().max(200).default(40)
515
+ }).prefault({});
516
+ var personaProfileSchema = z2.object({
517
+ /** Stable lowercase slug, unique within the workspace. Baked into env var, branch and mount module. */
518
+ id: z2.string().min(1).max(40).regex(/^[a-z0-9][a-z0-9-]*$/, "Persona ids are lowercase slugs."),
519
+ /** Tab label and install-PR title suffix, e.g. "Knowledge base". */
520
+ label: z2.string().trim().min(1).max(60),
521
+ /** This persona's own publishable key. One key maps to exactly one persona. */
522
+ publishableKey: z2.string().min(8),
523
+ /** App-Router path globs this persona shows on. Empty = every page no other agent claims. */
524
+ pagePatterns: z2.array(z2.string().trim().min(1).max(200)).max(20).default([]),
525
+ /**
526
+ * Whether visitors may chat with this persona without signing in to the host
527
+ * app. Unset inherits the workspace's `auth.allowAnonymous`. A support or docs
528
+ * agent on public pages needs this on, or every logged-out visitor is told to
529
+ * sign in.
530
+ */
531
+ allowAnonymous: z2.boolean().optional(),
532
+ /**
533
+ * What this agent helps with, in the team's own words ("pricing, plans,
534
+ * getting started"). The one thing a team needs to write; the agent's role,
535
+ * greeting and instructions come from defaults. It is added to the agent's
536
+ * instructions at runtime (see `personaInstructions`).
537
+ */
538
+ scope: z2.string().trim().max(2e3).optional(),
539
+ /**
540
+ * Where to send people when the agent can't answer and it doesn't hand the
541
+ * chat to the team itself: a contact page (https) or an email (mailto:).
542
+ */
543
+ contactUrl: z2.string().trim().max(500).regex(/^(?:https:\/\/[^\s]+|mailto:[^\s@]+@[^\s@]+)$/, "Use an https:// link or a mailto: address.").optional(),
544
+ /**
545
+ * Shallow-merged over the workspace branding. Each field is optional with no
546
+ * default, so only the keys the persona sets override the workspace's — an
547
+ * absent field keeps the workspace value rather than resetting it.
548
+ */
549
+ branding: z2.object({
550
+ name: z2.string().optional(),
551
+ tagline: z2.string().optional(),
552
+ avatarUrl: z2.string().url().optional(),
553
+ launcherLabel: z2.string().optional()
554
+ }).optional(),
555
+ agent: agentConfigSchema.prefault({}),
556
+ features: featuresConfigSchema,
557
+ knowledgeBase: knowledgeBaseSchema
558
+ });
472
559
  var frankieConfigSchema = z2.object({
473
560
  tenantId: z2.string().min(1),
474
561
  branding: brandingConfigSchema.prefault({}),
@@ -483,7 +570,18 @@ var frankieConfigSchema = z2.object({
483
570
  skills: z2.array(skillSchema).max(30).default([]),
484
571
  limits: limitsConfigSchema.prefault({}),
485
572
  /** Opt-in end-user chat capabilities (attachments, model picker). */
486
- features: featuresConfigSchema
573
+ features: featuresConfigSchema,
574
+ /** Documentation the agent answers from, indexed for semantic retrieval. */
575
+ knowledgeBase: knowledgeBaseSchema,
576
+ /** App-Router path globs the primary (product) agent shows on. Empty = every page no persona claims. */
577
+ pagePatterns: z2.array(z2.string().trim().min(1).max(200)).max(20).default([]),
578
+ /**
579
+ * Additional embedded personas on this workspace. Empty for a single-agent
580
+ * workspace — the top-level agent/features/knowledgeBase + `auth.publishableKey`
581
+ * is the primary persona. Each entry resolves to its own one-agent config via
582
+ * its own publishable key, so the data plane still sees one config per key.
583
+ */
584
+ personas: z2.array(personaProfileSchema).max(8).default([])
487
585
  });
488
586
  var LEAKY_MODEL_MIGRATION = {
489
587
  "accounts/fireworks/models/kimi-k2p7-code": "accounts/fireworks/models/kimi-k3"
@@ -499,8 +597,73 @@ function parseFrankieConfig(input) {
499
597
  function defineFrankieConfig(config) {
500
598
  return config;
501
599
  }
600
+ function resolvePersonaConfig(config, publishableKey) {
601
+ if (publishableKey === config.auth.publishableKey) return config;
602
+ const persona = config.personas.find((entry) => entry.publishableKey === publishableKey);
603
+ if (!persona) return null;
604
+ return parseFrankieConfig({
605
+ ...config,
606
+ personas: [],
607
+ branding: { ...config.branding, ...persona.branding ?? {} },
608
+ auth: { ...config.auth, publishableKey: persona.publishableKey, allowAnonymous: persona.allowAnonymous ?? config.auth.allowAnonymous },
609
+ pagePatterns: persona.pagePatterns,
610
+ agent: { ...persona.agent, systemPrompt: personaInstructions(persona) },
611
+ features: persona.features,
612
+ knowledgeBase: persona.knowledgeBase
613
+ });
614
+ }
615
+ function personaInstructions(persona) {
616
+ const base = persona.agent.systemPrompt.trim();
617
+ const scope = persona.scope?.trim();
618
+ const handsOff = persona.features.escalation.enabled;
619
+ const contact = !handsOff ? persona.contactUrl?.trim() : void 0;
620
+ const fallback = handsOff ? "" : contact ? `When you can't answer from what you know, or someone asks for a person, say so briefly and point them to ${contact} to reach the team. Never guess.` : "When you can't answer from what you know, say so plainly. Never guess, and never promise that someone will follow up.";
621
+ const boundary = "Stay within this. If someone asks about something outside it, say briefly that it isn't something you can help with here" + (handsOff ? ", and offer to connect them with the team." : contact ? ", and share the contact link." : ".");
622
+ return [base, scope ? "What you help with, in the team's own words:\n" + scope + "\n\n" + boundary : "", fallback].filter(Boolean).join("\n\n");
623
+ }
624
+ function normalizeRoutePath(value) {
625
+ let path = (value || "/").split(/[?#]/)[0].trim();
626
+ if (!path.startsWith("/")) path = "/" + path;
627
+ if (path.length > 1 && path.endsWith("/")) path = path.slice(0, -1);
628
+ return path;
629
+ }
630
+ function matchesPagePattern(pathname, pattern) {
631
+ const path = normalizeRoutePath(pathname);
632
+ const pat = normalizeRoutePath(pattern);
633
+ const trailingDeep = pat.endsWith("/**");
634
+ const core = trailingDeep ? pat.slice(0, -3) : pat;
635
+ const escaped = core.replace(/[.+^${}()|[\]\\]/g, "\\$&");
636
+ const body = escaped.split("**").map((chunk) => chunk.replace(/\*/g, "[^/]*")).join(".*");
637
+ return new RegExp("^" + body + (trailingDeep ? "(?:/.*)?" : "") + "$").test(path);
638
+ }
639
+ function matchesAnyPagePattern(pathname, patterns) {
640
+ return patterns.length === 0 || patterns.some((pattern) => matchesPagePattern(pathname, pattern));
641
+ }
502
642
 
503
643
  // src/install.ts
644
+ function personaEnvKey(personaId) {
645
+ return "NEXT_PUBLIC_FRANKIE_KEY_" + personaId.toUpperCase().replace(/[^A-Z0-9]/g, "_");
646
+ }
647
+ var STANDARD_AGENT_IDS = ["support", "docs"];
648
+ function installAgentIds(personaIds = []) {
649
+ const custom = [...new Set(personaIds)].filter((id) => /^[a-z0-9][a-z0-9-]*$/.test(id) && !STANDARD_AGENT_IDS.includes(id)).sort();
650
+ return [...STANDARD_AGENT_IDS, ...custom];
651
+ }
652
+ function installBranch(workspaceId, baseSha, personaId) {
653
+ return "frankie/install-" + workspaceId + (personaId ? "--" + personaId : "") + "-" + baseSha.slice(0, 8);
654
+ }
655
+ function plainText(value, max = 80) {
656
+ const text = value.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/[`<>[\]()*_#|!\\]/g, "").replace(/\s+/g, " ").trim();
657
+ return text.length > max ? text.slice(0, max - 1).trimEnd() + "\u2026" : text;
658
+ }
659
+ function installTitle(personaLabel) {
660
+ return personaLabel ? "Install Frankie: " + plainText(personaLabel, 60) : "Install Frankie";
661
+ }
662
+ function matchesInstallBranch(ref, workspaceId, personaId) {
663
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
664
+ const mid = personaId ? escape(workspaceId) + "--?" + escape(personaId) : escape(workspaceId);
665
+ return new RegExp("^frankie/install-" + mid + "-[0-9a-f]{8}$").test(ref);
666
+ }
504
667
  function assertNoCommittedFrankieKeys(files) {
505
668
  for (const file of files) {
506
669
  if (/\bpk_live_[0-9a-f]{24}\b/i.test(file.content) || /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(file.content)) {
@@ -508,8 +671,17 @@ function assertNoCommittedFrankieKeys(files) {
508
671
  }
509
672
  }
510
673
  }
674
+ var ENV_BLOCK_START = "# --- Frankie (managed) ---";
675
+ var ENV_BLOCK_END = "# --- end Frankie ---";
676
+ var LEGACY_ENV_COMMENTS = [
677
+ "# Public at runtime, but inject it through your deployment environment instead of committing a workspace value.",
678
+ "# Server only: use the secret from this workspace. Never commit its value.",
679
+ "# This persona's publishable key. Public at runtime; set it in your deployment environment, don't commit a value."
680
+ ];
511
681
  function planHostedInstall(input) {
512
682
  const { files, workspace } = input;
683
+ const product = !input.persona;
684
+ const anonymous = workspace.allowAnonymous;
513
685
  const layouts = Object.keys(files).filter((p) => /(?:^|\/)(?:src\/)?app(?:\/\([^/]+\))?\/layout\.tsx$/.test(p));
514
686
  const roots = new Set(layouts.map((path) => path.replace(/app\/(?:\([^/]+\)\/)?layout\.tsx$/, "app/")));
515
687
  if (roots.size > 1) throw new Error("Multiple Next.js applications found. Run the installer from the intended app with the CLI; Frankie will not guess which app to modify.");
@@ -523,34 +695,70 @@ function planHostedInstall(input) {
523
695
  const pkg = JSON.parse(files[pkgPath] ?? "{}");
524
696
  if (!pkg.dependencies?.next) throw new Error("The selected app must have Next.js in dependencies.");
525
697
  const out = /* @__PURE__ */ new Map();
698
+ const deletions = [];
526
699
  const notes = [];
527
- const existingMount = files[layoutPath].includes("FrankieWidgetMount");
528
700
  const sourceRoot = appRoot.endsWith("src/app/") ? root + "src/" : root;
529
701
  const tokenPath = appRoot + "api/frankie/token/route.ts";
530
702
  const healthPath = appRoot + "api/frankie/health/route.ts";
531
- const auth = detectAuth(files, sourceRoot, pkg.dependencies);
532
- const authStrategy = workspace.allowAnonymous ? "anonymous" : files[tokenPath] ? "existing" : auth?.strategy ?? "unconfigured";
703
+ const agentsPath = appRoot + "frankie/FrankieAgents.tsx";
704
+ const chatModulePath = appRoot + "frankie/FrankieChatPage.tsx";
705
+ const importer = moduleImporter(files, root, sourceRoot);
706
+ const auth = detectAuth(files, sourceRoot, pkg.dependencies, (module) => importer(tokenPath, module));
707
+ const existingToken = files[tokenPath];
708
+ const authStrategy = anonymous ? "anonymous" : auth?.strategy ?? (existingToken && !existingToken.includes("AUTH_NOT_CONFIGURED") ? "existing" : "unconfigured");
533
709
  const needsAuthSetup = authStrategy === "unconfigured";
534
- if (needsAuthSetup) notes.push("No session lookup was detected. Export getCurrentUser from lib/frankie-auth.ts (see the generated token endpoint); until then it answers 501 and chat reports that sign-in is not wired.");
535
- if (authStrategy === "supabase") notes.push("Detected Supabase auth: the token endpoint verifies the user's Supabase access token and the widget forwards it automatically. Users must be signed in through Supabase.");
536
- pkg.dependencies = { ...pkg.dependencies, "@frankieai/react": pkg.dependencies["@frankieai/react"] ?? "^0.2.1", ...!workspace.allowAnonymous ? { jose: pkg.dependencies.jose ?? "^6.0.11" } : {} };
537
- out.set(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
538
- const authProp = workspace.allowAnonymous ? "" : " getUserToken={getUserToken}";
539
- const shared = `import { FrankieProvider, FrankieWidget, FrankieChatPage } from "@frankieai/react";
540
- import "@frankieai/react/styles.css";
541
- `;
542
- const clientAuthImport = auth?.client && !workspace.allowAnonymous ? `import { ${auth.client.name} } from "@/lib/supabase";
710
+ if (product && needsAuthSetup) notes.push("No session lookup was detected. Export getCurrentUser from lib/frankie-auth.ts (see the generated token endpoint); until then it answers 501 and chat reports that sign-in is not wired.");
711
+ if (product && authStrategy === "supabase") notes.push("Detected Supabase auth: the token endpoint verifies the user's Supabase access token and the widget forwards it automatically. Users must be signed in through Supabase.");
712
+ pkg.dependencies = withDependencies(pkg.dependencies, { "@frankieai/react": "^0.2.1", ...!anonymous ? { jose: "^6.0.11" } : {} });
713
+ out.set(pkgPath, renderJson(pkg, files[pkgPath]));
714
+ let manifest = {};
715
+ try {
716
+ const parsed = JSON.parse(files[root + "frankie.install.json"] ?? "{}");
717
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) manifest = parsed;
718
+ } catch {
719
+ }
720
+ const priorChat = manifest.workspaceId === workspace.id && (manifest.chatPath === "/chat" || manifest.chatPath === "/frankie/chat") ? manifest.chatPath : void 0;
721
+ const chatPath = priorChat ?? (files[integrationAppRoot + "chat/page.tsx"] ? "/frankie/chat" : "/chat");
722
+ let legacyChat = false;
723
+ for (const path of Object.keys(files).sort()) {
724
+ if (!path.startsWith(appRoot)) continue;
725
+ const legacy = path.match(/(?:^|\/)frankie\/(?:FrankieWidgetMount|FrankieSetupChat)\.tsx$/);
726
+ if (legacy) {
727
+ const exportsChat = /\bWorkspaceChatPage\b/.test(files[path]);
728
+ legacyChat ||= exportsChat;
729
+ out.set(path, `// Frankie now mounts every agent from FrankieAgents in the root layout.
730
+ // This module stays so existing imports keep working; it renders nothing.
731
+ export function FrankieWidgetMount() {
732
+ return null;
733
+ }
734
+ ${exportsChat ? `export { WorkspaceChatPage } from "${relativeImport(path, chatModulePath.slice(0, -4))}";
735
+ ` : ""}`);
736
+ }
737
+ if (/(?:^|\/)frankie\/FrankieWidget\.[a-z0-9][a-z0-9-]*\.tsx$/.test(path)) deletions.push(path);
738
+ }
739
+ const clientAuth = anonymous ? void 0 : auth?.client;
740
+ const clientAuthImport = clientAuth ? `import { ${clientAuth.name} } from "${importer(agentsPath, "lib/supabase")}";
543
741
  ` : "";
544
- const getToken = workspace.allowAnonymous ? "" : auth?.client ? `
545
- async function getUserToken() {
546
- const session = (await ${auth.client.name}?.auth.getSession())?.data.session;
547
- if (!session?.access_token) return undefined;
548
- const response = await fetch("/api/frankie/token", { method: "POST", headers: { Authorization: \`Bearer \${session.access_token}\` } });
742
+ const tokenHelpers = anonymous ? "" : clientAuth ? `
743
+ async function supabaseToken() {
744
+ const session = (await ${clientAuth.name}?.auth.getSession())?.data.session;
745
+ return session?.access_token;
746
+ }
747
+ /** The signed-in user's Frankie token, or undefined when nobody is signed in. */
748
+ export async function getUserToken() {
749
+ const accessToken = await supabaseToken();
750
+ if (!accessToken) return undefined;
751
+ const response = await fetch("/api/frankie/token", { method: "POST", headers: { Authorization: \`Bearer \${accessToken}\` } });
549
752
  if (!response.ok) return undefined;
550
753
  return ((await response.json()) as { token?: string }).token;
551
754
  }
755
+ const optionalUserToken = getUserToken;
756
+ async function productAvailable() {
757
+ return Boolean(await supabaseToken());
758
+ }
552
759
  ` : `
553
- async function getUserToken() {
760
+ /** The signed-in user's Frankie token; throws the reason chat can't start. */
761
+ export async function getUserToken() {
554
762
  const response = await fetch("/api/frankie/token", { method: "POST", credentials: "same-origin" });
555
763
  if (response.ok) return ((await response.json()) as { token?: string }).token;
556
764
  if (response.status === 401) throw new Error("Sign in to this app to use chat.");
@@ -558,65 +766,153 @@ async function getUserToken() {
558
766
  if (response.status === 503) throw new Error("Chat is not configured on the server yet (FRANKIE_JWT_SECRET is missing).");
559
767
  throw new Error("The chat sign-in endpoint returned " + response.status + ".");
560
768
  }
769
+ /** Support and docs agents chat with visitors too: who is signed in, if anyone. */
770
+ async function optionalUserToken() {
771
+ try {
772
+ const response = await fetch("/api/frankie/token", { method: "POST", credentials: "same-origin" });
773
+ return response.ok ? ((await response.json()) as { token?: string }).token : undefined;
774
+ } catch {
775
+ return undefined;
776
+ }
777
+ }
778
+ /** The product agent is for signed-in users. 501/503 still show it, so the widget can say what to fix. */
779
+ async function productAvailable() {
780
+ try {
781
+ const response = await fetch("/api/frankie/token", { method: "POST", credentials: "same-origin" });
782
+ return response.ok || response.status === 501 || response.status === 503;
783
+ } catch {
784
+ return false;
785
+ }
786
+ }
561
787
  `;
562
- const hostApiHeaders = auth?.client && !workspace.allowAnonymous ? `
563
- headers: async () => {
564
- const session = (await ${auth.client.name}?.auth.getSession())?.data.session;
788
+ const hostApiHeaders = clientAuth ? `
789
+ headers: async (): Promise<Record<string, string>> => {
790
+ const session = (await ${clientAuth.name}?.auth.getSession())?.data.session;
565
791
  return session?.access_token ? { Authorization: \`Bearer \${session.access_token}\` } : {};
566
792
  },` : "";
567
- const hostApi = `const hostApi = {
793
+ const hostApi = `export const hostApi = {
568
794
  baseUrl: typeof window !== "undefined" ? window.location.origin : "",
569
- credentials: "${auth?.client || workspace.allowAnonymous ? "same-origin" : "include"}" as const,${hostApiHeaders}
795
+ credentials: "${clientAuth || anonymous ? "same-origin" : "include"}" as const,${hostApiHeaders}
570
796
  };
571
797
  `;
572
- const apiProp = " api={hostApi}";
573
- let priorChat;
574
- try {
575
- const previous = JSON.parse(files[root + "frankie.install.json"] ?? "{}");
576
- if (previous.workspaceId === workspace.id && ["/chat", "/frankie/chat"].includes(previous.chatPath)) priorChat = previous.chatPath;
577
- } catch {
578
- }
579
- const chatPath = priorChat ?? (files[integrationAppRoot + "chat/page.tsx"] ? "/frankie/chat" : "/chat");
580
- if (!priorChat && files[integrationAppRoot + chatPath.slice(1) + "/page.tsx"]) throw new Error("Both /chat and /frankie/chat already exist. Choose a chat route manually.");
581
- out.set(root + "frankie.install.json", JSON.stringify({ workspaceId: workspace.id, chatPath }, null, 2) + "\n");
582
- if (chatPath !== "/chat") notes.push("Existing /chat preserved. Frankie chat is available at /frankie/chat.");
583
- const mount = `"use client";
798
+ const personaIds = installAgentIds([...input.agents ?? [], ...input.persona ? [input.persona.id] : []]);
799
+ const agentsModule = `"use client";
800
+ // Generated by Frankie. Every Frankie agent in this app mounts here, once, from
801
+ // the root layout. An agent turns on when its publishable key is set in the
802
+ // deployment environment, and shows on the pages chosen for it in Frankie.
803
+ import { useEffect, useState } from "react";
584
804
  import { usePathname } from "next/navigation";
585
- ${shared}${clientAuthImport}${getToken}${hostApi}
586
- export function FrankieWidgetMount() {
587
- const pathname = usePathname();
588
- const key = process.env.NEXT_PUBLIC_FRANKIE_KEY;
589
- if (!key || pathname === ${JSON.stringify(chatPath)}) return null;
590
- return <FrankieProvider publishableKey={key}${authProp}${apiProp}><FrankieWidget /></FrankieProvider>;
805
+ import { FrankieClient, FrankieProvider, FrankieWidget, type PublicWidgetConfig } from "@frankieai/react";
806
+ import "@frankieai/react/styles.css";
807
+ ${clientAuthImport}${tokenHelpers}${hostApi}
808
+ type Agent = { id: string; key: string | undefined };
809
+ // Literal process.env reads, so Next.js inlines each key at build time. Where
810
+ // two agents' pages overlap the earlier one wins; the product agent takes
811
+ // every page no other agent claims.
812
+ const PERSONAS: Agent[] = [
813
+ ${personaIds.map((id) => ` { id: ${JSON.stringify(id)}, key: process.env.${personaEnvKey(id)} },`).join("\n")}
814
+ ];
815
+ const PRODUCT: Agent = { id: "product", key: process.env.NEXT_PUBLIC_FRANKIE_KEY };
816
+ // The full-page chat never gets a floating launcher on top of it.
817
+ const CHAT_PATHS = ["/chat", "/frankie/chat"];
818
+
819
+ type Loaded = { config: PublicWidgetConfig | undefined; pages: string[] };
820
+ const loading = new Map<string, Promise<Loaded>>();
821
+ function load(key: string): Promise<Loaded> {
822
+ let pending = loading.get(key);
823
+ if (!pending) {
824
+ pending = new FrankieClient({ publishableKey: key })
825
+ .getConfig()
826
+ .then((config) => ({ config, pages: (config as { pages?: string[] }).pages ?? [] }))
827
+ .catch(() => ({ config: undefined, pages: [] }));
828
+ loading.set(key, pending);
829
+ }
830
+ return pending;
591
831
  }
832
+
833
+ function matchesAny(pathname: string, patterns: string[]): boolean {
834
+ if (!patterns.length) return true;
835
+ const path = (pathname || "/").split(/[?#]/)[0]!.replace(/(.)\\/+$/, "$1");
836
+ return patterns.some((pattern) => {
837
+ const pat = (pattern || "/").replace(/(.)\\/+$/, "$1");
838
+ const deep = pat.endsWith("/**");
839
+ const core = (deep ? pat.slice(0, -3) : pat).replace(/[.+^\${}()|[\\]\\\\]/g, "\\\\$&");
840
+ const body = core.split("**").map((chunk) => chunk.replace(/\\*/g, "[^/]*")).join(".*");
841
+ return new RegExp("^" + body + (deep ? "(?:/.*)?" : "") + "$").test(path);
842
+ });
843
+ }
844
+
845
+ function pick(pathname: string, loaded: Record<string, Loaded>, signedIn: boolean): { agent: Agent; key: string } | undefined {
846
+ if (CHAT_PATHS.includes(pathname)) return undefined;
847
+ const live = [...PERSONAS, PRODUCT].flatMap((agent) => (agent.key ? [{ agent, key: agent.key }] : []));
848
+ // Decide once every agent's pages are known, so one never flashes in before another.
849
+ if (live.some(({ key }) => !loaded[key])) return undefined;
850
+ const personas = live.filter(({ agent, key }) => agent !== PRODUCT && loaded[key]!.config);
851
+ const claimed = personas.find(({ key }) => loaded[key]!.pages.length > 0 && matchesAny(pathname, loaded[key]!.pages));
852
+ if (claimed) return claimed;
853
+ const product = live.find(({ agent }) => agent === PRODUCT);
854
+ if (product && signedIn && matchesAny(pathname, loaded[product.key]!.pages)) return product;
855
+ return personas.find(({ key }) => loaded[key]!.pages.length === 0);
856
+ }
857
+
858
+ export function FrankieAgents() {
859
+ const pathname = usePathname() || "/";
860
+ const [loaded, setLoaded] = useState<Record<string, Loaded>>({});
861
+ useEffect(() => {
862
+ let live = true;
863
+ for (const { key } of [...PERSONAS, PRODUCT]) {
864
+ if (key) void load(key).then((result) => { if (live) setLoaded((prev) => ({ ...prev, [key]: result })); });
865
+ }
866
+ return () => { live = false; };
867
+ }, []);
868
+ ${anonymous ? ` const signedIn = true;
869
+ ` : ` const [signedIn, setSignedIn] = useState(false);
870
+ useEffect(() => {
871
+ if (!PRODUCT.key) return;
872
+ let live = true;
873
+ void productAvailable().then((ok) => { if (live) setSignedIn(ok); });
874
+ return () => { live = false; };
875
+ }, [pathname]);
876
+ `} const active = pick(pathname, loaded, signedIn);
877
+ if (!active) return null;
878
+ return (
879
+ <FrankieProvider key={active.key} publishableKey={active.key} config={loaded[active.key]?.config}${anonymous ? "" : ` getUserToken={active.agent === PRODUCT ? getUserToken : optionalUserToken}`} api={hostApi}>
880
+ <FrankieWidget />
881
+ </FrankieProvider>
882
+ );
883
+ }
884
+ `;
885
+ out.set(agentsPath, agentsModule);
886
+ const rootLayout = files[rootLayoutPath];
887
+ if (!rootLayout.includes("FrankieAgents")) {
888
+ const mounted = mountWidget(rootLayout, "FrankieAgents");
889
+ if (!mounted) throw new Error("The root layout has no safe mount point. Add <FrankieAgents /> inside <body> manually.");
890
+ out.set(rootLayoutPath, insertImport(mounted, `import { FrankieAgents } from "./frankie/FrankieAgents";`));
891
+ }
892
+ if (product || legacyChat) {
893
+ out.set(chatModulePath, `"use client";
894
+ import { FrankieChatPage } from "@frankieai/react";
895
+ import "@frankieai/react/styles.css";
896
+ import { ${anonymous ? "" : "getUserToken, "}hostApi } from "./FrankieAgents";
897
+
592
898
  export function WorkspaceChatPage() {
593
899
  const key = process.env.NEXT_PUBLIC_FRANKIE_KEY;
594
900
  if (!key) return <p>Chat is not configured. Set NEXT_PUBLIC_FRANKIE_KEY in your deployment.</p>;
595
- return <FrankieChatPage publishableKey={key}${authProp}${apiProp} />;
901
+ return <FrankieChatPage publishableKey={key}${anonymous ? "" : " getUserToken={getUserToken}"} api={hostApi} />;
596
902
  }
597
- `;
598
- const moduleName = existingMount ? "FrankieSetupChat" : "FrankieWidgetMount";
599
- out.set(integrationAppRoot + "frankie/" + moduleName + ".tsx", mount);
600
- if (!existingMount) {
601
- const layout = files[layoutPath];
602
- const importLine = `import { FrankieWidgetMount } from "./frankie/FrankieWidgetMount";
603
- `;
604
- const withImport = /^["']use client["'];/.test(layout) ? layout.replace(/^(['"]use client['"];)/, "$1\n" + importLine) : importLine + layout;
605
- if (withImport.includes("</body>")) {
606
- out.set(layoutPath, withImport.replace("</body>", " <FrankieWidgetMount />\n</body>"));
607
- } else if (withImport.includes("</main>")) {
608
- out.set(layoutPath, withImport.replace("</main>", " <FrankieWidgetMount />\n</main>"));
609
- } else if (withImport.includes("{children}")) {
610
- out.set(layoutPath, withImport.replace("{children}", "{children}<FrankieWidgetMount />"));
611
- } else {
612
- throw new Error("The selected layout has no safe widget mount point. Add FrankieWidgetMount manually.");
613
- }
903
+ `);
614
904
  }
615
- const pageImport = chatPath === "/chat" ? "../frankie/" : "../../frankie/";
616
- out.set(integrationAppRoot + chatPath.slice(1) + "/page.tsx", `import { WorkspaceChatPage } from "${pageImport}${moduleName}";
905
+ if (product) {
906
+ if (!priorChat && files[integrationAppRoot + chatPath.slice(1) + "/page.tsx"]) throw new Error("Both /chat and /frankie/chat already exist. Choose a chat route manually.");
907
+ const pagePath = integrationAppRoot + chatPath.slice(1) + "/page.tsx";
908
+ out.set(pagePath, `import { WorkspaceChatPage } from "${relativeImport(pagePath, chatModulePath.slice(0, -4))}";
617
909
  export default WorkspaceChatPage;
618
910
  `);
619
- if (!workspace.allowAnonymous && !files[tokenPath]) {
911
+ const { personas: _legacyPersonas, ...kept2 } = manifest;
912
+ out.set(root + "frankie.install.json", JSON.stringify({ ...kept2, workspaceId: workspace.id, chatPath }, null, 2) + "\n");
913
+ if (chatPath !== "/chat") notes.push("Existing /chat preserved. Frankie chat is available at /frankie/chat.");
914
+ }
915
+ if (product && !anonymous && !files[tokenPath]) {
620
916
  const lookup = auth?.lookup ?? `// Frankie could not find your session lookup. Export it from lib/frankie-auth.ts:
621
917
  // export async function getCurrentUser(): Promise<{ id: string; name?: string; email?: string } | null>
622
918
  // then import it here in place of this stub.
@@ -644,8 +940,7 @@ export async function POST(${auth?.handlerParam ?? ""}) {
644
940
  }
645
941
  `);
646
942
  }
647
- if (!files[healthPath]) {
648
- out.set(healthPath, `import { NextResponse } from "next/server";
943
+ out.set(healthPath, `import { NextResponse } from "next/server";
649
944
 
650
945
  export const dynamic = "force-dynamic";
651
946
 
@@ -654,88 +949,128 @@ export async function GET() {
654
949
  {
655
950
  frankie: true,
656
951
  publishableKey: Boolean(process.env.NEXT_PUBLIC_FRANKIE_KEY),
952
+ agents: {
953
+ ${personaIds.map((id) => ` ${JSON.stringify(id)}: Boolean(process.env.${personaEnvKey(id)}),`).join("\n")}
954
+ },
657
955
  jwtSecret: Boolean(process.env.FRANKIE_JWT_SECRET),
658
956
  auth: ${JSON.stringify(authStrategy)},
659
- chatPath: ${JSON.stringify(chatPath)},
660
957
  },
661
958
  { headers: { "cache-control": "no-store", "access-control-allow-origin": "*" } },
662
959
  );
663
960
  }
664
961
  `);
665
- }
666
- let doc;
667
- for (const [path, content] of Object.entries(files)) {
668
- if (!/(?:openapi|swagger)[^/]*\.json$/i.test(path)) continue;
669
- try {
670
- const parsed = JSON.parse(content);
671
- if (parsed.openapi && parsed.paths) {
672
- doc = parsed;
673
- break;
962
+ let operationCount = 0;
963
+ const specPath = root + "public/frankie.openapi.json";
964
+ if (product) {
965
+ let doc;
966
+ for (const [path, content] of Object.entries(files)) {
967
+ if (!/(?:openapi|swagger)[^/]*\.json$/i.test(path)) continue;
968
+ try {
969
+ const parsed = JSON.parse(content);
970
+ if (parsed.openapi && parsed.paths) {
971
+ doc = parsed;
972
+ break;
973
+ }
974
+ } catch {
674
975
  }
675
- } catch {
676
976
  }
677
- }
678
- const middlewareMatchers = nextMiddlewareMatchers(files, sourceRoot, root);
679
- const paths = {};
680
- let withheld = 0;
681
- for (const [file, content] of Object.entries(files)) {
682
- if (/\.(test|spec)\.[tj]sx?$/.test(file)) continue;
683
- const nextRoute = file.match(/(?:^|\/)app(\/.*)\/route\.[tj]s$/);
684
- if (nextRoute) {
685
- const path = nextRoute[1].replace(/\/\([^/]+\)/g, "").replace(/\[([^\]]+)\]/g, "{$1}");
686
- if (path.includes("...") || /\/(?:auth|frankie)(?:\/|$)/.test(path)) continue;
687
- const guarded = matchesAnyMatcher(middlewareMatchers, path) || IN_HANDLER_AUTH_GUARD.test(content);
688
- for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE"]) {
689
- if (new RegExp("export\\s+(?:(?:async\\s+)?function\\s+" + method + "\\b|(?:const|let)\\s+" + method + "\\s*=)").test(content)) {
690
- if (!addInstallOperation(paths, method, path, file, guarded)) withheld += 1;
977
+ const middlewareMatchers = nextMiddlewareMatchers(files, sourceRoot, root);
978
+ const paths = {};
979
+ let withheld = 0;
980
+ for (const [file, content] of Object.entries(files)) {
981
+ if (/\.(test|spec)\.[tj]sx?$/.test(file)) continue;
982
+ const nextRoute = file.match(/(?:^|\/)app(\/.*)\/route\.[tj]s$/);
983
+ if (nextRoute) {
984
+ const path = nextRoute[1].replace(/\/\([^/]+\)/g, "").replace(/\[([^\]]+)\]/g, "{$1}");
985
+ if (path.includes("...") || /\/(?:auth|frankie)(?:\/|$)/.test(path)) continue;
986
+ const guarded = matchesAnyMatcher(middlewareMatchers, path) || IN_HANDLER_AUTH_GUARD.test(content);
987
+ for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE"]) {
988
+ if (new RegExp("export\\s+(?:(?:async\\s+)?function\\s+" + method + "\\b|(?:const|let)\\s+" + method + "\\s*=)").test(content)) {
989
+ if (!addInstallOperation(paths, method, path, file, guarded)) withheld += 1;
990
+ }
691
991
  }
992
+ } else if (/\.[tj]s$/.test(file) && /(?:routes?|api)\//.test(file)) {
993
+ for (const match of content.matchAll(/\b(?:app|router|fastify)\.(get|post|put|patch|delete)(?:\s*<[^;]{1,1600}?>)?\s*\(\s*["']([^"']+)["'](\s*,\s*[A-Za-z_$][\w$]*\s*,)?/g))
994
+ if (!addInstallOperation(paths, match[1].toUpperCase(), match[2].replace(/:([A-Za-z0-9_]+)/g, "{$1}"), file, Boolean(match[3]))) withheld += 1;
692
995
  }
693
- } else if (/\.[tj]s$/.test(file) && /(?:routes?|api)\//.test(file)) {
694
- for (const match of content.matchAll(/\b(?:app|router|fastify)\.(get|post|put|patch|delete)(?:\s*<[^;]{1,1600}?>)?\s*\(\s*["']([^"']+)["'](\s*,\s*[A-Za-z_$][\w$]*\s*,)?/g))
695
- if (!addInstallOperation(paths, match[1].toUpperCase(), match[2].replace(/:([A-Za-z0-9_]+)/g, "{$1}"), file, Boolean(match[3]))) withheld += 1;
696
996
  }
997
+ doc ??= { openapi: "3.0.3", info: { title: workspace.name + " API", version: "1.0.0", description: "Generated route inventory. Review schemas, authorization, and the deployed origin before enabling tools." }, paths };
998
+ for (const [path, item] of Object.entries(paths)) doc.paths[path] = { ...item, ...doc.paths[path] };
999
+ operationCount = Object.values(doc.paths).reduce((n, item) => n + Object.keys(item).filter((m) => /^(get|post|put|patch|delete)$/.test(m)).length, 0);
1000
+ out.set(specPath, JSON.stringify(doc, null, 2) + "\n");
1001
+ if (!operationCount) notes.push("No supported API routes detected. The OpenAPI draft has no operations; add the real schema before connecting tools.");
1002
+ if (withheld) notes.push(`Withheld ${withheld} newly discovered write operation(s) with no detected authorization guard (no Express/Fastify middleware argument, Next.js middleware.ts matcher covering the route, or in-handler auth check). Add them to the spec yourself once they're protected.`);
1003
+ notes.push("Generated OpenAPI includes read and write routes. Review schemas before approving tools; new connections still default to GET-only access.");
1004
+ notes.push("No public spec endpoint is required: Frankie connects this committed spec on install and reads later changes from your repository through the GitHub connection.");
1005
+ notes.push("The token endpoint issues a signed user JWT, but your product API must validate it and enforce user/resource permissions before exposing tools.");
1006
+ } else {
1007
+ const envKey = personaEnvKey(input.persona.id);
1008
+ notes.push(`${plainText(input.persona.label, 60)} turns on when ${envKey} is set in each frontend environment. Its pages come from Frankie at runtime, so changing them later needs no new pull request.`);
697
1009
  }
698
- doc ??= { openapi: "3.0.3", info: { title: workspace.name + " API", version: "1.0.0", description: "Generated route inventory. Review schemas, authorization, and the deployed origin before enabling tools." }, paths };
699
- for (const [path, item] of Object.entries(paths)) doc.paths[path] = { ...item, ...doc.paths[path] };
700
- const specPath = root + "public/frankie.openapi.json";
701
- const operationCount = Object.values(doc.paths).reduce((n, item) => n + Object.keys(item).filter((m) => /^(get|post|put|patch|delete)$/.test(m)).length, 0);
702
- out.set(specPath, JSON.stringify(doc, null, 2) + "\n");
703
- if (!operationCount) notes.push("No supported API routes detected. The OpenAPI draft has no operations; add the real schema before connecting tools.");
704
- if (withheld) notes.push(`Withheld ${withheld} newly discovered write operation(s) with no detected authorization guard (no Express/Fastify middleware argument, Next.js middleware.ts matcher covering the route, or in-handler auth check). Add them to the spec yourself once they're protected.`);
705
- notes.push("Generated OpenAPI includes read and write routes. Review schemas before approving tools; new connections still default to GET-only access.");
706
- notes.push("No public spec endpoint is required: Frankie connects this committed spec on install and reads later changes from your repository through the GitHub connection.");
707
- notes.push("The token endpoint issues a signed user JWT, but your product API must validate it and enforce user/resource permissions before exposing tools.");
708
1010
  const envPath = root + ".env.example";
709
- const env = (files[envPath] ?? "").replace(/^NEXT_PUBLIC_FRANKIE_KEY=.*\n?/gm, "").replace(/^FRANKIE_JWT_SECRET=.*\n?/gm, "").trimEnd();
710
- out.set(envPath, env + "\n# Public at runtime, but inject it through your deployment environment instead of committing a workspace value.\nNEXT_PUBLIC_FRANKIE_KEY=\n" + (workspace.allowAnonymous ? "" : "# Server only: use the secret from this workspace. Never commit its value.\nFRANKIE_JWT_SECRET=\n"));
711
- out.set(root + "FRANKIE_SETUP.md", `# Frankie setup
1011
+ const keyLine = /^(?:NEXT_PUBLIC_FRANKIE_KEY(?:_[A-Z0-9_]+)?|FRANKIE_JWT_SECRET)=.*$/;
1012
+ const kept = [];
1013
+ let inBlock = false;
1014
+ for (const line of (files[envPath] ?? "").split("\n")) {
1015
+ if (line === ENV_BLOCK_START) {
1016
+ inBlock = true;
1017
+ continue;
1018
+ }
1019
+ if (line === ENV_BLOCK_END) {
1020
+ inBlock = false;
1021
+ continue;
1022
+ }
1023
+ if (inBlock || keyLine.test(line) || LEGACY_ENV_COMMENTS.includes(line)) continue;
1024
+ kept.push(line);
1025
+ }
1026
+ const before = kept.join("\n").trimEnd();
1027
+ const block = [
1028
+ ENV_BLOCK_START,
1029
+ "# Publishable keys are public at runtime, but set them in your deployment environment instead of committing values. An agent stays off until its key is set.",
1030
+ "NEXT_PUBLIC_FRANKIE_KEY=",
1031
+ ...personaIds.map((id) => personaEnvKey(id) + "="),
1032
+ ...anonymous ? [] : ["# Server only: the secret from your Frankie workspace. Never commit its value or expose it to the browser.", "FRANKIE_JWT_SECRET="],
1033
+ ENV_BLOCK_END
1034
+ ].join("\n");
1035
+ out.set(envPath, (before ? before + "\n\n" : "") + block + "\n");
1036
+ if (product) {
1037
+ const keys = ["NEXT_PUBLIC_FRANKIE_KEY", ...personaIds.map(personaEnvKey)];
1038
+ out.set(root + "FRANKIE_SETUP.md", `# Frankie setup
712
1039
 
713
- Workspace: ${workspace.name}
1040
+ Workspace: ${plainText(workspace.name)}
714
1041
 
715
- 1. Copy NEXT_PUBLIC_FRANKIE_KEY from Frankie \u2192 Workspace \u2192 Developer details into the frontend deployment environment. Frankie deliberately leaves the value blank in this PR.
716
- ${workspace.allowAnonymous ? "" : "2. Add FRANKIE_JWT_SECRET from this workspace to the server hosting /api/frankie/token. Never commit the value.\n"}3. Run your package manager and commit the updated lockfile (for pnpm: pnpm install --lockfile-only). The remote GitHub installer cannot safely synthesize a lockfile.
717
- 4. Nothing to expose: this PR commits your spec to the repository, Frankie connects it for you on install, and later spec changes are read from your repository through the GitHub connection \u2014 no public spec endpoint or middleware bypass is required.
1042
+ 1. Copy NEXT_PUBLIC_FRANKIE_KEY from Frankie \u2192 Workspace \u2192 Developer details into every frontend deployment environment (Preview and Production). Frankie deliberately leaves the value blank in this PR.
1043
+ ${anonymous ? "" : "2. Add FRANKIE_JWT_SECRET from this workspace to the server hosting /api/frankie/token only. Never commit the value or expose it to the browser.\n"}3. Run your package manager and commit the updated lockfile (for pnpm: pnpm install --lockfile-only). The remote GitHub installer cannot safely synthesize a lockfile.
1044
+ 4. Nothing to expose: this PR commits your spec to the repository, Frankie connects it for you on install, and later spec changes are read from your repository through the GitHub connection.
718
1045
  5. Open ${chatPath}. It is created inside the detected authenticated dashboard group when one exists; add its link to the host sidebar during review.
719
- 6. In Frankie \u2192 Tools & MCP, approve the operations you want and choose access limits (the spec is already connected from this PR; it includes read and write routes). After merging later spec changes, use GitHub integration \u2192 Refresh Frankie from merged spec.
1046
+ 6. In Frankie \u2192 Tools & MCP, approve the operations you want and choose access limits. After merging later spec changes, use GitHub integration \u2192 Refresh Frankie from merged spec.
720
1047
  7. Forwarding sends the Frankie-signed JWT. Your API must validate it and enforce user/resource permissions. It is not automatically interchangeable with a Firebase or OAuth access token.
721
- 8. Add NEXT_PUBLIC_FRANKIE_KEY to every frontend deployment environment (Preview and Production). ${workspace.allowAnonymous ? "" : "Add FRANKIE_JWT_SECRET only to the server environment running /api/frankie/token; never expose it to the browser.\n"}9. Review conversations in Workspace \u2192 Chat sessions.
1048
+
1049
+ ## More agents
1050
+
1051
+ Every Frankie agent mounts from \`frankie/FrankieAgents.tsx\` in the root layout. To turn on another agent (Support, Docs), set its key in the deployment \u2014 no code change:
1052
+
1053
+ ${keys.map((key) => "- `" + key + "`").join("\n")}
1054
+
1055
+ Each agent shows on the pages chosen for it in Frankie; those are read at runtime.
722
1056
 
723
1057
  ## Remaining setup
724
1058
 
725
1059
  ${notes.map((n) => "- " + n).join("\n")}
726
1060
  `);
727
- const planned = [...out].map(([path, content]) => ({ path, content }));
1061
+ }
1062
+ const planned = [...out].filter(([path, content]) => files[path] !== content).map(([path, content]) => ({ path, content }));
728
1063
  assertNoCommittedFrankieKeys(planned);
729
- return { files: planned, root, chatPath, specPath, operationCount, needsAuthSetup, authStrategy, notes };
1064
+ return { files: planned, deletions, root, chatPath, specPath, operationCount, needsAuthSetup, authStrategy, notes };
730
1065
  }
731
1066
  var GET_CURRENT_USER = /export\s+(?:async\s+function\s+getCurrentUser\b|(?:const|let)\s+getCurrentUser\b|\{[^}]*\bgetCurrentUser\b[^}]*\})/;
732
1067
  var CUSTOM_AUTH_MODULES = ["lib/frankie-auth", "frankie/auth", "lib/auth", "lib/session", "lib/current-user", "lib/user", "server/auth", "auth"];
733
- function detectAuth(files, sourceRoot, deps) {
1068
+ function detectAuth(files, sourceRoot, deps, ref) {
734
1069
  for (const module of CUSTOM_AUTH_MODULES) {
735
1070
  for (const ext of [".ts", ".tsx", ".js"]) {
736
1071
  const source = files[sourceRoot + module + ext];
737
1072
  if (source && GET_CURRENT_USER.test(source)) {
738
- return { strategy: "custom", lookup: `import { getCurrentUser } from "@/${module}";
1073
+ return { strategy: "custom", lookup: `import { getCurrentUser } from "${ref(module)}";
739
1074
  ` };
740
1075
  }
741
1076
  }
@@ -744,8 +1079,8 @@ function detectAuth(files, sourceRoot, deps) {
744
1079
  return {
745
1080
  strategy: "firebase",
746
1081
  lookup: `import { cookies } from "next/headers";
747
- import { getAdminAuth } from "@/lib/firebase-admin";
748
- import { SESSION_COOKIE } from "@/lib/session";
1082
+ import { getAdminAuth } from "${ref("lib/firebase-admin")}";
1083
+ import { SESSION_COOKIE } from "${ref("lib/session")}";
749
1084
  async function getCurrentUser() {
750
1085
  const cookie = (await cookies()).get(SESSION_COOKIE)?.value;
751
1086
  if (!cookie) return null;
@@ -759,7 +1094,7 @@ async function getCurrentUser() {
759
1094
  if (authFile?.includes("NextAuth") && /export\s+(?:const|let)\s*\{[^}]*\bauth\b/.test(authFile)) {
760
1095
  return {
761
1096
  strategy: "nextauth",
762
- lookup: `import { auth } from "@/auth";
1097
+ lookup: `import { auth } from "${ref("auth")}";
763
1098
  async function getCurrentUser() {
764
1099
  const session = await auth();
765
1100
  const user = session?.user as { id?: string; name?: string | null; email?: string | null } | undefined;
@@ -837,6 +1172,107 @@ function matchesAnyMatcher(matchers, path) {
837
1172
  return new RegExp(`^${regexBody}$`).test(path);
838
1173
  });
839
1174
  }
1175
+ function insertImport(source, importLine) {
1176
+ const skip = [/^\s+/, /^\/\/[^\n]*/, /^\/\*[\s\S]*?\*\//];
1177
+ const keep = [/^["'][^"'\n]*["'][ \t]*;?/, /^import\s+(?:type\s+)?(?:[^"'`;]*?\sfrom\s*)?["'][^"'\n]+["'][ \t]*;?/];
1178
+ let at = 0;
1179
+ let afterPrologue = 0;
1180
+ let afterComments = 0;
1181
+ for (; ; ) {
1182
+ const rest = source.slice(at);
1183
+ const skipped = skip.map((pattern) => rest.match(pattern)?.[0]).find((hit) => hit);
1184
+ if (skipped) {
1185
+ at += skipped.length;
1186
+ if (!/^\s+$/.test(skipped) && afterPrologue === 0) afterComments = at;
1187
+ continue;
1188
+ }
1189
+ const kept = keep.map((pattern) => rest.match(pattern)?.[0]).find((hit) => hit);
1190
+ if (!kept) break;
1191
+ at += kept.length;
1192
+ afterPrologue = at;
1193
+ }
1194
+ const end = afterPrologue || afterComments;
1195
+ if (end === 0) return `${importLine}
1196
+
1197
+ ${source}`;
1198
+ return `${source.slice(0, end)}
1199
+ ${importLine}${source.slice(end)}`;
1200
+ }
1201
+ function mountWidget(layout, component = "FrankieWidgetMount") {
1202
+ const mount = `<${component} />`;
1203
+ for (const tag of ["</body>", "</main>"]) {
1204
+ const at = layout.indexOf(tag);
1205
+ if (at === -1) continue;
1206
+ const lineStart = layout.lastIndexOf("\n", at) + 1;
1207
+ const lead = layout.slice(lineStart, at);
1208
+ if (!/^[ \t]*$/.test(lead)) return `${layout.slice(0, at)}${mount}${layout.slice(at)}`;
1209
+ const unit = lead.includes(" ") ? " " : " ";
1210
+ return `${layout.slice(0, lineStart)}${lead}${unit}${mount}
1211
+ ${layout.slice(lineStart)}`;
1212
+ }
1213
+ return layout.includes("{children}") ? layout.replace("{children}", `{children}${mount}`) : void 0;
1214
+ }
1215
+ function withDependencies(current, added) {
1216
+ const existing = current ?? {};
1217
+ const merged = { ...existing };
1218
+ for (const [name, range] of Object.entries(added)) merged[name] ??= range;
1219
+ const names = Object.keys(existing);
1220
+ const sorted = [...names].sort((a, b) => a.localeCompare(b, "en"));
1221
+ if (names.some((name, index) => name !== sorted[index])) return merged;
1222
+ return Object.fromEntries(Object.keys(merged).sort((a, b) => a.localeCompare(b, "en")).map((name) => [name, merged[name]]));
1223
+ }
1224
+ function renderJson(value, original) {
1225
+ const indent = original?.match(/^([ \t]+)"/m)?.[1] ?? " ";
1226
+ const text = JSON.stringify(value, null, indent);
1227
+ return original === void 0 || original.endsWith("\n") ? `${text}
1228
+ ` : text;
1229
+ }
1230
+ function moduleImporter(files, root, sourceRoot) {
1231
+ const tsconfig = files[root + "tsconfig.json"];
1232
+ if (tsconfig === void 0) return (_from, module) => `@/${module}`;
1233
+ const alias = aliasFor(tsconfig, root, sourceRoot);
1234
+ if (alias !== void 0) return (_from, module) => `${alias}${module}`;
1235
+ return (from, module) => relativeImport(from, sourceRoot + module);
1236
+ }
1237
+ function aliasFor(tsconfig, root, sourceRoot) {
1238
+ let options;
1239
+ try {
1240
+ const parsed = JSON.parse(tsconfig.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "").replace(/,(\s*[}\]])/g, "$1"));
1241
+ options = parsed.compilerOptions;
1242
+ } catch {
1243
+ return void 0;
1244
+ }
1245
+ const paths = options?.paths;
1246
+ if (!paths || typeof paths !== "object") return void 0;
1247
+ const baseUrl = typeof options?.baseUrl === "string" ? options.baseUrl : ".";
1248
+ const target = normalizePath(sourceRoot);
1249
+ for (const [pattern, targets] of Object.entries(paths)) {
1250
+ if (!pattern.endsWith("/*") || !Array.isArray(targets)) continue;
1251
+ for (const entry of targets) {
1252
+ if (typeof entry !== "string" || !entry.endsWith("/*")) continue;
1253
+ if (normalizePath(`${root}${baseUrl}/${entry.slice(0, -1)}`) === target) return pattern.slice(0, -1);
1254
+ }
1255
+ }
1256
+ return void 0;
1257
+ }
1258
+ function normalizePath(path) {
1259
+ const out = [];
1260
+ for (const part of path.split("/")) {
1261
+ if (part === "" || part === ".") continue;
1262
+ if (part === "..") out.pop();
1263
+ else out.push(part);
1264
+ }
1265
+ return out.join("/") + "/";
1266
+ }
1267
+ function relativeImport(fromFile, module) {
1268
+ const from = normalizePath(fromFile.slice(0, fromFile.lastIndexOf("/") + 1)).split("/").filter(Boolean);
1269
+ const to = module.split("/").filter((part) => part !== "" && part !== ".");
1270
+ let common = 0;
1271
+ while (common < from.length && common < to.length && from[common] === to[common]) common += 1;
1272
+ const up = from.length - common;
1273
+ const rel = [...Array(up).fill(".."), ...to.slice(common)].join("/");
1274
+ return up === 0 ? `./${rel}` : rel;
1275
+ }
840
1276
 
841
1277
  // src/sdk-updates.ts
842
1278
  function sdkUpdateWorkflow(mode) {
@@ -1076,9 +1512,184 @@ function compareApiDocuments(before, after) {
1076
1512
  unchangedIds: [...next].filter(([key, value]) => old.get(key)?.fingerprint === value.fingerprint).map(([, value]) => value.id)
1077
1513
  };
1078
1514
  }
1515
+
1516
+ // src/theme-infer.ts
1517
+ var hex2 = (value) => Math.round(Math.min(255, Math.max(0, value))).toString(16).padStart(2, "0");
1518
+ var toHex = (r, g, b) => "#" + hex2(r) + hex2(g) + hex2(b);
1519
+ function hslToHex(h, s, l) {
1520
+ const sat = s / 100, light = l / 100;
1521
+ const k = (n) => (n + h / 30) % 12;
1522
+ const a = sat * Math.min(light, 1 - light);
1523
+ const f = (n) => light - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
1524
+ return toHex(f(0) * 255, f(8) * 255, f(4) * 255);
1525
+ }
1526
+ function oklchToHex(l, c, hDeg) {
1527
+ const h = hDeg * Math.PI / 180;
1528
+ const a = c * Math.cos(h), b = c * Math.sin(h);
1529
+ const l_ = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3;
1530
+ const m_ = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3;
1531
+ const s_ = (l - 0.0894841775 * a - 1.291485548 * b) ** 3;
1532
+ const linear = [
1533
+ 4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_,
1534
+ -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_,
1535
+ -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_
1536
+ ];
1537
+ const gamma = (x) => (x <= 31308e-7 ? 12.92 * x : 1.055 * x ** (1 / 2.4) - 0.055) * 255;
1538
+ return toHex(gamma(linear[0]), gamma(linear[1]), gamma(linear[2]));
1539
+ }
1540
+ var NUMBER = String.raw`-?\d*\.?\d+`;
1541
+ var parts = (body) => body.replace(/\/.*$/, "").split(/[\s,]+/).filter(Boolean);
1542
+ function normalizeColor(raw) {
1543
+ if (raw.length > 200) return void 0;
1544
+ const value = raw.trim().replace(/\s*!important$/, "").toLowerCase();
1545
+ let match = value.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
1546
+ if (match) {
1547
+ const digits = match[1];
1548
+ return digits.length <= 4 ? "#" + [...digits.slice(0, 3)].map((d) => d + d).join("") : "#" + digits.slice(0, 6);
1549
+ }
1550
+ match = value.match(/^rgba?\(([^)]*)\)$/);
1551
+ if (match) {
1552
+ const [r, g, b] = parts(match[1]).map((part) => part.endsWith("%") ? parseFloat(part) * 2.55 : parseFloat(part));
1553
+ return [r, g, b].every((n) => Number.isFinite(n)) ? toHex(r, g, b) : void 0;
1554
+ }
1555
+ match = value.match(/^hsla?\(([^)]*)\)$/) ?? value.match(new RegExp(`^(${NUMBER}(?:deg)?\\s+${NUMBER}%\\s+${NUMBER}%)$`));
1556
+ if (match) {
1557
+ const [h, s, l] = parts(match[1]).map((part) => parseFloat(part));
1558
+ return [h, s, l].every((n) => Number.isFinite(n)) ? hslToHex(h, s, l) : void 0;
1559
+ }
1560
+ match = value.match(/^oklch\(([^)]*)\)$/);
1561
+ if (match) {
1562
+ const [lRaw, cRaw, hRaw] = parts(match[1]);
1563
+ const l = lRaw?.endsWith("%") ? parseFloat(lRaw) / 100 : parseFloat(lRaw ?? "");
1564
+ const c = cRaw?.endsWith("%") ? parseFloat(cRaw) / 100 * 0.4 : parseFloat(cRaw ?? "");
1565
+ const h = hRaw === void 0 || hRaw === "none" ? 0 : parseFloat(hRaw);
1566
+ return [l, c, h].every((n) => Number.isFinite(n)) ? oklchToHex(l, c, h) : void 0;
1567
+ }
1568
+ return void 0;
1569
+ }
1570
+ function cssBlocks(source) {
1571
+ const blocks = [];
1572
+ let segmentStart = 0;
1573
+ for (let at = 0; at < source.length; ) {
1574
+ const open = source.indexOf("{", at);
1575
+ if (open === -1) break;
1576
+ const nextOpen = source.indexOf("{", open + 1);
1577
+ const close = source.indexOf("}", open + 1);
1578
+ if (close === -1) break;
1579
+ if (nextOpen !== -1 && nextOpen < close) {
1580
+ segmentStart = open + 1;
1581
+ at = open + 1;
1582
+ continue;
1583
+ }
1584
+ blocks.push([source.slice(segmentStart, open), source.slice(open + 1, close)]);
1585
+ segmentStart = close + 1;
1586
+ at = close + 1;
1587
+ }
1588
+ return blocks;
1589
+ }
1590
+ function customProperty(declaration) {
1591
+ const colon = declaration.indexOf(":");
1592
+ if (colon === -1) return void 0;
1593
+ const name = declaration.slice(0, colon).trim();
1594
+ const value = declaration.slice(colon + 1).trim();
1595
+ return name.length <= 100 && value.length <= 200 && /^--[\w-]+$/.test(name) && value ? [name, value] : void 0;
1596
+ }
1597
+ function rootVariables(css) {
1598
+ const vars = /* @__PURE__ */ new Map();
1599
+ const source = stripComments(css);
1600
+ for (const [rawSelector, body] of cssBlocks(source)) {
1601
+ const selector = rawSelector.split(";").pop().trim();
1602
+ if (selector.length > 1e3) continue;
1603
+ if (!/(?:^|[\s,]):root\b(?![^,]*\.dark)|^@theme\b/.test(selector) || /\.dark|\[data-theme/.test(selector)) continue;
1604
+ for (const declaration of body.split(";")) {
1605
+ const found = customProperty(declaration);
1606
+ if (found && !vars.has(found[0])) vars.set(found[0], found[1]);
1607
+ }
1608
+ }
1609
+ return vars;
1610
+ }
1611
+ function stripComments(css) {
1612
+ let out = "";
1613
+ for (let at = 0; ; ) {
1614
+ const start = css.indexOf("/*", at);
1615
+ if (start === -1) return out + css.slice(at);
1616
+ out += css.slice(at, start);
1617
+ const end = css.indexOf("*/", start + 2);
1618
+ if (end === -1) return out;
1619
+ at = end + 2;
1620
+ }
1621
+ }
1622
+ function resolve(value, vars, depth = 0) {
1623
+ if (depth > 4) return void 0;
1624
+ const reference = value.match(/^(?:(hsla?|oklch|rgba?)\(\s*)?var\(\s*(--[\w-]+)\s*(?:,[^)]*)?\)\s*\)?$/i);
1625
+ if (!reference) return normalizeColor(value);
1626
+ const inner = vars.get(reference[2]);
1627
+ if (!inner) return void 0;
1628
+ const wrapper = reference[1]?.toLowerCase();
1629
+ return wrapper && !/^\s*(?:#|[a-z]+\()/i.test(inner) ? normalizeColor(wrapper + "(" + inner + ")") : resolve(inner, vars, depth + 1);
1630
+ }
1631
+ function radiusOption(value) {
1632
+ const match = value.trim().match(/^(\d*\.?\d+)(rem|px)?$/);
1633
+ if (!match) return void 0;
1634
+ const rem = match[2] === "px" ? parseFloat(match[1]) / 16 : parseFloat(match[1]);
1635
+ return rem < 0.525 ? "0.35" : rem < 0.9 ? "0.7" : "1.1";
1636
+ }
1637
+ var CSS_PRIORITY = [/(?:^|\/)app\/globals\.css$/, /(?:^|\/)styles\/globals\.css$/, /globals\.css$/, /\.css$/];
1638
+ var PRIMARY_VARS = ["--primary", "--color-primary", "--brand", "--color-brand", "--accent", "--color-accent"];
1639
+ function rank(path) {
1640
+ const index = CSS_PRIORITY.findIndex((pattern) => pattern.test(path));
1641
+ return index === -1 ? CSS_PRIORITY.length : index;
1642
+ }
1643
+ function inferTheme(files, root = "") {
1644
+ const inRoot = (path) => path.startsWith(root) && !/(?:^|\/)(?:node_modules|dist|\.next|vendor|coverage)\//.test(path);
1645
+ const theme = {};
1646
+ const sources = [];
1647
+ const set = (field, value, path) => {
1648
+ if (!value || theme[field]) return;
1649
+ theme[field] = value;
1650
+ sources.push({ field, path });
1651
+ };
1652
+ const cssFiles = Object.keys(files).filter((path) => inRoot(path) && path.endsWith(".css")).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
1653
+ const vars = /* @__PURE__ */ new Map();
1654
+ const varPath = /* @__PURE__ */ new Map();
1655
+ for (const path of cssFiles) {
1656
+ for (const [name, value] of rootVariables(files[path])) if (!vars.has(name)) {
1657
+ vars.set(name, value);
1658
+ varPath.set(name, path);
1659
+ }
1660
+ }
1661
+ for (const name of PRIMARY_VARS) if (vars.has(name)) set("primary", resolve(vars.get(name), vars), varPath.get(name));
1662
+ for (const name of ["--background", "--color-background"]) if (vars.has(name)) set("background", resolve(vars.get(name), vars), varPath.get(name));
1663
+ for (const name of ["--foreground", "--color-foreground"]) if (vars.has(name)) set("foreground", resolve(vars.get(name), vars), varPath.get(name));
1664
+ if (vars.has("--radius")) set("radius", radiusOption(vars.get("--radius")), varPath.get("--radius"));
1665
+ for (const path of Object.keys(files).filter((p) => inRoot(p) && /(?:^|\/)tailwind\.config\.[cm]?[jt]s$/.test(p)).sort()) {
1666
+ const source = files[path];
1667
+ for (const key of ["primary", "brand", "accent"]) {
1668
+ const direct = source.match(new RegExp(`["']?${key}["']?\\s*:\\s*["'\`]([^"'\`]+)["'\`]`));
1669
+ const nested = source.match(new RegExp(`["']?${key}["']?\\s*:\\s*\\{[^}]*?DEFAULT\\s*:\\s*["'\`]([^"'\`]+)["'\`]`));
1670
+ const raw = direct?.[1] ?? nested?.[1];
1671
+ if (raw) set("primary", resolve(raw, vars), path);
1672
+ }
1673
+ }
1674
+ for (const path of Object.keys(files).filter((p) => inRoot(p) && /(?:^|\/)app\/(?:\([^/]+\)\/)?layout\.tsx$/.test(p)).sort()) {
1675
+ const raw = files[path].match(/themeColor\s*:\s*(?:\[\s*\{[^}]*?color\s*:\s*)?["'`]([^"'`]+)["'`]/)?.[1];
1676
+ if (raw) set("primary", normalizeColor(raw), path);
1677
+ }
1678
+ for (const path of Object.keys(files).filter((p) => inRoot(p) && /(?:^|\/)(?:manifest\.json|site\.webmanifest|manifest\.webmanifest)$/.test(p)).sort()) {
1679
+ try {
1680
+ const manifest = JSON.parse(files[path]);
1681
+ if (typeof manifest.theme_color === "string") set("primary", normalizeColor(manifest.theme_color), path);
1682
+ if (typeof manifest.background_color === "string") set("background", normalizeColor(manifest.background_color), path);
1683
+ } catch {
1684
+ }
1685
+ }
1686
+ if (!theme.primary) return void 0;
1687
+ return { theme: { ...theme, primary: theme.primary }, sources };
1688
+ }
1079
1689
  export {
1080
1690
  FIREWORKS_MODELS,
1081
1691
  SKILL_TOOL_NAME,
1692
+ STANDARD_AGENT_IDS,
1082
1693
  STARTER_PROMPT_ICONS,
1083
1694
  activeSkills,
1084
1695
  agentConfigSchema,
@@ -1098,14 +1709,33 @@ export {
1098
1709
  evaluateToolPolicy,
1099
1710
  featuresConfigSchema,
1100
1711
  frankieConfigSchema,
1712
+ inferTheme,
1713
+ insertImport,
1714
+ installAgentIds,
1715
+ installBranch,
1716
+ installTitle,
1717
+ knowledgeBaseSchema,
1718
+ knowledgeSourceSchema,
1101
1719
  limitsConfigSchema,
1102
1720
  matchPath,
1721
+ matchesAnyPagePattern,
1722
+ matchesInstallBranch,
1723
+ matchesPagePattern,
1103
1724
  mcpServerSchema,
1104
1725
  modelChoiceSchema,
1105
1726
  modelConfigSchema,
1727
+ moduleImporter,
1728
+ mountWidget,
1729
+ normalizeColor,
1106
1730
  operationId,
1107
1731
  parseFrankieConfig,
1732
+ personaEnvKey,
1733
+ personaInstructions,
1734
+ personaProfileSchema,
1735
+ plainText,
1108
1736
  planHostedInstall,
1737
+ renderJson,
1738
+ resolvePersonaConfig,
1109
1739
  sdkUpdateWorkflow,
1110
1740
  skillSchema,
1111
1741
  starterPromptSchema,
@@ -1114,6 +1744,7 @@ export {
1114
1744
  toolDescriptions,
1115
1745
  toolPolicySchema,
1116
1746
  validateApiDocument,
1117
- widgetThemeSchema
1747
+ widgetThemeSchema,
1748
+ withDependencies
1118
1749
  };
1119
1750
  //# sourceMappingURL=index.js.map