@runtypelabs/persona-proxy 2.3.0 → 3.8.4

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.cjs CHANGED
@@ -448,6 +448,17 @@ Cart has sourdough (qty 1) and croissant box (qty 1); user says "pay":
448
448
  };
449
449
 
450
450
  // src/utils/stripe.ts
451
+ var STRIPE_API_VERSION = "2026-03-25.dahlia";
452
+ function parseStripeApiErrorBody(body) {
453
+ var _a;
454
+ try {
455
+ const parsed = JSON.parse(body);
456
+ const msg = (_a = parsed == null ? void 0 : parsed.error) == null ? void 0 : _a.message;
457
+ return typeof msg === "string" && msg.length > 0 ? msg : void 0;
458
+ } catch {
459
+ return void 0;
460
+ }
461
+ }
451
462
  async function createCheckoutSession(options) {
452
463
  const { secretKey, items, successUrl, cancelUrl } = options;
453
464
  try {
@@ -464,6 +475,12 @@ async function createCheckoutSession(options) {
464
475
  error: "Each item must have name (string), price (number in cents), and quantity (number)"
465
476
  };
466
477
  }
478
+ if (!Number.isFinite(item.price) || !Number.isInteger(item.price) || item.price < 1 || !Number.isInteger(item.quantity) || item.quantity < 1) {
479
+ return {
480
+ success: false,
481
+ error: "Each item needs a positive integer price (cents) and quantity (Stripe rejects decimals or zero)"
482
+ };
483
+ }
467
484
  }
468
485
  const lineItems = items.map((item) => ({
469
486
  price_data: {
@@ -490,17 +507,19 @@ async function createCheckoutSession(options) {
490
507
  const stripeResponse = await fetch("https://api.stripe.com/v1/checkout/sessions", {
491
508
  method: "POST",
492
509
  headers: {
493
- "Authorization": `Bearer ${secretKey}`,
494
- "Content-Type": "application/x-www-form-urlencoded"
510
+ Authorization: `Bearer ${secretKey}`,
511
+ "Content-Type": "application/x-www-form-urlencoded",
512
+ "Stripe-Version": STRIPE_API_VERSION
495
513
  },
496
514
  body: params
497
515
  });
498
516
  if (!stripeResponse.ok) {
499
517
  const errorData = await stripeResponse.text();
518
+ const stripeMessage = parseStripeApiErrorBody(errorData);
500
519
  console.error("Stripe API error:", errorData);
501
520
  return {
502
521
  success: false,
503
- error: "Failed to create checkout session"
522
+ error: stripeMessage != null ? stripeMessage : "Failed to create checkout session"
504
523
  };
505
524
  }
506
525
  const session = await stripeResponse.json();
@@ -521,6 +540,14 @@ async function createCheckoutSession(options) {
521
540
  // src/index.ts
522
541
  var DEFAULT_ENDPOINT = "https://api.runtype.com/v1/dispatch";
523
542
  var DEFAULT_PATH = "/api/chat/dispatch";
543
+ var getRuntimeEnv = () => {
544
+ const maybeProcess = globalThis.process;
545
+ return maybeProcess == null ? void 0 : maybeProcess.env;
546
+ };
547
+ var isDevelopmentRuntime = () => {
548
+ var _a;
549
+ return ((_a = getRuntimeEnv()) == null ? void 0 : _a.NODE_ENV) === "development";
550
+ };
524
551
  var DEFAULT_FLOW = {
525
552
  name: "Streaming Prompt Flow",
526
553
  description: "Streaming chat generated by the widget",
@@ -548,7 +575,7 @@ var DEFAULT_FLOW = {
548
575
  };
549
576
  var withCors = (allowedOrigins) => async (c, next) => {
550
577
  const origin = c.req.header("origin");
551
- const isDevelopment = process.env.NODE_ENV === "development";
578
+ const isDevelopment = isDevelopmentRuntime();
552
579
  let corsOrigin;
553
580
  if (!allowedOrigins || allowedOrigins.length === 0) {
554
581
  corsOrigin = origin || "*";
@@ -602,15 +629,12 @@ var createChatProxyApp = (options = {}) => {
602
629
  return c.json({ error: "Missing messageId" }, 400);
603
630
  }
604
631
  payload.timestamp = (_a2 = payload.timestamp) != null ? _a2 : (/* @__PURE__ */ new Date()).toISOString();
605
- const isDevelopment = process.env.NODE_ENV === "development";
632
+ const isDevelopment = isDevelopmentRuntime();
606
633
  if (isDevelopment) {
607
634
  console.log("\n=== Feedback Received ===");
608
635
  console.log("Type:", payload.type);
609
636
  console.log("Message ID:", payload.messageId);
610
- console.log(
611
- "Content Preview:",
612
- (_c2 = (_b2 = payload.content) == null ? void 0 : _b2.substring(0, 100)) != null ? _c2 : "(none)"
613
- );
637
+ console.log("Content Length:", (_c2 = (_b2 = payload.content) == null ? void 0 : _b2.length) != null ? _c2 : 0);
614
638
  console.log("Timestamp:", payload.timestamp);
615
639
  console.log("=== End Feedback ===\n");
616
640
  }
@@ -633,8 +657,8 @@ var createChatProxyApp = (options = {}) => {
633
657
  });
634
658
  });
635
659
  app.post(path, async (c) => {
636
- var _a2, _b2, _c2, _d, _e;
637
- const apiKey = (_a2 = options.apiKey) != null ? _a2 : process.env.RUNTYPE_API_KEY;
660
+ var _a2, _b2, _c2, _d, _e, _f;
661
+ const apiKey = (_b2 = options.apiKey) != null ? _b2 : (_a2 = getRuntimeEnv()) == null ? void 0 : _a2.RUNTYPE_API_KEY;
638
662
  if (!apiKey) {
639
663
  return c.json(
640
664
  { error: "Missing API key. Set RUNTYPE_API_KEY." },
@@ -650,13 +674,13 @@ var createChatProxyApp = (options = {}) => {
650
674
  400
651
675
  );
652
676
  }
653
- const isDevelopment = process.env.NODE_ENV === "development";
677
+ const isDevelopment = isDevelopmentRuntime();
654
678
  const isAgentMode = !!clientPayload.agent;
655
679
  let runtypePayload;
656
680
  if (isAgentMode) {
657
681
  runtypePayload = clientPayload;
658
682
  } else {
659
- const messages = (_b2 = clientPayload.messages) != null ? _b2 : [];
683
+ const messages = (_c2 = clientPayload.messages) != null ? _c2 : [];
660
684
  const sortedMessages = [...messages].sort((a, b) => {
661
685
  const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
662
686
  const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
@@ -666,8 +690,8 @@ var createChatProxyApp = (options = {}) => {
666
690
  role: message.role,
667
691
  content: message.content
668
692
  }));
669
- const flowId = (_c2 = clientPayload.flowId) != null ? _c2 : options.flowId;
670
- const flowConfig = (_d = options.flowConfig) != null ? _d : DEFAULT_FLOW;
693
+ const flowId = (_d = clientPayload.flowId) != null ? _d : options.flowId;
694
+ const flowConfig = (_e = options.flowConfig) != null ? _e : DEFAULT_FLOW;
671
695
  runtypePayload = {
672
696
  record: {
673
697
  name: "Streaming Chat Widget",
@@ -725,7 +749,7 @@ var createChatProxyApp = (options = {}) => {
725
749
  return new Response(response.body, {
726
750
  status: response.status,
727
751
  headers: {
728
- "Content-Type": (_e = response.headers.get("content-type")) != null ? _e : "application/json",
752
+ "Content-Type": (_f = response.headers.get("content-type")) != null ? _f : "application/json",
729
753
  "Cache-Control": "no-store"
730
754
  }
731
755
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/flows/conversational.ts","../src/flows/scheduling.ts","../src/flows/shopping-assistant.ts","../src/flows/components.ts","../src/flows/bakery-assistant.ts","../src/utils/stripe.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport { handle } from \"hono/vercel\";\n\nexport type RuntypeFlowStep = {\n id: string;\n name: string;\n type: string;\n enabled: boolean;\n config: Record<string, unknown>;\n};\n\nexport type RuntypeFlowConfig = {\n name: string;\n description: string;\n steps: RuntypeFlowStep[];\n};\n\n\n\n/**\n * Payload for message feedback (upvote/downvote)\n */\nexport type FeedbackPayload = {\n type: \"upvote\" | \"downvote\";\n messageId: string;\n content?: string;\n timestamp?: string;\n sessionId?: string;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Handler function for processing feedback\n */\nexport type FeedbackHandler = (feedback: FeedbackPayload) => Promise<void> | void;\n\nexport type ChatProxyOptions = {\n upstreamUrl?: string;\n apiKey?: string;\n path?: string;\n allowedOrigins?: string[];\n flowId?: string;\n flowConfig?: RuntypeFlowConfig;\n /**\n * Path for the feedback endpoint (default: \"/api/feedback\")\n */\n feedbackPath?: string;\n /**\n * Custom handler for processing feedback.\n * Use this to store feedback in a database or send to analytics.\n * \n * @example\n * ```ts\n * onFeedback: async (feedback) => {\n * await db.feedback.create({ data: feedback });\n * }\n * ```\n */\n onFeedback?: FeedbackHandler;\n};\n\nconst DEFAULT_ENDPOINT = \"https://api.runtype.com/v1/dispatch\";\nconst DEFAULT_PATH = \"/api/chat/dispatch\";\n\nconst DEFAULT_FLOW: RuntypeFlowConfig = {\n name: \"Streaming Prompt Flow\",\n description: \"Streaming chat generated by the widget\",\n steps: [\n {\n id: \"widget_prompt\",\n name: \"Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n responseFormat: \"markdown\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: \"you are a helpful assistant, chatting with a user\",\n // tools: {\n // toolIds: [\n // \"builtin:dalle\"\n // ]\n // },\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n\nconst withCors =\n (allowedOrigins: string[] | undefined) =>\n async (c: Context, next: () => Promise<void>) => {\n const origin = c.req.header(\"origin\");\n const isDevelopment = process.env.NODE_ENV === \"development\";\n \n // Determine the CORS origin to allow\n let corsOrigin: string;\n if (!allowedOrigins || allowedOrigins.length === 0) {\n // No restrictions - allow any origin (or use the request origin)\n corsOrigin = origin || \"*\";\n } else if (allowedOrigins.includes(origin || \"\")) {\n // Origin is in the allowed list\n corsOrigin = origin || \"*\";\n } else if (isDevelopment && origin) {\n // In development, allow the actual origin even if not in the list\n // This helps with local development where ports might vary\n corsOrigin = origin;\n } else {\n // Production: origin not allowed - reject by not setting CORS headers\n // Return error for preflight, or continue without CORS headers\n if (c.req.method === \"OPTIONS\") {\n return c.json({ error: \"CORS policy violation: origin not allowed\" }, 403);\n }\n // For non-preflight requests, continue but browser will block due to missing CORS headers\n await next();\n return;\n }\n\n const headers: Record<string, string> = {\n \"Access-Control-Allow-Origin\": corsOrigin,\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n Vary: \"Origin\"\n };\n\n if (c.req.method === \"OPTIONS\") {\n return new Response(null, { status: 204, headers });\n }\n\n await next();\n Object.entries(headers).forEach(([key, value]) =>\n c.header(key, value, { append: false })\n );\n };\n\nexport const createChatProxyApp = (options: ChatProxyOptions = {}) => {\n const app = new Hono();\n const path = options.path ?? DEFAULT_PATH;\n const feedbackPath = options.feedbackPath ?? \"/api/feedback\";\n const upstream = options.upstreamUrl ?? DEFAULT_ENDPOINT;\n\n app.use(\"*\", withCors(options.allowedOrigins));\n\n // Feedback endpoint for collecting upvote/downvote data\n app.post(feedbackPath, async (c) => {\n let payload: FeedbackPayload;\n try {\n payload = await c.req.json();\n } catch (error) {\n return c.json({ error: \"Invalid JSON body\" }, 400);\n }\n\n // Validate payload\n if (!payload.type || ![\"upvote\", \"downvote\"].includes(payload.type)) {\n return c.json(\n { error: \"Invalid feedback type. Must be 'upvote' or 'downvote'\" },\n 400\n );\n }\n if (!payload.messageId) {\n return c.json({ error: \"Missing messageId\" }, 400);\n }\n\n // Add timestamp if not provided\n payload.timestamp = payload.timestamp ?? new Date().toISOString();\n\n const isDevelopment =\n process.env.NODE_ENV === \"development\";\n\n if (isDevelopment) {\n console.log(\"\\n=== Feedback Received ===\");\n console.log(\"Type:\", payload.type);\n console.log(\"Message ID:\", payload.messageId);\n console.log(\n \"Content Preview:\",\n payload.content?.substring(0, 100) ?? \"(none)\"\n );\n console.log(\"Timestamp:\", payload.timestamp);\n console.log(\"=== End Feedback ===\\n\");\n }\n\n // Call custom handler if provided\n if (options.onFeedback) {\n try {\n await options.onFeedback(payload);\n } catch (error) {\n console.error(\"[Feedback] Handler error:\", error);\n return c.json({ error: \"Feedback handler failed\" }, 500);\n }\n }\n\n return c.json({\n success: true,\n message: \"Feedback recorded\",\n feedback: {\n type: payload.type,\n messageId: payload.messageId,\n timestamp: payload.timestamp\n }\n });\n });\n\n // Chat dispatch endpoint\n app.post(path, async (c) => {\n const apiKey = options.apiKey ?? process.env.RUNTYPE_API_KEY;\n if (!apiKey) {\n return c.json(\n { error: \"Missing API key. Set RUNTYPE_API_KEY.\" },\n 401\n );\n }\n\n let clientPayload: Record<string, unknown>;\n try {\n clientPayload = await c.req.json();\n } catch (error) {\n return c.json(\n { error: \"Invalid JSON body\", details: error },\n 400\n );\n }\n\n const isDevelopment = process.env.NODE_ENV === \"development\";\n\n // Detect agent mode: if the payload contains an `agent` field, forward it directly\n const isAgentMode = !!clientPayload.agent;\n\n let runtypePayload: Record<string, unknown>;\n\n if (isAgentMode) {\n // Agent dispatch - forward the payload as-is to the upstream API\n runtypePayload = clientPayload;\n } else {\n // Flow dispatch - build the Runtype flow payload\n const messages = (clientPayload.messages ?? []) as Array<{ role: string; content: string; createdAt?: string }>;\n const sortedMessages = [...messages].sort((a, b) => {\n const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;\n const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;\n return timeA - timeB;\n });\n const formattedMessages = sortedMessages.map((message) => ({\n role: message.role,\n content: message.content\n }));\n\n const flowId = (clientPayload.flowId as string | undefined) ?? options.flowId;\n const flowConfig = options.flowConfig ?? DEFAULT_FLOW;\n\n runtypePayload = {\n record: {\n name: \"Streaming Chat Widget\",\n type: \"standalone\",\n metadata: (clientPayload.metadata as Record<string, unknown>) || {}\n },\n messages: formattedMessages,\n options: {\n streamResponse: true,\n recordMode: \"virtual\",\n flowMode: flowId ? \"existing\" : \"virtual\",\n autoAppendMetadata: false\n }\n };\n\n const clientInputs = clientPayload.inputs;\n if (clientInputs && typeof clientInputs === \"object\" && !Array.isArray(clientInputs)) {\n runtypePayload.inputs = clientInputs;\n }\n\n if (flowId) {\n runtypePayload.flow = { id: flowId };\n } else {\n runtypePayload.flow = flowConfig;\n }\n }\n\n if (isDevelopment) {\n console.log(`\\n=== Runtype Proxy Request (${isAgentMode ? \"agent\" : \"flow\"}) ===`);\n console.log(\"URL:\", upstream);\n console.log(\"API Key Used:\", apiKey ? \"Yes\" : \"No\");\n console.log(\"API Key (first 12 chars):\", apiKey ? apiKey.substring(0, 12) : \"N/A\");\n console.log(\"Request Payload:\", JSON.stringify(runtypePayload, null, 2));\n }\n\n const response = await fetch(upstream, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(runtypePayload)\n });\n\n if (isDevelopment) {\n console.log(\"Response Status:\", response.status);\n console.log(\"Response Status Text:\", response.statusText);\n\n // If there's an error, try to read and log the response body\n if (!response.ok) {\n const clonedResponse = response.clone();\n try {\n const errorBody = await clonedResponse.text();\n console.log(\"Error Response Body:\", errorBody);\n } catch (e) {\n console.log(\"Could not read error response body:\", e);\n }\n }\n console.log(\"=== End Runtype Proxy Request ===\\n\");\n }\n\n return new Response(response.body, {\n status: response.status,\n headers: {\n \"Content-Type\":\n response.headers.get(\"content-type\") ?? \"application/json\",\n \"Cache-Control\": \"no-store\"\n }\n });\n });\n\n return app;\n};\n\nexport const createVercelHandler = (options?: ChatProxyOptions) =>\n handle(createChatProxyApp(options));\n\n// Export pre-configured flows\nexport * from \"./flows/index.js\";\n\n// Export utility functions\nexport * from \"./utils/index.js\";\n\nexport default createChatProxyApp;\n\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Basic conversational assistant flow\n * This is the default flow for simple chat interactions\n */\nexport const CONVERSATIONAL_FLOW: RuntypeFlowConfig = {\n name: \"Streaming Prompt Flow\",\n description: \"Streaming chat generated by the widget\",\n steps: [\n {\n id: \"widget_prompt\",\n name: \"Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n responseFormat: \"markdown\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: \"you are a helpful assistant, chatting with a user\",\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Dynamic Form flow configuration\n * This flow returns forms as component directives for the widget to render\n */\nexport const FORM_DIRECTIVE_FLOW: RuntypeFlowConfig = {\n name: \"Dynamic Form Flow\",\n description: \"Returns dynamic forms as component directives\",\n steps: [\n {\n id: \"form_prompt\",\n name: \"Form Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful assistant that can have conversations and collect user information via forms.\n\nRESPONSE FORMAT:\nAlways respond with valid JSON. Choose the appropriate format:\n\n1. For CONVERSATIONAL responses or text answers:\n {\"text\": \"Your response here\"}\n\n2. When the user wants to SCHEDULE, BOOK, SIGN UP, or provide DETAILS (show a form):\n {\"component\": \"DynamicForm\", \"props\": {\"title\": \"Form Title\", \"description\": \"Optional description\", \"fields\": [...], \"submit_text\": \"Submit\"}}\n\n3. For BOTH explanation AND form:\n {\"text\": \"Your explanation\", \"component\": \"DynamicForm\", \"props\": {...}}\n\nFORM FIELD FORMAT:\nEach field in the \"fields\" array should have:\n- label (required): Display name for the field\n- name (optional): Field identifier (defaults to lowercase label with underscores)\n- type (optional): \"text\", \"email\", \"tel\", \"date\", \"time\", \"textarea\", \"number\" (defaults to \"text\")\n- placeholder (optional): Placeholder text\n- required (optional): true/false\n\nEXAMPLES:\n\nUser: \"Schedule a demo for me\"\nResponse: {\"text\": \"I'd be happy to help you schedule a demo! Please fill out the form below:\", \"component\": \"DynamicForm\", \"props\": {\"title\": \"Schedule a Demo\", \"description\": \"Share your details and we'll follow up with a confirmation.\", \"fields\": [{\"label\": \"Full Name\", \"type\": \"text\", \"required\": true}, {\"label\": \"Email\", \"type\": \"email\", \"required\": true}, {\"label\": \"Company\", \"type\": \"text\"}, {\"label\": \"Preferred Date\", \"type\": \"date\", \"required\": true}, {\"label\": \"Notes\", \"type\": \"textarea\", \"placeholder\": \"Any specific topics you'd like to cover?\"}], \"submit_text\": \"Request Demo\"}}\n\nUser: \"What is AI?\"\nResponse: {\"text\": \"AI (Artificial Intelligence) refers to computer systems designed to perform tasks that typically require human intelligence, such as learning, reasoning, problem-solving, and understanding language.\"}\n\nUser: \"Collect my contact details\"\nResponse: {\"component\": \"DynamicForm\", \"props\": {\"title\": \"Contact Details\", \"fields\": [{\"label\": \"Name\", \"type\": \"text\", \"required\": true}, {\"label\": \"Email\", \"type\": \"email\", \"required\": true}, {\"label\": \"Phone\", \"type\": \"tel\"}], \"submit_text\": \"Save Details\"}}\n\nIMPORTANT:\n- Use {\"text\": \"...\"} for questions, explanations, and general conversation\n- Show a DynamicForm when user wants to provide information, schedule, book, or sign up\n- Create contextually appropriate form fields based on what the user is trying to do\n- Keep forms focused with only the relevant fields needed`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Shopping assistant flow configuration\n * This flow returns JSON actions for page interaction including:\n * - Simple messages\n * - Navigation with messages\n * - Element clicks with messages\n * - Stripe checkout\n */\nexport const SHOPPING_ASSISTANT_FLOW: RuntypeFlowConfig = {\n name: \"Shopping Assistant Flow\",\n description: \"Returns JSON actions for page interaction\",\n steps: [\n {\n id: \"action_prompt\",\n name: \"Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant that can interact with web pages.\nYou will receive information about the current page's elements (class names and text content)\nand user messages. You must respond with JSON in one of these formats:\n\n1. Simple message:\n{\n \"action\": \"message\",\n \"text\": \"Your response text here\"\n}\n\n2. Navigate then show message (for navigation to another page):\n{\n \"action\": \"nav_then_click\",\n \"page\": \"http://site.com/page-url\",\n \"on_load_text\": \"Message to show after navigation\"\n}\n\n3. Show message and click an element:\n{\n \"action\": \"message_and_click\",\n \"element\": \".className-of-element\",\n \"text\": \"Your message text\"\n}\n\n4. Create Stripe checkout:\n{\n \"action\": \"checkout\",\n \"text\": \"Your message text\",\n \"items\": [\n {\"name\": \"Product Name\", \"price\": 2999, \"quantity\": 1}\n ]\n}\n\nGuidelines:\n- Use \"message\" for simple conversational responses\n- Use \"nav_then_click\" when you need to navigate to a different page (like a product detail page)\n- Use \"message_and_click\" when you want to click a button or element on the current page\n- Use \"checkout\" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)\n- When selecting elements, use the class names provided in the page context\n- Always respond with valid JSON only, no additional text\n- For product searches, format results as markdown links: [Product Name](url)\n- Be helpful and conversational in your messages\n- Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)\n\nExample conversation flow:\n- User: \"I am looking for a black shirt in medium\"\n- You: {\"action\": \"message\", \"text\": \"Here are the products I found:\\\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\\\n\\\\nWould you like me to navigate to the first result and add it to your cart?\"}\n\n- User: \"No, I would like to add another shirt to the cart\"\n- You: {\"action\": \"message_and_click\", \"element\": \".AddToCartButton-blue-shirt-large\", \"text\": \"I've added the Blue Shirt - Large to your cart. Ready to checkout?\"}\n\n- User: \"yes\"\n- You: {\"action\": \"checkout\", \"text\": \"Perfect! I'll set up the checkout for you.\", \"items\": [{\"name\": \"Black Shirt - Medium\", \"price\": 2999, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n\n/**\n * Metadata-based shopping assistant flow configuration\n * This flow uses DOM context from record metadata instead of user message.\n * The metadata should include dom_elements, dom_body, page_url, and page_title.\n */\nexport const SHOPPING_ASSISTANT_METADATA_FLOW: RuntypeFlowConfig = {\n name: \"Metadata-Based Shopping Assistant\",\n description: \"Uses DOM context from record metadata for page interaction\",\n steps: [\n {\n id: \"metadata_action_prompt\",\n name: \"Metadata Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant that can interact with web pages.\n\nIMPORTANT: You have access to the current page's DOM elements through the record metadata, which includes:\n- dom_elements: Array of page elements with className, innerText, and tagName\n- dom_body: Complete HTML body of the page (if provided)\n- page_url: Current page URL\n- page_title: Page title\n\nThe dom_elements array provides information about clickable elements and their text content.\nUse this metadata to understand what's available on the page and help users interact with it.\n\nYou must respond with JSON in one of these formats:\n\n1. Simple message:\n{\n \"action\": \"message\",\n \"text\": \"Your response text here\"\n}\n\n2. Navigate then show message (for navigation to another page):\n{\n \"action\": \"nav_then_click\",\n \"page\": \"http://site.com/page-url\",\n \"on_load_text\": \"Message to show after navigation\"\n}\n\n3. Show message and click an element:\n{\n \"action\": \"message_and_click\",\n \"element\": \".className-of-element\",\n \"text\": \"Your message text\"\n}\n\n4. Create Stripe checkout:\n{\n \"action\": \"checkout\",\n \"text\": \"Your message text\",\n \"items\": [\n {\"name\": \"Product Name\", \"price\": 2999, \"quantity\": 1}\n ]\n}\n\nGuidelines:\n- Use \"message\" for simple conversational responses\n- Use \"nav_then_click\" when you need to navigate to a different page (like a product detail page)\n- Use \"message_and_click\" when you want to click a button or element on the current page\n- Use \"checkout\" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)\n- When selecting elements, use the class names from the dom_elements in the metadata\n- Always respond with valid JSON only, no additional text\n- For product searches, format results as markdown links: [Product Name](url)\n- Be helpful and conversational in your messages\n- Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)\n\nExample conversation flow:\n- User: \"I am looking for a black shirt in medium\"\n- You: {\"action\": \"message\", \"text\": \"Here are the products I found:\\\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\\\n\\\\nWould you like me to navigate to the first result and add it to your cart?\"}\n\n- User: \"No, I would like to add another shirt to the cart\"\n- You: {\"action\": \"message_and_click\", \"element\": \".AddToCartButton-blue-shirt-large\", \"text\": \"I've added the Blue Shirt - Large to your cart. Ready to checkout?\"}\n\n- User: \"yes\"\n- You: {\"action\": \"checkout\", \"text\": \"Perfect! I'll set up the checkout for you.\", \"items\": [{\"name\": \"Black Shirt - Medium\", \"price\": 2999, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Component-aware flow for custom component rendering\n * This flow instructs the AI to respond with component directives in JSON format\n */\nexport const COMPONENT_FLOW: RuntypeFlowConfig = {\n name: \"Component Flow\",\n description: \"Flow configured for custom component rendering\",\n steps: [\n {\n id: \"component_prompt\",\n name: \"Component Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful assistant that can both have conversations and render custom UI components.\n\nRESPONSE FORMAT:\nAlways respond with valid JSON. Choose the appropriate format based on the user's request:\n\n1. For CONVERSATIONAL questions or text responses:\n {\"text\": \"Your response here\"}\n\n2. For VISUAL DISPLAYS or when the user asks to SHOW/DISPLAY something:\n {\"component\": \"ComponentName\", \"props\": {...}}\n\n3. For BOTH explanation AND visual:\n {\"text\": \"Your explanation here\", \"component\": \"ComponentName\", \"props\": {...}}\n\nAvailable components for visual displays:\n- ProductCard: Display product information. Props: title (string), price (number), description (string, optional), image (string, optional)\n- SimpleChart: Display a bar chart. Props: title (string), data (array of numbers), labels (array of strings, optional)\n- StatusBadge: Display a status badge. Props: status (string: \"success\", \"error\", \"warning\", \"info\", \"pending\"), message (string)\n- InfoCard: Display an information card. Props: title (string), content (string), icon (string, optional)\n\nExamples:\n- User asks \"What is the capital of France?\": {\"text\": \"The capital of France is Paris.\"}\n- User asks \"What does that chart show?\": {\"text\": \"The chart shows sales data increasing from 100 to 200 over three months.\"}\n- User asks \"Show me a product card\": {\"component\": \"ProductCard\", \"props\": {\"title\": \"Laptop\", \"price\": 999, \"description\": \"A great laptop\"}}\n- User asks \"Display a chart\": {\"component\": \"SimpleChart\", \"props\": {\"title\": \"Sales\", \"data\": [100, 150, 200], \"labels\": [\"Jan\", \"Feb\", \"Mar\"]}}\n- User asks \"Show me a chart and explain it\": {\"text\": \"Here's the sales data for Q1:\", \"component\": \"SimpleChart\", \"props\": {\"title\": \"Q1 Sales\", \"data\": [100, 150, 200], \"labels\": [\"Jan\", \"Feb\", \"Mar\"]}}\n\nIMPORTANT:\n- Use {\"text\": \"...\"} for questions, explanations, discussions, and general chat\n- Use {\"component\": \"...\", \"props\": {...}} ONLY when the user explicitly wants to SEE/VIEW/DISPLAY visual content\n- You can combine both: {\"text\": \"...\", \"component\": \"...\", \"props\": {...}} when you want to explain something AND show a visual\n- Never force a component when the user just wants information`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Bakery assistant flow configuration for \"Flour & Stone\" bakery demo\n * This flow returns JSON actions for page interaction including:\n * - Simple messages with bakery brand voice\n * - Navigation to bakery pages\n * - Add to cart interactions\n * - Stripe checkout\n *\n * Designed to guide users toward the gift card when asking for gift recommendations.\n */\nexport const BAKERY_ASSISTANT_FLOW: RuntypeFlowConfig = {\n name: \"Bakery Assistant Flow\",\n description: \"Flour & Stone bakery shopping assistant with gift recommendations\",\n steps: [\n {\n id: \"bakery_action_prompt\",\n name: \"Bakery Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant for Flour & Stone, a premium artisan bakery known for traditional bread-making and exceptional pastries.\n\nBrand voice: Warm, knowledgeable, passionate about craft baking. Use phrases like \"fresh from the oven\", \"handcrafted with care\", \"artisan tradition\". Do not explain selectors, JSON, or templating to the user.\n\n## Live context (request inputs — substituted each turn)\n\nThe widget sends **only** these keys as dispatch **inputs** (nothing extra on the record for this demo).\n\n**Orientation**\n- Path: {{current_page}} (compare before nav_then_click; e.g. /bakery-goods.html)\n- Full URL: {{page_url}}\n- Title: {{page_title}}\n\n**Page DOM**\n- page_elements: JSON array of enriched nodes (selector, tagName, text, role, interactivity, attributes including data-*). Prefer **selector** for message_and_click when you click a specific control.\n- page_context: Same slice formatted for the LLM (structured card summaries when matched, then groups by interactivity).\n\n{{page_elements}}\n\n{{page_context}}\n\n**Cart (for checkout — mirror cart.items when user pays)**\n{{cart}}\n\n**Recent order (if any)**\n{{recent_order}}\n\nIf {{current_page}} already equals the page you would navigate to, use {\"action\":\"message\",...} instead of nav_then_click.\n\n## Discovering products\n\nUse {{page_context}} for a quick scan and {{page_elements}} for exact selectors and attributes. Product rows often include data-product in **attributes**; prices appear in **text**; add-to-cart controls are usually **clickable** with stable **selector** values.\n\n## Output: one JSON object only\n\nNo markdown fences, no commentary before/after. Valid JSON only.\n\n### 1. message\n{\"action\": \"message\", \"text\": \"...\"}\nUse for chat, clarifying questions, \"we're already on that page\", or when you need the user to choose (e.g. $25 vs $50 gift card).\n\n### 2. nav_then_click\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"...\"}\nUse root-relative paths starting with /. Only when current_page is different from the target. This **only** changes pages — it does **not** open Stripe or payment.\n\n### 3. add_to_cart\n{\"action\": \"add_to_cart\", \"text\": \"...\", \"item\": {\"id\": \"product-id\", \"name\": \"Product Name\", \"price\": 1200}}\nUse when adding from context without scrolling (optional; on goods page prefer scroll_then_add).\n\n### 4. scroll_then_add (preferred on /bakery-goods.html)\n{\"action\": \"scroll_then_add\", \"text\": \"...\", \"item\": {\"id\": \"...\", \"name\": \"...\", \"price\": 1200}}\nScrolls the product into view then adds one unit (cart merges duplicate ids into quantity).\n\n### 5. checkout → Stripe (this demo)\n{\"action\": \"checkout\", \"text\": \"Brief message\", \"items\": [{\"name\": \"...\", \"price\": 1200, \"quantity\": 2}, ...]}\n**Only** this action starts hosted checkout (Stripe). **Never** use nav_then_click to a \"/checkout\" URL for payment here.\nRequirements: cart in context must have items; **items array must list every cart line** with the same name, cent prices, and quantities as cart.items. If cart is null or empty, use message — do not checkout.\n\n### 6. message_and_click (rare)\nIf page_elements show a specific button selector and scroll_then_add is wrong, you may use message_and_click with a CSS selector — prefer scroll_then_add on bakery-goods.html.\n\n## Rules\n\n- Prices in JSON are always **integer cents** (1200 = $12.00).\n- After adding to cart, invite checkout or more shopping.\n- On checkout confirmation (\"yes\", \"checkout\", \"pay\", \"proceed\", etc.), build **items** from **cart.items** (all rows, correct quantity). Do not drop lines or invent prices.\n\n## Product catalog (ids and cent prices)\n\n- Sourdough Loaf: sourdough-loaf, 1200\n- Croissant Box (6): croissant-box, 2400\n- Cinnamon Rolls (4): cinnamon-rolls, 1800\n- Baguette Trio: baguette-trio, 900\n- Almond Tart: almond-tart, 800\n- Fruit Danish: fruit-danish, 600\n- $50 Gift Card: gift-card-50, 5000\n- $25 Gift Card: gift-card-25, 2500\n\n## Examples\n\nGift seeker on /bakery-locations.html:\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"Here are our goods! You'll find our gift cards below — $50 is our most popular. Want me to add one?\"}\n\nOn /bakery-goods.html, user wants $50 gift card:\n{\"action\": \"scroll_then_add\", \"text\": \"Added the $50 gift card. Ready to check out?\", \"item\": {\"id\": \"gift-card-50\", \"name\": \"$50 Gift Card\", \"price\": 5000}}\n\nUser on /bakery.html agrees to see products:\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"Here are our handcrafted goods — what sounds good today?\"}\n\nOn /bakery-goods.html, add sourdough:\n{\"action\": \"scroll_then_add\", \"text\": \"Sourdough is in your cart. Anything else, or shall we check out?\", \"item\": {\"id\": \"sourdough-loaf\", \"name\": \"Sourdough Loaf\", \"price\": 1200}}\n\nCart has one $50 gift card; user says yes to checkout:\n{\"action\": \"checkout\", \"text\": \"Opening secure checkout...\", \"items\": [{\"name\": \"$50 Gift Card\", \"price\": 5000, \"quantity\": 1}]}\n\nCart has sourdough (qty 1) and croissant box (qty 1); user says \"pay\":\n{\"action\": \"checkout\", \"text\": \"Taking you to checkout...\", \"items\": [{\"name\": \"Sourdough Loaf\", \"price\": 1200, \"quantity\": 1}, {\"name\": \"Croissant Box (6)\", \"price\": 2400, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","/**\n * Stripe checkout helpers using the REST API\n * This approach works on all platforms including Cloudflare Workers, Vercel Edge, etc.\n */\n\nexport interface CheckoutItem {\n name: string;\n price: number; // Price in cents\n quantity: number;\n}\n\nexport interface CreateCheckoutSessionOptions {\n secretKey: string;\n items: CheckoutItem[];\n successUrl: string;\n cancelUrl: string;\n}\n\nexport interface CheckoutSessionResponse {\n success: boolean;\n checkoutUrl?: string;\n sessionId?: string;\n error?: string;\n}\n\n/**\n * Creates a Stripe checkout session using the REST API\n * @param options - Checkout session configuration\n * @returns Checkout session response with URL and session ID\n */\nexport async function createCheckoutSession(\n options: CreateCheckoutSessionOptions\n): Promise<CheckoutSessionResponse> {\n const { secretKey, items, successUrl, cancelUrl } = options;\n\n try {\n // Validate items\n if (!items || !Array.isArray(items) || items.length === 0) {\n return {\n success: false,\n error: \"Items array is required\"\n };\n }\n\n for (const item of items) {\n if (!item.name || typeof item.price !== \"number\" || typeof item.quantity !== \"number\") {\n return {\n success: false,\n error: \"Each item must have name (string), price (number in cents), and quantity (number)\"\n };\n }\n }\n\n // Build line items for URL encoding\n const lineItems = items.map((item) => ({\n price_data: {\n currency: \"usd\",\n product_data: {\n name: item.name,\n },\n unit_amount: item.price,\n },\n quantity: item.quantity,\n }));\n\n // Convert line items to URL-encoded format\n const params = new URLSearchParams({\n \"payment_method_types[0]\": \"card\",\n \"mode\": \"payment\",\n \"success_url\": successUrl,\n \"cancel_url\": cancelUrl,\n });\n\n // Add line items to params\n lineItems.forEach((item, index) => {\n params.append(`line_items[${index}][price_data][currency]`, item.price_data.currency);\n params.append(`line_items[${index}][price_data][product_data][name]`, item.price_data.product_data.name);\n params.append(`line_items[${index}][price_data][unit_amount]`, item.price_data.unit_amount.toString());\n params.append(`line_items[${index}][quantity]`, item.quantity.toString());\n });\n\n // Create Stripe checkout session using REST API\n const stripeResponse = await fetch(\"https://api.stripe.com/v1/checkout/sessions\", {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${secretKey}`,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body: params,\n });\n\n if (!stripeResponse.ok) {\n const errorData = await stripeResponse.text();\n console.error(\"Stripe API error:\", errorData);\n return {\n success: false,\n error: \"Failed to create checkout session\"\n };\n }\n\n const session = await stripeResponse.json() as { url: string; id: string };\n\n return {\n success: true,\n checkoutUrl: session.url,\n sessionId: session.id,\n };\n } catch (error) {\n console.error(\"Stripe checkout error:\", error);\n return {\n success: false,\n error: error instanceof Error ? error.message : \"Failed to create checkout session\"\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAqB;AAErB,oBAAuB;;;ACIhB,IAAM,sBAAyC;AAAA,EACpD,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO;AAAA,IACL;AAAA,MACE,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM;AAAA,MACN,SAAS;AAAA,MACT,QAAQ;AAAA,QACN,OAAO;AAAA,QACP,gBAAgB;AAAA,QAChB,gBAAgB;AAAA,QAChB,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,kBAAkB;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF;;;ACnBO,IAAM,sBAAyC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AAS;AAAA,QACP,eAAe,UAAU,MAAM;AAAA,QAC/B,gBAAgB;AAAA,MAClB;AAAA,MACA,MAAM,KAAK,UAAU,cAAc;AAAA,IACrC,CAAC;AAED,QAAI,eAAe;AACjB,cAAQ,IAAI,oBAAoB,SAAS,MAAM;AAC/C,cAAQ,IAAI,yBAAyB,SAAS,UAAU;AAGxD,UAAI,CAAC,SAAS,IAAI;AAChB,cAAM,iBAAiB,SAAS,MAAM;AACtC,YAAI;AACF,gBAAM,YAAY,MAAM,eAAe,KAAK;AAC5C,kBAAQ,IAAI,wBAAwB,SAAS;AAAA,QAC/C,SAAS,GAAG;AACV,kBAAQ,IAAI,uCAAuC,CAAC;AAAA,QACtD;AAAA,MACF;AACA,cAAQ,IAAI,qCAAqC;AAAA,IACnD;AAEA,WAAO,IAAI,SAAS,SAAS,MAAM;AAAA,MACjC,QAAQ,SAAS;AAAA,MACjB,SAAS;AAAA,QACP,iBACE,cAAS,QAAQ,IAAI,cAAc,MAAnC,YAAwC;AAAA,QAC1C,iBAAiB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;AAEO,IAAM,sBAAsB,CAAC,gBAClC,sBAAO,mBAAmB,OAAO,CAAC;AAQpC,IAAO,gBAAQ;","names":["_a","_b","_c"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/flows/conversational.ts","../src/flows/scheduling.ts","../src/flows/shopping-assistant.ts","../src/flows/components.ts","../src/flows/bakery-assistant.ts","../src/utils/stripe.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport { handle } from \"hono/vercel\";\n\nexport type RuntypeFlowStep = {\n id: string;\n name: string;\n type: string;\n enabled: boolean;\n config: Record<string, unknown>;\n};\n\nexport type RuntypeFlowConfig = {\n name: string;\n description: string;\n steps: RuntypeFlowStep[];\n};\n\ntype RuntimeEnv = Record<string, string | undefined>;\n\n/**\n * Payload for message feedback (upvote/downvote)\n */\nexport type FeedbackPayload = {\n type: \"upvote\" | \"downvote\";\n messageId: string;\n content?: string;\n timestamp?: string;\n sessionId?: string;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Handler function for processing feedback\n */\nexport type FeedbackHandler = (feedback: FeedbackPayload) => Promise<void> | void;\n\nexport type ChatProxyOptions = {\n upstreamUrl?: string;\n apiKey?: string;\n path?: string;\n allowedOrigins?: string[];\n flowId?: string;\n flowConfig?: RuntypeFlowConfig;\n /**\n * Path for the feedback endpoint (default: \"/api/feedback\")\n */\n feedbackPath?: string;\n /**\n * Custom handler for processing feedback.\n * Use this to store feedback in a database or send to analytics.\n * \n * @example\n * ```ts\n * onFeedback: async (feedback) => {\n * await db.feedback.create({ data: feedback });\n * }\n * ```\n */\n onFeedback?: FeedbackHandler;\n};\n\nconst DEFAULT_ENDPOINT = \"https://api.runtype.com/v1/dispatch\";\nconst DEFAULT_PATH = \"/api/chat/dispatch\";\n\nconst getRuntimeEnv = (): RuntimeEnv | undefined => {\n const maybeProcess = (\n globalThis as typeof globalThis & { process?: { env?: RuntimeEnv } }\n ).process;\n return maybeProcess?.env;\n};\n\n/** True only when `NODE_ENV` is exactly `\"development\"` (unset = production). Safe when `process` is missing (e.g. some Workers runtimes). */\nconst isDevelopmentRuntime = (): boolean =>\n getRuntimeEnv()?.NODE_ENV === \"development\";\n\nconst DEFAULT_FLOW: RuntypeFlowConfig = {\n name: \"Streaming Prompt Flow\",\n description: \"Streaming chat generated by the widget\",\n steps: [\n {\n id: \"widget_prompt\",\n name: \"Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n responseFormat: \"markdown\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: \"you are a helpful assistant, chatting with a user\",\n // tools: {\n // toolIds: [\n // \"builtin:dalle\"\n // ]\n // },\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n\nconst withCors =\n (allowedOrigins: string[] | undefined) =>\n async (c: Context, next: () => Promise<void>) => {\n const origin = c.req.header(\"origin\");\n const isDevelopment = isDevelopmentRuntime();\n \n // Determine the CORS origin to allow\n let corsOrigin: string;\n if (!allowedOrigins || allowedOrigins.length === 0) {\n // No restrictions - allow any origin (or use the request origin)\n corsOrigin = origin || \"*\";\n } else if (allowedOrigins.includes(origin || \"\")) {\n // Origin is in the allowed list\n corsOrigin = origin || \"*\";\n } else if (isDevelopment && origin) {\n // In development, allow the actual origin even if not in the list\n // This helps with local development where ports might vary\n corsOrigin = origin;\n } else {\n // Production: origin not allowed - reject by not setting CORS headers\n // Return error for preflight, or continue without CORS headers\n if (c.req.method === \"OPTIONS\") {\n return c.json({ error: \"CORS policy violation: origin not allowed\" }, 403);\n }\n // For non-preflight requests, continue but browser will block due to missing CORS headers\n await next();\n return;\n }\n\n const headers: Record<string, string> = {\n \"Access-Control-Allow-Origin\": corsOrigin,\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n Vary: \"Origin\"\n };\n\n if (c.req.method === \"OPTIONS\") {\n return new Response(null, { status: 204, headers });\n }\n\n await next();\n Object.entries(headers).forEach(([key, value]) =>\n c.header(key, value, { append: false })\n );\n };\n\nexport const createChatProxyApp = (options: ChatProxyOptions = {}) => {\n const app = new Hono();\n const path = options.path ?? DEFAULT_PATH;\n const feedbackPath = options.feedbackPath ?? \"/api/feedback\";\n const upstream = options.upstreamUrl ?? DEFAULT_ENDPOINT;\n\n app.use(\"*\", withCors(options.allowedOrigins));\n\n // Feedback endpoint for collecting upvote/downvote data\n app.post(feedbackPath, async (c) => {\n let payload: FeedbackPayload;\n try {\n payload = await c.req.json();\n } catch (error) {\n return c.json({ error: \"Invalid JSON body\" }, 400);\n }\n\n // Validate payload\n if (!payload.type || ![\"upvote\", \"downvote\"].includes(payload.type)) {\n return c.json(\n { error: \"Invalid feedback type. Must be 'upvote' or 'downvote'\" },\n 400\n );\n }\n if (!payload.messageId) {\n return c.json({ error: \"Missing messageId\" }, 400);\n }\n\n // Add timestamp if not provided\n payload.timestamp = payload.timestamp ?? new Date().toISOString();\n\n const isDevelopment = isDevelopmentRuntime();\n\n if (isDevelopment) {\n console.log(\"\\n=== Feedback Received ===\");\n console.log(\"Type:\", payload.type);\n console.log(\"Message ID:\", payload.messageId);\n console.log(\"Content Length:\", payload.content?.length ?? 0);\n console.log(\"Timestamp:\", payload.timestamp);\n console.log(\"=== End Feedback ===\\n\");\n }\n\n // Call custom handler if provided\n if (options.onFeedback) {\n try {\n await options.onFeedback(payload);\n } catch (error) {\n console.error(\"[Feedback] Handler error:\", error);\n return c.json({ error: \"Feedback handler failed\" }, 500);\n }\n }\n\n return c.json({\n success: true,\n message: \"Feedback recorded\",\n feedback: {\n type: payload.type,\n messageId: payload.messageId,\n timestamp: payload.timestamp\n }\n });\n });\n\n // Chat dispatch endpoint\n app.post(path, async (c) => {\n const apiKey = options.apiKey ?? getRuntimeEnv()?.RUNTYPE_API_KEY;\n if (!apiKey) {\n return c.json(\n { error: \"Missing API key. Set RUNTYPE_API_KEY.\" },\n 401\n );\n }\n\n let clientPayload: Record<string, unknown>;\n try {\n clientPayload = await c.req.json();\n } catch (error) {\n return c.json(\n { error: \"Invalid JSON body\", details: error },\n 400\n );\n }\n\n const isDevelopment = isDevelopmentRuntime();\n\n // Detect agent mode: if the payload contains an `agent` field, forward it directly\n const isAgentMode = !!clientPayload.agent;\n\n let runtypePayload: Record<string, unknown>;\n\n if (isAgentMode) {\n // Agent dispatch - forward the payload as-is to the upstream API\n runtypePayload = clientPayload;\n } else {\n // Flow dispatch - build the Runtype flow payload\n const messages = (clientPayload.messages ?? []) as Array<{ role: string; content: string; createdAt?: string }>;\n const sortedMessages = [...messages].sort((a, b) => {\n const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;\n const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;\n return timeA - timeB;\n });\n const formattedMessages = sortedMessages.map((message) => ({\n role: message.role,\n content: message.content\n }));\n\n const flowId = (clientPayload.flowId as string | undefined) ?? options.flowId;\n const flowConfig = options.flowConfig ?? DEFAULT_FLOW;\n\n runtypePayload = {\n record: {\n name: \"Streaming Chat Widget\",\n type: \"standalone\",\n metadata: (clientPayload.metadata as Record<string, unknown>) || {}\n },\n messages: formattedMessages,\n options: {\n streamResponse: true,\n recordMode: \"virtual\",\n flowMode: flowId ? \"existing\" : \"virtual\",\n autoAppendMetadata: false\n }\n };\n\n const clientInputs = clientPayload.inputs;\n if (clientInputs && typeof clientInputs === \"object\" && !Array.isArray(clientInputs)) {\n runtypePayload.inputs = clientInputs;\n }\n\n if (flowId) {\n runtypePayload.flow = { id: flowId };\n } else {\n runtypePayload.flow = flowConfig;\n }\n }\n\n // Development only: do not log key material or full bodies in production.\n if (isDevelopment) {\n console.log(`\\n=== Runtype Proxy Request (${isAgentMode ? \"agent\" : \"flow\"}) ===`);\n console.log(\"URL:\", upstream);\n console.log(\"API Key Used:\", apiKey ? \"Yes\" : \"No\");\n console.log(\"API Key (first 12 chars):\", apiKey ? apiKey.substring(0, 12) : \"N/A\");\n console.log(\"Request Payload:\", JSON.stringify(runtypePayload, null, 2));\n }\n\n const response = await fetch(upstream, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(runtypePayload)\n });\n\n if (isDevelopment) {\n console.log(\"Response Status:\", response.status);\n console.log(\"Response Status Text:\", response.statusText);\n\n // If there's an error, try to read and log the response body\n if (!response.ok) {\n const clonedResponse = response.clone();\n try {\n const errorBody = await clonedResponse.text();\n console.log(\"Error Response Body:\", errorBody);\n } catch (e) {\n console.log(\"Could not read error response body:\", e);\n }\n }\n console.log(\"=== End Runtype Proxy Request ===\\n\");\n }\n\n return new Response(response.body, {\n status: response.status,\n headers: {\n \"Content-Type\":\n response.headers.get(\"content-type\") ?? \"application/json\",\n \"Cache-Control\": \"no-store\"\n }\n });\n });\n\n return app;\n};\n\nexport const createVercelHandler = (options?: ChatProxyOptions) =>\n handle(createChatProxyApp(options));\n\n// Export pre-configured flows\nexport * from \"./flows/index.js\";\n\n// Export utility functions\nexport * from \"./utils/index.js\";\n\nexport default createChatProxyApp;\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Basic conversational assistant flow\n * This is the default flow for simple chat interactions\n */\nexport const CONVERSATIONAL_FLOW: RuntypeFlowConfig = {\n name: \"Streaming Prompt Flow\",\n description: \"Streaming chat generated by the widget\",\n steps: [\n {\n id: \"widget_prompt\",\n name: \"Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n responseFormat: \"markdown\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: \"you are a helpful assistant, chatting with a user\",\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Dynamic Form flow configuration\n * This flow returns forms as component directives for the widget to render\n */\nexport const FORM_DIRECTIVE_FLOW: RuntypeFlowConfig = {\n name: \"Dynamic Form Flow\",\n description: \"Returns dynamic forms as component directives\",\n steps: [\n {\n id: \"form_prompt\",\n name: \"Form Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful assistant that can have conversations and collect user information via forms.\n\nRESPONSE FORMAT:\nAlways respond with valid JSON. Choose the appropriate format:\n\n1. For CONVERSATIONAL responses or text answers:\n {\"text\": \"Your response here\"}\n\n2. When the user wants to SCHEDULE, BOOK, SIGN UP, or provide DETAILS (show a form):\n {\"component\": \"DynamicForm\", \"props\": {\"title\": \"Form Title\", \"description\": \"Optional description\", \"fields\": [...], \"submit_text\": \"Submit\"}}\n\n3. For BOTH explanation AND form:\n {\"text\": \"Your explanation\", \"component\": \"DynamicForm\", \"props\": {...}}\n\nFORM FIELD FORMAT:\nEach field in the \"fields\" array should have:\n- label (required): Display name for the field\n- name (optional): Field identifier (defaults to lowercase label with underscores)\n- type (optional): \"text\", \"email\", \"tel\", \"date\", \"time\", \"textarea\", \"number\" (defaults to \"text\")\n- placeholder (optional): Placeholder text\n- required (optional): true/false\n\nEXAMPLES:\n\nUser: \"Schedule a demo for me\"\nResponse: {\"text\": \"I'd be happy to help you schedule a demo! Please fill out the form below:\", \"component\": \"DynamicForm\", \"props\": {\"title\": \"Schedule a Demo\", \"description\": \"Share your details and we'll follow up with a confirmation.\", \"fields\": [{\"label\": \"Full Name\", \"type\": \"text\", \"required\": true}, {\"label\": \"Email\", \"type\": \"email\", \"required\": true}, {\"label\": \"Company\", \"type\": \"text\"}, {\"label\": \"Preferred Date\", \"type\": \"date\", \"required\": true}, {\"label\": \"Notes\", \"type\": \"textarea\", \"placeholder\": \"Any specific topics you'd like to cover?\"}], \"submit_text\": \"Request Demo\"}}\n\nUser: \"What is AI?\"\nResponse: {\"text\": \"AI (Artificial Intelligence) refers to computer systems designed to perform tasks that typically require human intelligence, such as learning, reasoning, problem-solving, and understanding language.\"}\n\nUser: \"Collect my contact details\"\nResponse: {\"component\": \"DynamicForm\", \"props\": {\"title\": \"Contact Details\", \"fields\": [{\"label\": \"Name\", \"type\": \"text\", \"required\": true}, {\"label\": \"Email\", \"type\": \"email\", \"required\": true}, {\"label\": \"Phone\", \"type\": \"tel\"}], \"submit_text\": \"Save Details\"}}\n\nIMPORTANT:\n- Use {\"text\": \"...\"} for questions, explanations, and general conversation\n- Show a DynamicForm when user wants to provide information, schedule, book, or sign up\n- Create contextually appropriate form fields based on what the user is trying to do\n- Keep forms focused with only the relevant fields needed`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Shopping assistant flow configuration\n * This flow returns JSON actions for page interaction including:\n * - Simple messages\n * - Navigation with messages\n * - Element clicks with messages\n * - Stripe checkout\n */\nexport const SHOPPING_ASSISTANT_FLOW: RuntypeFlowConfig = {\n name: \"Shopping Assistant Flow\",\n description: \"Returns JSON actions for page interaction\",\n steps: [\n {\n id: \"action_prompt\",\n name: \"Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant that can interact with web pages.\nYou will receive information about the current page's elements (class names and text content)\nand user messages. You must respond with JSON in one of these formats:\n\n1. Simple message:\n{\n \"action\": \"message\",\n \"text\": \"Your response text here\"\n}\n\n2. Navigate then show message (for navigation to another page):\n{\n \"action\": \"nav_then_click\",\n \"page\": \"http://site.com/page-url\",\n \"on_load_text\": \"Message to show after navigation\"\n}\n\n3. Show message and click an element:\n{\n \"action\": \"message_and_click\",\n \"element\": \".className-of-element\",\n \"text\": \"Your message text\"\n}\n\n4. Create Stripe checkout:\n{\n \"action\": \"checkout\",\n \"text\": \"Your message text\",\n \"items\": [\n {\"name\": \"Product Name\", \"price\": 2999, \"quantity\": 1}\n ]\n}\n\nGuidelines:\n- Use \"message\" for simple conversational responses\n- Use \"nav_then_click\" when you need to navigate to a different page (like a product detail page)\n- Use \"message_and_click\" when you want to click a button or element on the current page\n- Use \"checkout\" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)\n- When selecting elements, use the class names provided in the page context\n- Always respond with valid JSON only, no additional text\n- For product searches, format results as markdown links: [Product Name](url)\n- Be helpful and conversational in your messages\n- Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)\n\nExample conversation flow:\n- User: \"I am looking for a black shirt in medium\"\n- You: {\"action\": \"message\", \"text\": \"Here are the products I found:\\\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\\\n\\\\nWould you like me to navigate to the first result and add it to your cart?\"}\n\n- User: \"No, I would like to add another shirt to the cart\"\n- You: {\"action\": \"message_and_click\", \"element\": \".AddToCartButton-blue-shirt-large\", \"text\": \"I've added the Blue Shirt - Large to your cart. Ready to checkout?\"}\n\n- User: \"yes\"\n- You: {\"action\": \"checkout\", \"text\": \"Perfect! I'll set up the checkout for you.\", \"items\": [{\"name\": \"Black Shirt - Medium\", \"price\": 2999, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n\n/**\n * Metadata-based shopping assistant flow configuration\n * This flow uses DOM context from record metadata instead of user message.\n * The metadata should include dom_elements, dom_body, page_url, and page_title.\n */\nexport const SHOPPING_ASSISTANT_METADATA_FLOW: RuntypeFlowConfig = {\n name: \"Metadata-Based Shopping Assistant\",\n description: \"Uses DOM context from record metadata for page interaction\",\n steps: [\n {\n id: \"metadata_action_prompt\",\n name: \"Metadata Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant that can interact with web pages.\n\nIMPORTANT: You have access to the current page's DOM elements through the record metadata, which includes:\n- dom_elements: Array of page elements with className, innerText, and tagName\n- dom_body: Complete HTML body of the page (if provided)\n- page_url: Current page URL\n- page_title: Page title\n\nThe dom_elements array provides information about clickable elements and their text content.\nUse this metadata to understand what's available on the page and help users interact with it.\n\nYou must respond with JSON in one of these formats:\n\n1. Simple message:\n{\n \"action\": \"message\",\n \"text\": \"Your response text here\"\n}\n\n2. Navigate then show message (for navigation to another page):\n{\n \"action\": \"nav_then_click\",\n \"page\": \"http://site.com/page-url\",\n \"on_load_text\": \"Message to show after navigation\"\n}\n\n3. Show message and click an element:\n{\n \"action\": \"message_and_click\",\n \"element\": \".className-of-element\",\n \"text\": \"Your message text\"\n}\n\n4. Create Stripe checkout:\n{\n \"action\": \"checkout\",\n \"text\": \"Your message text\",\n \"items\": [\n {\"name\": \"Product Name\", \"price\": 2999, \"quantity\": 1}\n ]\n}\n\nGuidelines:\n- Use \"message\" for simple conversational responses\n- Use \"nav_then_click\" when you need to navigate to a different page (like a product detail page)\n- Use \"message_and_click\" when you want to click a button or element on the current page\n- Use \"checkout\" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)\n- When selecting elements, use the class names from the dom_elements in the metadata\n- Always respond with valid JSON only, no additional text\n- For product searches, format results as markdown links: [Product Name](url)\n- Be helpful and conversational in your messages\n- Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)\n\nExample conversation flow:\n- User: \"I am looking for a black shirt in medium\"\n- You: {\"action\": \"message\", \"text\": \"Here are the products I found:\\\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\\\n\\\\nWould you like me to navigate to the first result and add it to your cart?\"}\n\n- User: \"No, I would like to add another shirt to the cart\"\n- You: {\"action\": \"message_and_click\", \"element\": \".AddToCartButton-blue-shirt-large\", \"text\": \"I've added the Blue Shirt - Large to your cart. Ready to checkout?\"}\n\n- User: \"yes\"\n- You: {\"action\": \"checkout\", \"text\": \"Perfect! I'll set up the checkout for you.\", \"items\": [{\"name\": \"Black Shirt - Medium\", \"price\": 2999, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Component-aware flow for custom component rendering\n * This flow instructs the AI to respond with component directives in JSON format\n */\nexport const COMPONENT_FLOW: RuntypeFlowConfig = {\n name: \"Component Flow\",\n description: \"Flow configured for custom component rendering\",\n steps: [\n {\n id: \"component_prompt\",\n name: \"Component Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful assistant that can both have conversations and render custom UI components.\n\nRESPONSE FORMAT:\nAlways respond with valid JSON. Choose the appropriate format based on the user's request:\n\n1. For CONVERSATIONAL questions or text responses:\n {\"text\": \"Your response here\"}\n\n2. For VISUAL DISPLAYS or when the user asks to SHOW/DISPLAY something:\n {\"component\": \"ComponentName\", \"props\": {...}}\n\n3. For BOTH explanation AND visual:\n {\"text\": \"Your explanation here\", \"component\": \"ComponentName\", \"props\": {...}}\n\nAvailable components for visual displays:\n- ProductCard: Display product information. Props: title (string), price (number), description (string, optional), image (string, optional)\n- SimpleChart: Display a bar chart. Props: title (string), data (array of numbers), labels (array of strings, optional)\n- StatusBadge: Display a status badge. Props: status (string: \"success\", \"error\", \"warning\", \"info\", \"pending\"), message (string)\n- InfoCard: Display an information card. Props: title (string), content (string), icon (string, optional)\n\nExamples:\n- User asks \"What is the capital of France?\": {\"text\": \"The capital of France is Paris.\"}\n- User asks \"What does that chart show?\": {\"text\": \"The chart shows sales data increasing from 100 to 200 over three months.\"}\n- User asks \"Show me a product card\": {\"component\": \"ProductCard\", \"props\": {\"title\": \"Laptop\", \"price\": 999, \"description\": \"A great laptop\"}}\n- User asks \"Display a chart\": {\"component\": \"SimpleChart\", \"props\": {\"title\": \"Sales\", \"data\": [100, 150, 200], \"labels\": [\"Jan\", \"Feb\", \"Mar\"]}}\n- User asks \"Show me a chart and explain it\": {\"text\": \"Here's the sales data for Q1:\", \"component\": \"SimpleChart\", \"props\": {\"title\": \"Q1 Sales\", \"data\": [100, 150, 200], \"labels\": [\"Jan\", \"Feb\", \"Mar\"]}}\n\nIMPORTANT:\n- Use {\"text\": \"...\"} for questions, explanations, discussions, and general chat\n- Use {\"component\": \"...\", \"props\": {...}} ONLY when the user explicitly wants to SEE/VIEW/DISPLAY visual content\n- You can combine both: {\"text\": \"...\", \"component\": \"...\", \"props\": {...}} when you want to explain something AND show a visual\n- Never force a component when the user just wants information`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Bakery assistant flow configuration for \"Flour & Stone\" bakery demo\n * This flow returns JSON actions for page interaction including:\n * - Simple messages with bakery brand voice\n * - Navigation to bakery pages\n * - Add to cart interactions\n * - Stripe checkout\n *\n * Designed to guide users toward the gift card when asking for gift recommendations.\n */\nexport const BAKERY_ASSISTANT_FLOW: RuntypeFlowConfig = {\n name: \"Bakery Assistant Flow\",\n description: \"Flour & Stone bakery shopping assistant with gift recommendations\",\n steps: [\n {\n id: \"bakery_action_prompt\",\n name: \"Bakery Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant for Flour & Stone, a premium artisan bakery known for traditional bread-making and exceptional pastries.\n\nBrand voice: Warm, knowledgeable, passionate about craft baking. Use phrases like \"fresh from the oven\", \"handcrafted with care\", \"artisan tradition\". Do not explain selectors, JSON, or templating to the user.\n\n## Live context (request inputs — substituted each turn)\n\nThe widget sends **only** these keys as dispatch **inputs** (nothing extra on the record for this demo).\n\n**Orientation**\n- Path: {{current_page}} (compare before nav_then_click; e.g. /bakery-goods.html)\n- Full URL: {{page_url}}\n- Title: {{page_title}}\n\n**Page DOM**\n- page_elements: JSON array of enriched nodes (selector, tagName, text, role, interactivity, attributes including data-*). Prefer **selector** for message_and_click when you click a specific control.\n- page_context: Same slice formatted for the LLM (structured card summaries when matched, then groups by interactivity).\n\n{{page_elements}}\n\n{{page_context}}\n\n**Cart (for checkout — mirror cart.items when user pays)**\n{{cart}}\n\n**Recent order (if any)**\n{{recent_order}}\n\nIf {{current_page}} already equals the page you would navigate to, use {\"action\":\"message\",...} instead of nav_then_click.\n\n## Discovering products\n\nUse {{page_context}} for a quick scan and {{page_elements}} for exact selectors and attributes. Product rows often include data-product in **attributes**; prices appear in **text**; add-to-cart controls are usually **clickable** with stable **selector** values.\n\n## Output: one JSON object only\n\nNo markdown fences, no commentary before/after. Valid JSON only.\n\n### 1. message\n{\"action\": \"message\", \"text\": \"...\"}\nUse for chat, clarifying questions, \"we're already on that page\", or when you need the user to choose (e.g. $25 vs $50 gift card).\n\n### 2. nav_then_click\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"...\"}\nUse root-relative paths starting with /. Only when current_page is different from the target. This **only** changes pages — it does **not** open Stripe or payment.\n\n### 3. add_to_cart\n{\"action\": \"add_to_cart\", \"text\": \"...\", \"item\": {\"id\": \"product-id\", \"name\": \"Product Name\", \"price\": 1200}}\nUse when adding from context without scrolling (optional; on goods page prefer scroll_then_add).\n\n### 4. scroll_then_add (preferred on /bakery-goods.html)\n{\"action\": \"scroll_then_add\", \"text\": \"...\", \"item\": {\"id\": \"...\", \"name\": \"...\", \"price\": 1200}}\nScrolls the product into view then adds one unit (cart merges duplicate ids into quantity).\n\n### 5. checkout → Stripe (this demo)\n{\"action\": \"checkout\", \"text\": \"Brief message\", \"items\": [{\"name\": \"...\", \"price\": 1200, \"quantity\": 2}, ...]}\n**Only** this action starts hosted checkout (Stripe). **Never** use nav_then_click to a \"/checkout\" URL for payment here.\nRequirements: cart in context must have items; **items array must list every cart line** with the same name, cent prices, and quantities as cart.items. If cart is null or empty, use message — do not checkout.\n\n### 6. message_and_click (rare)\nIf page_elements show a specific button selector and scroll_then_add is wrong, you may use message_and_click with a CSS selector — prefer scroll_then_add on bakery-goods.html.\n\n## Rules\n\n- Prices in JSON are always **integer cents** (1200 = $12.00).\n- After adding to cart, invite checkout or more shopping.\n- On checkout confirmation (\"yes\", \"checkout\", \"pay\", \"proceed\", etc.), build **items** from **cart.items** (all rows, correct quantity). Do not drop lines or invent prices.\n\n## Product catalog (ids and cent prices)\n\n- Sourdough Loaf: sourdough-loaf, 1200\n- Croissant Box (6): croissant-box, 2400\n- Cinnamon Rolls (4): cinnamon-rolls, 1800\n- Baguette Trio: baguette-trio, 900\n- Almond Tart: almond-tart, 800\n- Fruit Danish: fruit-danish, 600\n- $50 Gift Card: gift-card-50, 5000\n- $25 Gift Card: gift-card-25, 2500\n\n## Examples\n\nGift seeker on /bakery-locations.html:\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"Here are our goods! You'll find our gift cards below — $50 is our most popular. Want me to add one?\"}\n\nOn /bakery-goods.html, user wants $50 gift card:\n{\"action\": \"scroll_then_add\", \"text\": \"Added the $50 gift card. Ready to check out?\", \"item\": {\"id\": \"gift-card-50\", \"name\": \"$50 Gift Card\", \"price\": 5000}}\n\nUser on /bakery.html agrees to see products:\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"Here are our handcrafted goods — what sounds good today?\"}\n\nOn /bakery-goods.html, add sourdough:\n{\"action\": \"scroll_then_add\", \"text\": \"Sourdough is in your cart. Anything else, or shall we check out?\", \"item\": {\"id\": \"sourdough-loaf\", \"name\": \"Sourdough Loaf\", \"price\": 1200}}\n\nCart has one $50 gift card; user says yes to checkout:\n{\"action\": \"checkout\", \"text\": \"Opening secure checkout...\", \"items\": [{\"name\": \"$50 Gift Card\", \"price\": 5000, \"quantity\": 1}]}\n\nCart has sourdough (qty 1) and croissant box (qty 1); user says \"pay\":\n{\"action\": \"checkout\", \"text\": \"Taking you to checkout...\", \"items\": [{\"name\": \"Sourdough Loaf\", \"price\": 1200, \"quantity\": 1}, {\"name\": \"Croissant Box (6)\", \"price\": 2400, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","/**\n * Stripe checkout helpers using the REST API\n * This approach works on all platforms including Cloudflare Workers, Vercel Edge, etc.\n */\n\n/**\n * Pinned API version for raw HTTP calls (no SDK). Required for organization API keys and\n * keeps behavior stable across accounts. See https://docs.stripe.com/api/versioning\n */\nconst STRIPE_API_VERSION = \"2026-03-25.dahlia\";\n\nexport interface CheckoutItem {\n name: string;\n price: number; // Price in cents\n quantity: number;\n}\n\nexport interface CreateCheckoutSessionOptions {\n secretKey: string;\n items: CheckoutItem[];\n successUrl: string;\n cancelUrl: string;\n}\n\nexport interface CheckoutSessionResponse {\n success: boolean;\n checkoutUrl?: string;\n sessionId?: string;\n error?: string;\n}\n\nfunction parseStripeApiErrorBody(body: string): string | undefined {\n try {\n const parsed = JSON.parse(body) as {\n error?: { message?: string; type?: string };\n };\n const msg = parsed?.error?.message;\n return typeof msg === \"string\" && msg.length > 0 ? msg : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Creates a Stripe checkout session using the REST API\n * @param options - Checkout session configuration\n * @returns Checkout session response with URL and session ID\n */\nexport async function createCheckoutSession(\n options: CreateCheckoutSessionOptions\n): Promise<CheckoutSessionResponse> {\n const { secretKey, items, successUrl, cancelUrl } = options;\n\n try {\n // Validate items\n if (!items || !Array.isArray(items) || items.length === 0) {\n return {\n success: false,\n error: \"Items array is required\"\n };\n }\n\n for (const item of items) {\n if (!item.name || typeof item.price !== \"number\" || typeof item.quantity !== \"number\") {\n return {\n success: false,\n error: \"Each item must have name (string), price (number in cents), and quantity (number)\"\n };\n }\n if (\n !Number.isFinite(item.price) ||\n !Number.isInteger(item.price) ||\n item.price < 1 ||\n !Number.isInteger(item.quantity) ||\n item.quantity < 1\n ) {\n return {\n success: false,\n error:\n \"Each item needs a positive integer price (cents) and quantity (Stripe rejects decimals or zero)\",\n };\n }\n }\n\n // Build line items for URL encoding\n const lineItems = items.map((item) => ({\n price_data: {\n currency: \"usd\",\n product_data: {\n name: item.name,\n },\n unit_amount: item.price,\n },\n quantity: item.quantity,\n }));\n\n // Convert line items to URL-encoded format\n const params = new URLSearchParams({\n \"payment_method_types[0]\": \"card\",\n \"mode\": \"payment\",\n \"success_url\": successUrl,\n \"cancel_url\": cancelUrl,\n });\n\n // Add line items to params\n lineItems.forEach((item, index) => {\n params.append(`line_items[${index}][price_data][currency]`, item.price_data.currency);\n params.append(`line_items[${index}][price_data][product_data][name]`, item.price_data.product_data.name);\n params.append(`line_items[${index}][price_data][unit_amount]`, item.price_data.unit_amount.toString());\n params.append(`line_items[${index}][quantity]`, item.quantity.toString());\n });\n\n // Create Stripe checkout session using REST API\n const stripeResponse = await fetch(\"https://api.stripe.com/v1/checkout/sessions\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${secretKey}`,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Stripe-Version\": STRIPE_API_VERSION,\n },\n body: params,\n });\n\n if (!stripeResponse.ok) {\n const errorData = await stripeResponse.text();\n const stripeMessage = parseStripeApiErrorBody(errorData);\n console.error(\"Stripe API error:\", errorData);\n return {\n success: false,\n error: stripeMessage ?? \"Failed to create checkout session\",\n };\n }\n\n const session = await stripeResponse.json() as { url: string; id: string };\n\n return {\n success: true,\n checkoutUrl: session.url,\n sessionId: session.id,\n };\n } catch (error) {\n console.error(\"Stripe checkout error:\", error);\n return {\n success: false,\n error: error instanceof Error ? error.message : \"Failed to create checkout session\"\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAqB;AAErB,oBAAuB;;;ACIhB,IAAM,sBAAyC;AAAA,EACpD,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO;AAAA,IACL;AAAA,MACE,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM;AAAA,MACN,SAAS;AAAA,MACT,QAAQ;AAAA,QACN,OAAO;AAAA,QACP,gBAAgB;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A,cAAQ,IAAI,qCAAqC;AAAA,IACnD;AAEA,WAAO,IAAI,SAAS,SAAS,MAAM;AAAA,MACjC,QAAQ,SAAS;AAAA,MACjB,SAAS;AAAA,QACP,iBACE,cAAS,QAAQ,IAAI,cAAc,MAAnC,YAAwC;AAAA,QAC1C,iBAAiB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;AAEO,IAAM,sBAAsB,CAAC,gBAClC,sBAAO,mBAAmB,OAAO,CAAC;AAQpC,IAAO,gBAAQ;","names":["_a","_b","_c"]}
package/dist/index.js CHANGED
@@ -415,6 +415,17 @@ Cart has sourdough (qty 1) and croissant box (qty 1); user says "pay":
415
415
  };
416
416
 
417
417
  // src/utils/stripe.ts
418
+ var STRIPE_API_VERSION = "2026-03-25.dahlia";
419
+ function parseStripeApiErrorBody(body) {
420
+ var _a;
421
+ try {
422
+ const parsed = JSON.parse(body);
423
+ const msg = (_a = parsed == null ? void 0 : parsed.error) == null ? void 0 : _a.message;
424
+ return typeof msg === "string" && msg.length > 0 ? msg : void 0;
425
+ } catch {
426
+ return void 0;
427
+ }
428
+ }
418
429
  async function createCheckoutSession(options) {
419
430
  const { secretKey, items, successUrl, cancelUrl } = options;
420
431
  try {
@@ -431,6 +442,12 @@ async function createCheckoutSession(options) {
431
442
  error: "Each item must have name (string), price (number in cents), and quantity (number)"
432
443
  };
433
444
  }
445
+ if (!Number.isFinite(item.price) || !Number.isInteger(item.price) || item.price < 1 || !Number.isInteger(item.quantity) || item.quantity < 1) {
446
+ return {
447
+ success: false,
448
+ error: "Each item needs a positive integer price (cents) and quantity (Stripe rejects decimals or zero)"
449
+ };
450
+ }
434
451
  }
435
452
  const lineItems = items.map((item) => ({
436
453
  price_data: {
@@ -457,17 +474,19 @@ async function createCheckoutSession(options) {
457
474
  const stripeResponse = await fetch("https://api.stripe.com/v1/checkout/sessions", {
458
475
  method: "POST",
459
476
  headers: {
460
- "Authorization": `Bearer ${secretKey}`,
461
- "Content-Type": "application/x-www-form-urlencoded"
477
+ Authorization: `Bearer ${secretKey}`,
478
+ "Content-Type": "application/x-www-form-urlencoded",
479
+ "Stripe-Version": STRIPE_API_VERSION
462
480
  },
463
481
  body: params
464
482
  });
465
483
  if (!stripeResponse.ok) {
466
484
  const errorData = await stripeResponse.text();
485
+ const stripeMessage = parseStripeApiErrorBody(errorData);
467
486
  console.error("Stripe API error:", errorData);
468
487
  return {
469
488
  success: false,
470
- error: "Failed to create checkout session"
489
+ error: stripeMessage != null ? stripeMessage : "Failed to create checkout session"
471
490
  };
472
491
  }
473
492
  const session = await stripeResponse.json();
@@ -488,6 +507,14 @@ async function createCheckoutSession(options) {
488
507
  // src/index.ts
489
508
  var DEFAULT_ENDPOINT = "https://api.runtype.com/v1/dispatch";
490
509
  var DEFAULT_PATH = "/api/chat/dispatch";
510
+ var getRuntimeEnv = () => {
511
+ const maybeProcess = globalThis.process;
512
+ return maybeProcess == null ? void 0 : maybeProcess.env;
513
+ };
514
+ var isDevelopmentRuntime = () => {
515
+ var _a;
516
+ return ((_a = getRuntimeEnv()) == null ? void 0 : _a.NODE_ENV) === "development";
517
+ };
491
518
  var DEFAULT_FLOW = {
492
519
  name: "Streaming Prompt Flow",
493
520
  description: "Streaming chat generated by the widget",
@@ -515,7 +542,7 @@ var DEFAULT_FLOW = {
515
542
  };
516
543
  var withCors = (allowedOrigins) => async (c, next) => {
517
544
  const origin = c.req.header("origin");
518
- const isDevelopment = process.env.NODE_ENV === "development";
545
+ const isDevelopment = isDevelopmentRuntime();
519
546
  let corsOrigin;
520
547
  if (!allowedOrigins || allowedOrigins.length === 0) {
521
548
  corsOrigin = origin || "*";
@@ -569,15 +596,12 @@ var createChatProxyApp = (options = {}) => {
569
596
  return c.json({ error: "Missing messageId" }, 400);
570
597
  }
571
598
  payload.timestamp = (_a2 = payload.timestamp) != null ? _a2 : (/* @__PURE__ */ new Date()).toISOString();
572
- const isDevelopment = process.env.NODE_ENV === "development";
599
+ const isDevelopment = isDevelopmentRuntime();
573
600
  if (isDevelopment) {
574
601
  console.log("\n=== Feedback Received ===");
575
602
  console.log("Type:", payload.type);
576
603
  console.log("Message ID:", payload.messageId);
577
- console.log(
578
- "Content Preview:",
579
- (_c2 = (_b2 = payload.content) == null ? void 0 : _b2.substring(0, 100)) != null ? _c2 : "(none)"
580
- );
604
+ console.log("Content Length:", (_c2 = (_b2 = payload.content) == null ? void 0 : _b2.length) != null ? _c2 : 0);
581
605
  console.log("Timestamp:", payload.timestamp);
582
606
  console.log("=== End Feedback ===\n");
583
607
  }
@@ -600,8 +624,8 @@ var createChatProxyApp = (options = {}) => {
600
624
  });
601
625
  });
602
626
  app.post(path, async (c) => {
603
- var _a2, _b2, _c2, _d, _e;
604
- const apiKey = (_a2 = options.apiKey) != null ? _a2 : process.env.RUNTYPE_API_KEY;
627
+ var _a2, _b2, _c2, _d, _e, _f;
628
+ const apiKey = (_b2 = options.apiKey) != null ? _b2 : (_a2 = getRuntimeEnv()) == null ? void 0 : _a2.RUNTYPE_API_KEY;
605
629
  if (!apiKey) {
606
630
  return c.json(
607
631
  { error: "Missing API key. Set RUNTYPE_API_KEY." },
@@ -617,13 +641,13 @@ var createChatProxyApp = (options = {}) => {
617
641
  400
618
642
  );
619
643
  }
620
- const isDevelopment = process.env.NODE_ENV === "development";
644
+ const isDevelopment = isDevelopmentRuntime();
621
645
  const isAgentMode = !!clientPayload.agent;
622
646
  let runtypePayload;
623
647
  if (isAgentMode) {
624
648
  runtypePayload = clientPayload;
625
649
  } else {
626
- const messages = (_b2 = clientPayload.messages) != null ? _b2 : [];
650
+ const messages = (_c2 = clientPayload.messages) != null ? _c2 : [];
627
651
  const sortedMessages = [...messages].sort((a, b) => {
628
652
  const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
629
653
  const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
@@ -633,8 +657,8 @@ var createChatProxyApp = (options = {}) => {
633
657
  role: message.role,
634
658
  content: message.content
635
659
  }));
636
- const flowId = (_c2 = clientPayload.flowId) != null ? _c2 : options.flowId;
637
- const flowConfig = (_d = options.flowConfig) != null ? _d : DEFAULT_FLOW;
660
+ const flowId = (_d = clientPayload.flowId) != null ? _d : options.flowId;
661
+ const flowConfig = (_e = options.flowConfig) != null ? _e : DEFAULT_FLOW;
638
662
  runtypePayload = {
639
663
  record: {
640
664
  name: "Streaming Chat Widget",
@@ -692,7 +716,7 @@ var createChatProxyApp = (options = {}) => {
692
716
  return new Response(response.body, {
693
717
  status: response.status,
694
718
  headers: {
695
- "Content-Type": (_e = response.headers.get("content-type")) != null ? _e : "application/json",
719
+ "Content-Type": (_f = response.headers.get("content-type")) != null ? _f : "application/json",
696
720
  "Cache-Control": "no-store"
697
721
  }
698
722
  });
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/flows/conversational.ts","../src/flows/scheduling.ts","../src/flows/shopping-assistant.ts","../src/flows/components.ts","../src/flows/bakery-assistant.ts","../src/utils/stripe.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport { handle } from \"hono/vercel\";\n\nexport type RuntypeFlowStep = {\n id: string;\n name: string;\n type: string;\n enabled: boolean;\n config: Record<string, unknown>;\n};\n\nexport type RuntypeFlowConfig = {\n name: string;\n description: string;\n steps: RuntypeFlowStep[];\n};\n\n\n\n/**\n * Payload for message feedback (upvote/downvote)\n */\nexport type FeedbackPayload = {\n type: \"upvote\" | \"downvote\";\n messageId: string;\n content?: string;\n timestamp?: string;\n sessionId?: string;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Handler function for processing feedback\n */\nexport type FeedbackHandler = (feedback: FeedbackPayload) => Promise<void> | void;\n\nexport type ChatProxyOptions = {\n upstreamUrl?: string;\n apiKey?: string;\n path?: string;\n allowedOrigins?: string[];\n flowId?: string;\n flowConfig?: RuntypeFlowConfig;\n /**\n * Path for the feedback endpoint (default: \"/api/feedback\")\n */\n feedbackPath?: string;\n /**\n * Custom handler for processing feedback.\n * Use this to store feedback in a database or send to analytics.\n * \n * @example\n * ```ts\n * onFeedback: async (feedback) => {\n * await db.feedback.create({ data: feedback });\n * }\n * ```\n */\n onFeedback?: FeedbackHandler;\n};\n\nconst DEFAULT_ENDPOINT = \"https://api.runtype.com/v1/dispatch\";\nconst DEFAULT_PATH = \"/api/chat/dispatch\";\n\nconst DEFAULT_FLOW: RuntypeFlowConfig = {\n name: \"Streaming Prompt Flow\",\n description: \"Streaming chat generated by the widget\",\n steps: [\n {\n id: \"widget_prompt\",\n name: \"Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n responseFormat: \"markdown\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: \"you are a helpful assistant, chatting with a user\",\n // tools: {\n // toolIds: [\n // \"builtin:dalle\"\n // ]\n // },\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n\nconst withCors =\n (allowedOrigins: string[] | undefined) =>\n async (c: Context, next: () => Promise<void>) => {\n const origin = c.req.header(\"origin\");\n const isDevelopment = process.env.NODE_ENV === \"development\";\n \n // Determine the CORS origin to allow\n let corsOrigin: string;\n if (!allowedOrigins || allowedOrigins.length === 0) {\n // No restrictions - allow any origin (or use the request origin)\n corsOrigin = origin || \"*\";\n } else if (allowedOrigins.includes(origin || \"\")) {\n // Origin is in the allowed list\n corsOrigin = origin || \"*\";\n } else if (isDevelopment && origin) {\n // In development, allow the actual origin even if not in the list\n // This helps with local development where ports might vary\n corsOrigin = origin;\n } else {\n // Production: origin not allowed - reject by not setting CORS headers\n // Return error for preflight, or continue without CORS headers\n if (c.req.method === \"OPTIONS\") {\n return c.json({ error: \"CORS policy violation: origin not allowed\" }, 403);\n }\n // For non-preflight requests, continue but browser will block due to missing CORS headers\n await next();\n return;\n }\n\n const headers: Record<string, string> = {\n \"Access-Control-Allow-Origin\": corsOrigin,\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n Vary: \"Origin\"\n };\n\n if (c.req.method === \"OPTIONS\") {\n return new Response(null, { status: 204, headers });\n }\n\n await next();\n Object.entries(headers).forEach(([key, value]) =>\n c.header(key, value, { append: false })\n );\n };\n\nexport const createChatProxyApp = (options: ChatProxyOptions = {}) => {\n const app = new Hono();\n const path = options.path ?? DEFAULT_PATH;\n const feedbackPath = options.feedbackPath ?? \"/api/feedback\";\n const upstream = options.upstreamUrl ?? DEFAULT_ENDPOINT;\n\n app.use(\"*\", withCors(options.allowedOrigins));\n\n // Feedback endpoint for collecting upvote/downvote data\n app.post(feedbackPath, async (c) => {\n let payload: FeedbackPayload;\n try {\n payload = await c.req.json();\n } catch (error) {\n return c.json({ error: \"Invalid JSON body\" }, 400);\n }\n\n // Validate payload\n if (!payload.type || ![\"upvote\", \"downvote\"].includes(payload.type)) {\n return c.json(\n { error: \"Invalid feedback type. Must be 'upvote' or 'downvote'\" },\n 400\n );\n }\n if (!payload.messageId) {\n return c.json({ error: \"Missing messageId\" }, 400);\n }\n\n // Add timestamp if not provided\n payload.timestamp = payload.timestamp ?? new Date().toISOString();\n\n const isDevelopment =\n process.env.NODE_ENV === \"development\";\n\n if (isDevelopment) {\n console.log(\"\\n=== Feedback Received ===\");\n console.log(\"Type:\", payload.type);\n console.log(\"Message ID:\", payload.messageId);\n console.log(\n \"Content Preview:\",\n payload.content?.substring(0, 100) ?? \"(none)\"\n );\n console.log(\"Timestamp:\", payload.timestamp);\n console.log(\"=== End Feedback ===\\n\");\n }\n\n // Call custom handler if provided\n if (options.onFeedback) {\n try {\n await options.onFeedback(payload);\n } catch (error) {\n console.error(\"[Feedback] Handler error:\", error);\n return c.json({ error: \"Feedback handler failed\" }, 500);\n }\n }\n\n return c.json({\n success: true,\n message: \"Feedback recorded\",\n feedback: {\n type: payload.type,\n messageId: payload.messageId,\n timestamp: payload.timestamp\n }\n });\n });\n\n // Chat dispatch endpoint\n app.post(path, async (c) => {\n const apiKey = options.apiKey ?? process.env.RUNTYPE_API_KEY;\n if (!apiKey) {\n return c.json(\n { error: \"Missing API key. Set RUNTYPE_API_KEY.\" },\n 401\n );\n }\n\n let clientPayload: Record<string, unknown>;\n try {\n clientPayload = await c.req.json();\n } catch (error) {\n return c.json(\n { error: \"Invalid JSON body\", details: error },\n 400\n );\n }\n\n const isDevelopment = process.env.NODE_ENV === \"development\";\n\n // Detect agent mode: if the payload contains an `agent` field, forward it directly\n const isAgentMode = !!clientPayload.agent;\n\n let runtypePayload: Record<string, unknown>;\n\n if (isAgentMode) {\n // Agent dispatch - forward the payload as-is to the upstream API\n runtypePayload = clientPayload;\n } else {\n // Flow dispatch - build the Runtype flow payload\n const messages = (clientPayload.messages ?? []) as Array<{ role: string; content: string; createdAt?: string }>;\n const sortedMessages = [...messages].sort((a, b) => {\n const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;\n const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;\n return timeA - timeB;\n });\n const formattedMessages = sortedMessages.map((message) => ({\n role: message.role,\n content: message.content\n }));\n\n const flowId = (clientPayload.flowId as string | undefined) ?? options.flowId;\n const flowConfig = options.flowConfig ?? DEFAULT_FLOW;\n\n runtypePayload = {\n record: {\n name: \"Streaming Chat Widget\",\n type: \"standalone\",\n metadata: (clientPayload.metadata as Record<string, unknown>) || {}\n },\n messages: formattedMessages,\n options: {\n streamResponse: true,\n recordMode: \"virtual\",\n flowMode: flowId ? \"existing\" : \"virtual\",\n autoAppendMetadata: false\n }\n };\n\n const clientInputs = clientPayload.inputs;\n if (clientInputs && typeof clientInputs === \"object\" && !Array.isArray(clientInputs)) {\n runtypePayload.inputs = clientInputs;\n }\n\n if (flowId) {\n runtypePayload.flow = { id: flowId };\n } else {\n runtypePayload.flow = flowConfig;\n }\n }\n\n if (isDevelopment) {\n console.log(`\\n=== Runtype Proxy Request (${isAgentMode ? \"agent\" : \"flow\"}) ===`);\n console.log(\"URL:\", upstream);\n console.log(\"API Key Used:\", apiKey ? \"Yes\" : \"No\");\n console.log(\"API Key (first 12 chars):\", apiKey ? apiKey.substring(0, 12) : \"N/A\");\n console.log(\"Request Payload:\", JSON.stringify(runtypePayload, null, 2));\n }\n\n const response = await fetch(upstream, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(runtypePayload)\n });\n\n if (isDevelopment) {\n console.log(\"Response Status:\", response.status);\n console.log(\"Response Status Text:\", response.statusText);\n\n // If there's an error, try to read and log the response body\n if (!response.ok) {\n const clonedResponse = response.clone();\n try {\n const errorBody = await clonedResponse.text();\n console.log(\"Error Response Body:\", errorBody);\n } catch (e) {\n console.log(\"Could not read error response body:\", e);\n }\n }\n console.log(\"=== End Runtype Proxy Request ===\\n\");\n }\n\n return new Response(response.body, {\n status: response.status,\n headers: {\n \"Content-Type\":\n response.headers.get(\"content-type\") ?? \"application/json\",\n \"Cache-Control\": \"no-store\"\n }\n });\n });\n\n return app;\n};\n\nexport const createVercelHandler = (options?: ChatProxyOptions) =>\n handle(createChatProxyApp(options));\n\n// Export pre-configured flows\nexport * from \"./flows/index.js\";\n\n// Export utility functions\nexport * from \"./utils/index.js\";\n\nexport default createChatProxyApp;\n\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Basic conversational assistant flow\n * This is the default flow for simple chat interactions\n */\nexport const CONVERSATIONAL_FLOW: RuntypeFlowConfig = {\n name: \"Streaming Prompt Flow\",\n description: \"Streaming chat generated by the widget\",\n steps: [\n {\n id: \"widget_prompt\",\n name: \"Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n responseFormat: \"markdown\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: \"you are a helpful assistant, chatting with a user\",\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Dynamic Form flow configuration\n * This flow returns forms as component directives for the widget to render\n */\nexport const FORM_DIRECTIVE_FLOW: RuntypeFlowConfig = {\n name: \"Dynamic Form Flow\",\n description: \"Returns dynamic forms as component directives\",\n steps: [\n {\n id: \"form_prompt\",\n name: \"Form Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful assistant that can have conversations and collect user information via forms.\n\nRESPONSE FORMAT:\nAlways respond with valid JSON. Choose the appropriate format:\n\n1. For CONVERSATIONAL responses or text answers:\n {\"text\": \"Your response here\"}\n\n2. When the user wants to SCHEDULE, BOOK, SIGN UP, or provide DETAILS (show a form):\n {\"component\": \"DynamicForm\", \"props\": {\"title\": \"Form Title\", \"description\": \"Optional description\", \"fields\": [...], \"submit_text\": \"Submit\"}}\n\n3. For BOTH explanation AND form:\n {\"text\": \"Your explanation\", \"component\": \"DynamicForm\", \"props\": {...}}\n\nFORM FIELD FORMAT:\nEach field in the \"fields\" array should have:\n- label (required): Display name for the field\n- name (optional): Field identifier (defaults to lowercase label with underscores)\n- type (optional): \"text\", \"email\", \"tel\", \"date\", \"time\", \"textarea\", \"number\" (defaults to \"text\")\n- placeholder (optional): Placeholder text\n- required (optional): true/false\n\nEXAMPLES:\n\nUser: \"Schedule a demo for me\"\nResponse: {\"text\": \"I'd be happy to help you schedule a demo! Please fill out the form below:\", \"component\": \"DynamicForm\", \"props\": {\"title\": \"Schedule a Demo\", \"description\": \"Share your details and we'll follow up with a confirmation.\", \"fields\": [{\"label\": \"Full Name\", \"type\": \"text\", \"required\": true}, {\"label\": \"Email\", \"type\": \"email\", \"required\": true}, {\"label\": \"Company\", \"type\": \"text\"}, {\"label\": \"Preferred Date\", \"type\": \"date\", \"required\": true}, {\"label\": \"Notes\", \"type\": \"textarea\", \"placeholder\": \"Any specific topics you'd like to cover?\"}], \"submit_text\": \"Request Demo\"}}\n\nUser: \"What is AI?\"\nResponse: {\"text\": \"AI (Artificial Intelligence) refers to computer systems designed to perform tasks that typically require human intelligence, such as learning, reasoning, problem-solving, and understanding language.\"}\n\nUser: \"Collect my contact details\"\nResponse: {\"component\": \"DynamicForm\", \"props\": {\"title\": \"Contact Details\", \"fields\": [{\"label\": \"Name\", \"type\": \"text\", \"required\": true}, {\"label\": \"Email\", \"type\": \"email\", \"required\": true}, {\"label\": \"Phone\", \"type\": \"tel\"}], \"submit_text\": \"Save Details\"}}\n\nIMPORTANT:\n- Use {\"text\": \"...\"} for questions, explanations, and general conversation\n- Show a DynamicForm when user wants to provide information, schedule, book, or sign up\n- Create contextually appropriate form fields based on what the user is trying to do\n- Keep forms focused with only the relevant fields needed`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Shopping assistant flow configuration\n * This flow returns JSON actions for page interaction including:\n * - Simple messages\n * - Navigation with messages\n * - Element clicks with messages\n * - Stripe checkout\n */\nexport const SHOPPING_ASSISTANT_FLOW: RuntypeFlowConfig = {\n name: \"Shopping Assistant Flow\",\n description: \"Returns JSON actions for page interaction\",\n steps: [\n {\n id: \"action_prompt\",\n name: \"Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant that can interact with web pages.\nYou will receive information about the current page's elements (class names and text content)\nand user messages. You must respond with JSON in one of these formats:\n\n1. Simple message:\n{\n \"action\": \"message\",\n \"text\": \"Your response text here\"\n}\n\n2. Navigate then show message (for navigation to another page):\n{\n \"action\": \"nav_then_click\",\n \"page\": \"http://site.com/page-url\",\n \"on_load_text\": \"Message to show after navigation\"\n}\n\n3. Show message and click an element:\n{\n \"action\": \"message_and_click\",\n \"element\": \".className-of-element\",\n \"text\": \"Your message text\"\n}\n\n4. Create Stripe checkout:\n{\n \"action\": \"checkout\",\n \"text\": \"Your message text\",\n \"items\": [\n {\"name\": \"Product Name\", \"price\": 2999, \"quantity\": 1}\n ]\n}\n\nGuidelines:\n- Use \"message\" for simple conversational responses\n- Use \"nav_then_click\" when you need to navigate to a different page (like a product detail page)\n- Use \"message_and_click\" when you want to click a button or element on the current page\n- Use \"checkout\" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)\n- When selecting elements, use the class names provided in the page context\n- Always respond with valid JSON only, no additional text\n- For product searches, format results as markdown links: [Product Name](url)\n- Be helpful and conversational in your messages\n- Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)\n\nExample conversation flow:\n- User: \"I am looking for a black shirt in medium\"\n- You: {\"action\": \"message\", \"text\": \"Here are the products I found:\\\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\\\n\\\\nWould you like me to navigate to the first result and add it to your cart?\"}\n\n- User: \"No, I would like to add another shirt to the cart\"\n- You: {\"action\": \"message_and_click\", \"element\": \".AddToCartButton-blue-shirt-large\", \"text\": \"I've added the Blue Shirt - Large to your cart. Ready to checkout?\"}\n\n- User: \"yes\"\n- You: {\"action\": \"checkout\", \"text\": \"Perfect! I'll set up the checkout for you.\", \"items\": [{\"name\": \"Black Shirt - Medium\", \"price\": 2999, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n\n/**\n * Metadata-based shopping assistant flow configuration\n * This flow uses DOM context from record metadata instead of user message.\n * The metadata should include dom_elements, dom_body, page_url, and page_title.\n */\nexport const SHOPPING_ASSISTANT_METADATA_FLOW: RuntypeFlowConfig = {\n name: \"Metadata-Based Shopping Assistant\",\n description: \"Uses DOM context from record metadata for page interaction\",\n steps: [\n {\n id: \"metadata_action_prompt\",\n name: \"Metadata Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant that can interact with web pages.\n\nIMPORTANT: You have access to the current page's DOM elements through the record metadata, which includes:\n- dom_elements: Array of page elements with className, innerText, and tagName\n- dom_body: Complete HTML body of the page (if provided)\n- page_url: Current page URL\n- page_title: Page title\n\nThe dom_elements array provides information about clickable elements and their text content.\nUse this metadata to understand what's available on the page and help users interact with it.\n\nYou must respond with JSON in one of these formats:\n\n1. Simple message:\n{\n \"action\": \"message\",\n \"text\": \"Your response text here\"\n}\n\n2. Navigate then show message (for navigation to another page):\n{\n \"action\": \"nav_then_click\",\n \"page\": \"http://site.com/page-url\",\n \"on_load_text\": \"Message to show after navigation\"\n}\n\n3. Show message and click an element:\n{\n \"action\": \"message_and_click\",\n \"element\": \".className-of-element\",\n \"text\": \"Your message text\"\n}\n\n4. Create Stripe checkout:\n{\n \"action\": \"checkout\",\n \"text\": \"Your message text\",\n \"items\": [\n {\"name\": \"Product Name\", \"price\": 2999, \"quantity\": 1}\n ]\n}\n\nGuidelines:\n- Use \"message\" for simple conversational responses\n- Use \"nav_then_click\" when you need to navigate to a different page (like a product detail page)\n- Use \"message_and_click\" when you want to click a button or element on the current page\n- Use \"checkout\" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)\n- When selecting elements, use the class names from the dom_elements in the metadata\n- Always respond with valid JSON only, no additional text\n- For product searches, format results as markdown links: [Product Name](url)\n- Be helpful and conversational in your messages\n- Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)\n\nExample conversation flow:\n- User: \"I am looking for a black shirt in medium\"\n- You: {\"action\": \"message\", \"text\": \"Here are the products I found:\\\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\\\n\\\\nWould you like me to navigate to the first result and add it to your cart?\"}\n\n- User: \"No, I would like to add another shirt to the cart\"\n- You: {\"action\": \"message_and_click\", \"element\": \".AddToCartButton-blue-shirt-large\", \"text\": \"I've added the Blue Shirt - Large to your cart. Ready to checkout?\"}\n\n- User: \"yes\"\n- You: {\"action\": \"checkout\", \"text\": \"Perfect! I'll set up the checkout for you.\", \"items\": [{\"name\": \"Black Shirt - Medium\", \"price\": 2999, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Component-aware flow for custom component rendering\n * This flow instructs the AI to respond with component directives in JSON format\n */\nexport const COMPONENT_FLOW: RuntypeFlowConfig = {\n name: \"Component Flow\",\n description: \"Flow configured for custom component rendering\",\n steps: [\n {\n id: \"component_prompt\",\n name: \"Component Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful assistant that can both have conversations and render custom UI components.\n\nRESPONSE FORMAT:\nAlways respond with valid JSON. Choose the appropriate format based on the user's request:\n\n1. For CONVERSATIONAL questions or text responses:\n {\"text\": \"Your response here\"}\n\n2. For VISUAL DISPLAYS or when the user asks to SHOW/DISPLAY something:\n {\"component\": \"ComponentName\", \"props\": {...}}\n\n3. For BOTH explanation AND visual:\n {\"text\": \"Your explanation here\", \"component\": \"ComponentName\", \"props\": {...}}\n\nAvailable components for visual displays:\n- ProductCard: Display product information. Props: title (string), price (number), description (string, optional), image (string, optional)\n- SimpleChart: Display a bar chart. Props: title (string), data (array of numbers), labels (array of strings, optional)\n- StatusBadge: Display a status badge. Props: status (string: \"success\", \"error\", \"warning\", \"info\", \"pending\"), message (string)\n- InfoCard: Display an information card. Props: title (string), content (string), icon (string, optional)\n\nExamples:\n- User asks \"What is the capital of France?\": {\"text\": \"The capital of France is Paris.\"}\n- User asks \"What does that chart show?\": {\"text\": \"The chart shows sales data increasing from 100 to 200 over three months.\"}\n- User asks \"Show me a product card\": {\"component\": \"ProductCard\", \"props\": {\"title\": \"Laptop\", \"price\": 999, \"description\": \"A great laptop\"}}\n- User asks \"Display a chart\": {\"component\": \"SimpleChart\", \"props\": {\"title\": \"Sales\", \"data\": [100, 150, 200], \"labels\": [\"Jan\", \"Feb\", \"Mar\"]}}\n- User asks \"Show me a chart and explain it\": {\"text\": \"Here's the sales data for Q1:\", \"component\": \"SimpleChart\", \"props\": {\"title\": \"Q1 Sales\", \"data\": [100, 150, 200], \"labels\": [\"Jan\", \"Feb\", \"Mar\"]}}\n\nIMPORTANT:\n- Use {\"text\": \"...\"} for questions, explanations, discussions, and general chat\n- Use {\"component\": \"...\", \"props\": {...}} ONLY when the user explicitly wants to SEE/VIEW/DISPLAY visual content\n- You can combine both: {\"text\": \"...\", \"component\": \"...\", \"props\": {...}} when you want to explain something AND show a visual\n- Never force a component when the user just wants information`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Bakery assistant flow configuration for \"Flour & Stone\" bakery demo\n * This flow returns JSON actions for page interaction including:\n * - Simple messages with bakery brand voice\n * - Navigation to bakery pages\n * - Add to cart interactions\n * - Stripe checkout\n *\n * Designed to guide users toward the gift card when asking for gift recommendations.\n */\nexport const BAKERY_ASSISTANT_FLOW: RuntypeFlowConfig = {\n name: \"Bakery Assistant Flow\",\n description: \"Flour & Stone bakery shopping assistant with gift recommendations\",\n steps: [\n {\n id: \"bakery_action_prompt\",\n name: \"Bakery Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant for Flour & Stone, a premium artisan bakery known for traditional bread-making and exceptional pastries.\n\nBrand voice: Warm, knowledgeable, passionate about craft baking. Use phrases like \"fresh from the oven\", \"handcrafted with care\", \"artisan tradition\". Do not explain selectors, JSON, or templating to the user.\n\n## Live context (request inputs — substituted each turn)\n\nThe widget sends **only** these keys as dispatch **inputs** (nothing extra on the record for this demo).\n\n**Orientation**\n- Path: {{current_page}} (compare before nav_then_click; e.g. /bakery-goods.html)\n- Full URL: {{page_url}}\n- Title: {{page_title}}\n\n**Page DOM**\n- page_elements: JSON array of enriched nodes (selector, tagName, text, role, interactivity, attributes including data-*). Prefer **selector** for message_and_click when you click a specific control.\n- page_context: Same slice formatted for the LLM (structured card summaries when matched, then groups by interactivity).\n\n{{page_elements}}\n\n{{page_context}}\n\n**Cart (for checkout — mirror cart.items when user pays)**\n{{cart}}\n\n**Recent order (if any)**\n{{recent_order}}\n\nIf {{current_page}} already equals the page you would navigate to, use {\"action\":\"message\",...} instead of nav_then_click.\n\n## Discovering products\n\nUse {{page_context}} for a quick scan and {{page_elements}} for exact selectors and attributes. Product rows often include data-product in **attributes**; prices appear in **text**; add-to-cart controls are usually **clickable** with stable **selector** values.\n\n## Output: one JSON object only\n\nNo markdown fences, no commentary before/after. Valid JSON only.\n\n### 1. message\n{\"action\": \"message\", \"text\": \"...\"}\nUse for chat, clarifying questions, \"we're already on that page\", or when you need the user to choose (e.g. $25 vs $50 gift card).\n\n### 2. nav_then_click\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"...\"}\nUse root-relative paths starting with /. Only when current_page is different from the target. This **only** changes pages — it does **not** open Stripe or payment.\n\n### 3. add_to_cart\n{\"action\": \"add_to_cart\", \"text\": \"...\", \"item\": {\"id\": \"product-id\", \"name\": \"Product Name\", \"price\": 1200}}\nUse when adding from context without scrolling (optional; on goods page prefer scroll_then_add).\n\n### 4. scroll_then_add (preferred on /bakery-goods.html)\n{\"action\": \"scroll_then_add\", \"text\": \"...\", \"item\": {\"id\": \"...\", \"name\": \"...\", \"price\": 1200}}\nScrolls the product into view then adds one unit (cart merges duplicate ids into quantity).\n\n### 5. checkout → Stripe (this demo)\n{\"action\": \"checkout\", \"text\": \"Brief message\", \"items\": [{\"name\": \"...\", \"price\": 1200, \"quantity\": 2}, ...]}\n**Only** this action starts hosted checkout (Stripe). **Never** use nav_then_click to a \"/checkout\" URL for payment here.\nRequirements: cart in context must have items; **items array must list every cart line** with the same name, cent prices, and quantities as cart.items. If cart is null or empty, use message — do not checkout.\n\n### 6. message_and_click (rare)\nIf page_elements show a specific button selector and scroll_then_add is wrong, you may use message_and_click with a CSS selector — prefer scroll_then_add on bakery-goods.html.\n\n## Rules\n\n- Prices in JSON are always **integer cents** (1200 = $12.00).\n- After adding to cart, invite checkout or more shopping.\n- On checkout confirmation (\"yes\", \"checkout\", \"pay\", \"proceed\", etc.), build **items** from **cart.items** (all rows, correct quantity). Do not drop lines or invent prices.\n\n## Product catalog (ids and cent prices)\n\n- Sourdough Loaf: sourdough-loaf, 1200\n- Croissant Box (6): croissant-box, 2400\n- Cinnamon Rolls (4): cinnamon-rolls, 1800\n- Baguette Trio: baguette-trio, 900\n- Almond Tart: almond-tart, 800\n- Fruit Danish: fruit-danish, 600\n- $50 Gift Card: gift-card-50, 5000\n- $25 Gift Card: gift-card-25, 2500\n\n## Examples\n\nGift seeker on /bakery-locations.html:\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"Here are our goods! You'll find our gift cards below — $50 is our most popular. Want me to add one?\"}\n\nOn /bakery-goods.html, user wants $50 gift card:\n{\"action\": \"scroll_then_add\", \"text\": \"Added the $50 gift card. Ready to check out?\", \"item\": {\"id\": \"gift-card-50\", \"name\": \"$50 Gift Card\", \"price\": 5000}}\n\nUser on /bakery.html agrees to see products:\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"Here are our handcrafted goods — what sounds good today?\"}\n\nOn /bakery-goods.html, add sourdough:\n{\"action\": \"scroll_then_add\", \"text\": \"Sourdough is in your cart. Anything else, or shall we check out?\", \"item\": {\"id\": \"sourdough-loaf\", \"name\": \"Sourdough Loaf\", \"price\": 1200}}\n\nCart has one $50 gift card; user says yes to checkout:\n{\"action\": \"checkout\", \"text\": \"Opening secure checkout...\", \"items\": [{\"name\": \"$50 Gift Card\", \"price\": 5000, \"quantity\": 1}]}\n\nCart has sourdough (qty 1) and croissant box (qty 1); user says \"pay\":\n{\"action\": \"checkout\", \"text\": \"Taking you to checkout...\", \"items\": [{\"name\": \"Sourdough Loaf\", \"price\": 1200, \"quantity\": 1}, {\"name\": \"Croissant Box (6)\", \"price\": 2400, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","/**\n * Stripe checkout helpers using the REST API\n * This approach works on all platforms including Cloudflare Workers, Vercel Edge, etc.\n */\n\nexport interface CheckoutItem {\n name: string;\n price: number; // Price in cents\n quantity: number;\n}\n\nexport interface CreateCheckoutSessionOptions {\n secretKey: string;\n items: CheckoutItem[];\n successUrl: string;\n cancelUrl: string;\n}\n\nexport interface CheckoutSessionResponse {\n success: boolean;\n checkoutUrl?: string;\n sessionId?: string;\n error?: string;\n}\n\n/**\n * Creates a Stripe checkout session using the REST API\n * @param options - Checkout session configuration\n * @returns Checkout session response with URL and session ID\n */\nexport async function createCheckoutSession(\n options: CreateCheckoutSessionOptions\n): Promise<CheckoutSessionResponse> {\n const { secretKey, items, successUrl, cancelUrl } = options;\n\n try {\n // Validate items\n if (!items || !Array.isArray(items) || items.length === 0) {\n return {\n success: false,\n error: \"Items array is required\"\n };\n }\n\n for (const item of items) {\n if (!item.name || typeof item.price !== \"number\" || typeof item.quantity !== \"number\") {\n return {\n success: false,\n error: \"Each item must have name (string), price (number in cents), and quantity (number)\"\n };\n }\n }\n\n // Build line items for URL encoding\n const lineItems = items.map((item) => ({\n price_data: {\n currency: \"usd\",\n product_data: {\n name: item.name,\n },\n unit_amount: item.price,\n },\n quantity: item.quantity,\n }));\n\n // Convert line items to URL-encoded format\n const params = new URLSearchParams({\n \"payment_method_types[0]\": \"card\",\n \"mode\": \"payment\",\n \"success_url\": successUrl,\n \"cancel_url\": cancelUrl,\n });\n\n // Add line items to params\n lineItems.forEach((item, index) => {\n params.append(`line_items[${index}][price_data][currency]`, item.price_data.currency);\n params.append(`line_items[${index}][price_data][product_data][name]`, item.price_data.product_data.name);\n params.append(`line_items[${index}][price_data][unit_amount]`, item.price_data.unit_amount.toString());\n params.append(`line_items[${index}][quantity]`, item.quantity.toString());\n });\n\n // Create Stripe checkout session using REST API\n const stripeResponse = await fetch(\"https://api.stripe.com/v1/checkout/sessions\", {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${secretKey}`,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body: params,\n });\n\n if (!stripeResponse.ok) {\n const errorData = await stripeResponse.text();\n console.error(\"Stripe API error:\", errorData);\n return {\n success: false,\n error: \"Failed to create checkout session\"\n };\n }\n\n const session = await stripeResponse.json() as { url: string; id: string };\n\n return {\n success: true,\n checkoutUrl: session.url,\n sessionId: session.id,\n };\n } catch (error) {\n console.error(\"Stripe checkout error:\", error);\n return {\n success: false,\n error: error instanceof Error ? error.message : \"Failed to create checkout session\"\n };\n }\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAErB,SAAS,cAAc;;;ACIhB,IAAM,sBAAyC;AAAA,EACpD,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO;AAAA,IACL;AAAA,MACE,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM;AAAA,MACN,SAAS;AAAA,MACT,QAAQ;AAAA,QACN,OAAO;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AI,KAAK;AACjF,cAAQ,IAAI,oBAAoB,KAAK,UAAU,gBAAgB,MAAM,CAAC,CAAC;AAAA,IACzE;AAEA,UAAM,WAAW,MAAM,MAAM,UAAU;AAAA,MACrC,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,eAAe,UAAU,MAAM;AAAA,QAC/B,gBAAgB;AAAA,MAClB;AAAA,MACA,MAAM,KAAK,UAAU,cAAc;AAAA,IACrC,CAAC;AAED,QAAI,eAAe;AACjB,cAAQ,IAAI,oBAAoB,SAAS,MAAM;AAC/C,cAAQ,IAAI,yBAAyB,SAAS,UAAU;AAGxD,UAAI,CAAC,SAAS,IAAI;AAChB,cAAM,iBAAiB,SAAS,MAAM;AACtC,YAAI;AACF,gBAAM,YAAY,MAAM,eAAe,KAAK;AAC5C,kBAAQ,IAAI,wBAAwB,SAAS;AAAA,QAC/C,SAAS,GAAG;AACV,kBAAQ,IAAI,uCAAuC,CAAC;AAAA,QACtD;AAAA,MACF;AACA,cAAQ,IAAI,qCAAqC;AAAA,IACnD;AAEA,WAAO,IAAI,SAAS,SAAS,MAAM;AAAA,MACjC,QAAQ,SAAS;AAAA,MACjB,SAAS;AAAA,QACP,iBACE,cAAS,QAAQ,IAAI,cAAc,MAAnC,YAAwC;AAAA,QAC1C,iBAAiB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;AAEO,IAAM,sBAAsB,CAAC,YAClC,OAAO,mBAAmB,OAAO,CAAC;AAQpC,IAAO,gBAAQ;","names":["_a","_b","_c"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/flows/conversational.ts","../src/flows/scheduling.ts","../src/flows/shopping-assistant.ts","../src/flows/components.ts","../src/flows/bakery-assistant.ts","../src/utils/stripe.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport { handle } from \"hono/vercel\";\n\nexport type RuntypeFlowStep = {\n id: string;\n name: string;\n type: string;\n enabled: boolean;\n config: Record<string, unknown>;\n};\n\nexport type RuntypeFlowConfig = {\n name: string;\n description: string;\n steps: RuntypeFlowStep[];\n};\n\ntype RuntimeEnv = Record<string, string | undefined>;\n\n/**\n * Payload for message feedback (upvote/downvote)\n */\nexport type FeedbackPayload = {\n type: \"upvote\" | \"downvote\";\n messageId: string;\n content?: string;\n timestamp?: string;\n sessionId?: string;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Handler function for processing feedback\n */\nexport type FeedbackHandler = (feedback: FeedbackPayload) => Promise<void> | void;\n\nexport type ChatProxyOptions = {\n upstreamUrl?: string;\n apiKey?: string;\n path?: string;\n allowedOrigins?: string[];\n flowId?: string;\n flowConfig?: RuntypeFlowConfig;\n /**\n * Path for the feedback endpoint (default: \"/api/feedback\")\n */\n feedbackPath?: string;\n /**\n * Custom handler for processing feedback.\n * Use this to store feedback in a database or send to analytics.\n * \n * @example\n * ```ts\n * onFeedback: async (feedback) => {\n * await db.feedback.create({ data: feedback });\n * }\n * ```\n */\n onFeedback?: FeedbackHandler;\n};\n\nconst DEFAULT_ENDPOINT = \"https://api.runtype.com/v1/dispatch\";\nconst DEFAULT_PATH = \"/api/chat/dispatch\";\n\nconst getRuntimeEnv = (): RuntimeEnv | undefined => {\n const maybeProcess = (\n globalThis as typeof globalThis & { process?: { env?: RuntimeEnv } }\n ).process;\n return maybeProcess?.env;\n};\n\n/** True only when `NODE_ENV` is exactly `\"development\"` (unset = production). Safe when `process` is missing (e.g. some Workers runtimes). */\nconst isDevelopmentRuntime = (): boolean =>\n getRuntimeEnv()?.NODE_ENV === \"development\";\n\nconst DEFAULT_FLOW: RuntypeFlowConfig = {\n name: \"Streaming Prompt Flow\",\n description: \"Streaming chat generated by the widget\",\n steps: [\n {\n id: \"widget_prompt\",\n name: \"Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n responseFormat: \"markdown\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: \"you are a helpful assistant, chatting with a user\",\n // tools: {\n // toolIds: [\n // \"builtin:dalle\"\n // ]\n // },\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n\nconst withCors =\n (allowedOrigins: string[] | undefined) =>\n async (c: Context, next: () => Promise<void>) => {\n const origin = c.req.header(\"origin\");\n const isDevelopment = isDevelopmentRuntime();\n \n // Determine the CORS origin to allow\n let corsOrigin: string;\n if (!allowedOrigins || allowedOrigins.length === 0) {\n // No restrictions - allow any origin (or use the request origin)\n corsOrigin = origin || \"*\";\n } else if (allowedOrigins.includes(origin || \"\")) {\n // Origin is in the allowed list\n corsOrigin = origin || \"*\";\n } else if (isDevelopment && origin) {\n // In development, allow the actual origin even if not in the list\n // This helps with local development where ports might vary\n corsOrigin = origin;\n } else {\n // Production: origin not allowed - reject by not setting CORS headers\n // Return error for preflight, or continue without CORS headers\n if (c.req.method === \"OPTIONS\") {\n return c.json({ error: \"CORS policy violation: origin not allowed\" }, 403);\n }\n // For non-preflight requests, continue but browser will block due to missing CORS headers\n await next();\n return;\n }\n\n const headers: Record<string, string> = {\n \"Access-Control-Allow-Origin\": corsOrigin,\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n Vary: \"Origin\"\n };\n\n if (c.req.method === \"OPTIONS\") {\n return new Response(null, { status: 204, headers });\n }\n\n await next();\n Object.entries(headers).forEach(([key, value]) =>\n c.header(key, value, { append: false })\n );\n };\n\nexport const createChatProxyApp = (options: ChatProxyOptions = {}) => {\n const app = new Hono();\n const path = options.path ?? DEFAULT_PATH;\n const feedbackPath = options.feedbackPath ?? \"/api/feedback\";\n const upstream = options.upstreamUrl ?? DEFAULT_ENDPOINT;\n\n app.use(\"*\", withCors(options.allowedOrigins));\n\n // Feedback endpoint for collecting upvote/downvote data\n app.post(feedbackPath, async (c) => {\n let payload: FeedbackPayload;\n try {\n payload = await c.req.json();\n } catch (error) {\n return c.json({ error: \"Invalid JSON body\" }, 400);\n }\n\n // Validate payload\n if (!payload.type || ![\"upvote\", \"downvote\"].includes(payload.type)) {\n return c.json(\n { error: \"Invalid feedback type. Must be 'upvote' or 'downvote'\" },\n 400\n );\n }\n if (!payload.messageId) {\n return c.json({ error: \"Missing messageId\" }, 400);\n }\n\n // Add timestamp if not provided\n payload.timestamp = payload.timestamp ?? new Date().toISOString();\n\n const isDevelopment = isDevelopmentRuntime();\n\n if (isDevelopment) {\n console.log(\"\\n=== Feedback Received ===\");\n console.log(\"Type:\", payload.type);\n console.log(\"Message ID:\", payload.messageId);\n console.log(\"Content Length:\", payload.content?.length ?? 0);\n console.log(\"Timestamp:\", payload.timestamp);\n console.log(\"=== End Feedback ===\\n\");\n }\n\n // Call custom handler if provided\n if (options.onFeedback) {\n try {\n await options.onFeedback(payload);\n } catch (error) {\n console.error(\"[Feedback] Handler error:\", error);\n return c.json({ error: \"Feedback handler failed\" }, 500);\n }\n }\n\n return c.json({\n success: true,\n message: \"Feedback recorded\",\n feedback: {\n type: payload.type,\n messageId: payload.messageId,\n timestamp: payload.timestamp\n }\n });\n });\n\n // Chat dispatch endpoint\n app.post(path, async (c) => {\n const apiKey = options.apiKey ?? getRuntimeEnv()?.RUNTYPE_API_KEY;\n if (!apiKey) {\n return c.json(\n { error: \"Missing API key. Set RUNTYPE_API_KEY.\" },\n 401\n );\n }\n\n let clientPayload: Record<string, unknown>;\n try {\n clientPayload = await c.req.json();\n } catch (error) {\n return c.json(\n { error: \"Invalid JSON body\", details: error },\n 400\n );\n }\n\n const isDevelopment = isDevelopmentRuntime();\n\n // Detect agent mode: if the payload contains an `agent` field, forward it directly\n const isAgentMode = !!clientPayload.agent;\n\n let runtypePayload: Record<string, unknown>;\n\n if (isAgentMode) {\n // Agent dispatch - forward the payload as-is to the upstream API\n runtypePayload = clientPayload;\n } else {\n // Flow dispatch - build the Runtype flow payload\n const messages = (clientPayload.messages ?? []) as Array<{ role: string; content: string; createdAt?: string }>;\n const sortedMessages = [...messages].sort((a, b) => {\n const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;\n const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;\n return timeA - timeB;\n });\n const formattedMessages = sortedMessages.map((message) => ({\n role: message.role,\n content: message.content\n }));\n\n const flowId = (clientPayload.flowId as string | undefined) ?? options.flowId;\n const flowConfig = options.flowConfig ?? DEFAULT_FLOW;\n\n runtypePayload = {\n record: {\n name: \"Streaming Chat Widget\",\n type: \"standalone\",\n metadata: (clientPayload.metadata as Record<string, unknown>) || {}\n },\n messages: formattedMessages,\n options: {\n streamResponse: true,\n recordMode: \"virtual\",\n flowMode: flowId ? \"existing\" : \"virtual\",\n autoAppendMetadata: false\n }\n };\n\n const clientInputs = clientPayload.inputs;\n if (clientInputs && typeof clientInputs === \"object\" && !Array.isArray(clientInputs)) {\n runtypePayload.inputs = clientInputs;\n }\n\n if (flowId) {\n runtypePayload.flow = { id: flowId };\n } else {\n runtypePayload.flow = flowConfig;\n }\n }\n\n // Development only: do not log key material or full bodies in production.\n if (isDevelopment) {\n console.log(`\\n=== Runtype Proxy Request (${isAgentMode ? \"agent\" : \"flow\"}) ===`);\n console.log(\"URL:\", upstream);\n console.log(\"API Key Used:\", apiKey ? \"Yes\" : \"No\");\n console.log(\"API Key (first 12 chars):\", apiKey ? apiKey.substring(0, 12) : \"N/A\");\n console.log(\"Request Payload:\", JSON.stringify(runtypePayload, null, 2));\n }\n\n const response = await fetch(upstream, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(runtypePayload)\n });\n\n if (isDevelopment) {\n console.log(\"Response Status:\", response.status);\n console.log(\"Response Status Text:\", response.statusText);\n\n // If there's an error, try to read and log the response body\n if (!response.ok) {\n const clonedResponse = response.clone();\n try {\n const errorBody = await clonedResponse.text();\n console.log(\"Error Response Body:\", errorBody);\n } catch (e) {\n console.log(\"Could not read error response body:\", e);\n }\n }\n console.log(\"=== End Runtype Proxy Request ===\\n\");\n }\n\n return new Response(response.body, {\n status: response.status,\n headers: {\n \"Content-Type\":\n response.headers.get(\"content-type\") ?? \"application/json\",\n \"Cache-Control\": \"no-store\"\n }\n });\n });\n\n return app;\n};\n\nexport const createVercelHandler = (options?: ChatProxyOptions) =>\n handle(createChatProxyApp(options));\n\n// Export pre-configured flows\nexport * from \"./flows/index.js\";\n\n// Export utility functions\nexport * from \"./utils/index.js\";\n\nexport default createChatProxyApp;\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Basic conversational assistant flow\n * This is the default flow for simple chat interactions\n */\nexport const CONVERSATIONAL_FLOW: RuntypeFlowConfig = {\n name: \"Streaming Prompt Flow\",\n description: \"Streaming chat generated by the widget\",\n steps: [\n {\n id: \"widget_prompt\",\n name: \"Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n responseFormat: \"markdown\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: \"you are a helpful assistant, chatting with a user\",\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Dynamic Form flow configuration\n * This flow returns forms as component directives for the widget to render\n */\nexport const FORM_DIRECTIVE_FLOW: RuntypeFlowConfig = {\n name: \"Dynamic Form Flow\",\n description: \"Returns dynamic forms as component directives\",\n steps: [\n {\n id: \"form_prompt\",\n name: \"Form Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful assistant that can have conversations and collect user information via forms.\n\nRESPONSE FORMAT:\nAlways respond with valid JSON. Choose the appropriate format:\n\n1. For CONVERSATIONAL responses or text answers:\n {\"text\": \"Your response here\"}\n\n2. When the user wants to SCHEDULE, BOOK, SIGN UP, or provide DETAILS (show a form):\n {\"component\": \"DynamicForm\", \"props\": {\"title\": \"Form Title\", \"description\": \"Optional description\", \"fields\": [...], \"submit_text\": \"Submit\"}}\n\n3. For BOTH explanation AND form:\n {\"text\": \"Your explanation\", \"component\": \"DynamicForm\", \"props\": {...}}\n\nFORM FIELD FORMAT:\nEach field in the \"fields\" array should have:\n- label (required): Display name for the field\n- name (optional): Field identifier (defaults to lowercase label with underscores)\n- type (optional): \"text\", \"email\", \"tel\", \"date\", \"time\", \"textarea\", \"number\" (defaults to \"text\")\n- placeholder (optional): Placeholder text\n- required (optional): true/false\n\nEXAMPLES:\n\nUser: \"Schedule a demo for me\"\nResponse: {\"text\": \"I'd be happy to help you schedule a demo! Please fill out the form below:\", \"component\": \"DynamicForm\", \"props\": {\"title\": \"Schedule a Demo\", \"description\": \"Share your details and we'll follow up with a confirmation.\", \"fields\": [{\"label\": \"Full Name\", \"type\": \"text\", \"required\": true}, {\"label\": \"Email\", \"type\": \"email\", \"required\": true}, {\"label\": \"Company\", \"type\": \"text\"}, {\"label\": \"Preferred Date\", \"type\": \"date\", \"required\": true}, {\"label\": \"Notes\", \"type\": \"textarea\", \"placeholder\": \"Any specific topics you'd like to cover?\"}], \"submit_text\": \"Request Demo\"}}\n\nUser: \"What is AI?\"\nResponse: {\"text\": \"AI (Artificial Intelligence) refers to computer systems designed to perform tasks that typically require human intelligence, such as learning, reasoning, problem-solving, and understanding language.\"}\n\nUser: \"Collect my contact details\"\nResponse: {\"component\": \"DynamicForm\", \"props\": {\"title\": \"Contact Details\", \"fields\": [{\"label\": \"Name\", \"type\": \"text\", \"required\": true}, {\"label\": \"Email\", \"type\": \"email\", \"required\": true}, {\"label\": \"Phone\", \"type\": \"tel\"}], \"submit_text\": \"Save Details\"}}\n\nIMPORTANT:\n- Use {\"text\": \"...\"} for questions, explanations, and general conversation\n- Show a DynamicForm when user wants to provide information, schedule, book, or sign up\n- Create contextually appropriate form fields based on what the user is trying to do\n- Keep forms focused with only the relevant fields needed`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Shopping assistant flow configuration\n * This flow returns JSON actions for page interaction including:\n * - Simple messages\n * - Navigation with messages\n * - Element clicks with messages\n * - Stripe checkout\n */\nexport const SHOPPING_ASSISTANT_FLOW: RuntypeFlowConfig = {\n name: \"Shopping Assistant Flow\",\n description: \"Returns JSON actions for page interaction\",\n steps: [\n {\n id: \"action_prompt\",\n name: \"Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant that can interact with web pages.\nYou will receive information about the current page's elements (class names and text content)\nand user messages. You must respond with JSON in one of these formats:\n\n1. Simple message:\n{\n \"action\": \"message\",\n \"text\": \"Your response text here\"\n}\n\n2. Navigate then show message (for navigation to another page):\n{\n \"action\": \"nav_then_click\",\n \"page\": \"http://site.com/page-url\",\n \"on_load_text\": \"Message to show after navigation\"\n}\n\n3. Show message and click an element:\n{\n \"action\": \"message_and_click\",\n \"element\": \".className-of-element\",\n \"text\": \"Your message text\"\n}\n\n4. Create Stripe checkout:\n{\n \"action\": \"checkout\",\n \"text\": \"Your message text\",\n \"items\": [\n {\"name\": \"Product Name\", \"price\": 2999, \"quantity\": 1}\n ]\n}\n\nGuidelines:\n- Use \"message\" for simple conversational responses\n- Use \"nav_then_click\" when you need to navigate to a different page (like a product detail page)\n- Use \"message_and_click\" when you want to click a button or element on the current page\n- Use \"checkout\" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)\n- When selecting elements, use the class names provided in the page context\n- Always respond with valid JSON only, no additional text\n- For product searches, format results as markdown links: [Product Name](url)\n- Be helpful and conversational in your messages\n- Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)\n\nExample conversation flow:\n- User: \"I am looking for a black shirt in medium\"\n- You: {\"action\": \"message\", \"text\": \"Here are the products I found:\\\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\\\n\\\\nWould you like me to navigate to the first result and add it to your cart?\"}\n\n- User: \"No, I would like to add another shirt to the cart\"\n- You: {\"action\": \"message_and_click\", \"element\": \".AddToCartButton-blue-shirt-large\", \"text\": \"I've added the Blue Shirt - Large to your cart. Ready to checkout?\"}\n\n- User: \"yes\"\n- You: {\"action\": \"checkout\", \"text\": \"Perfect! I'll set up the checkout for you.\", \"items\": [{\"name\": \"Black Shirt - Medium\", \"price\": 2999, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n\n/**\n * Metadata-based shopping assistant flow configuration\n * This flow uses DOM context from record metadata instead of user message.\n * The metadata should include dom_elements, dom_body, page_url, and page_title.\n */\nexport const SHOPPING_ASSISTANT_METADATA_FLOW: RuntypeFlowConfig = {\n name: \"Metadata-Based Shopping Assistant\",\n description: \"Uses DOM context from record metadata for page interaction\",\n steps: [\n {\n id: \"metadata_action_prompt\",\n name: \"Metadata Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant that can interact with web pages.\n\nIMPORTANT: You have access to the current page's DOM elements through the record metadata, which includes:\n- dom_elements: Array of page elements with className, innerText, and tagName\n- dom_body: Complete HTML body of the page (if provided)\n- page_url: Current page URL\n- page_title: Page title\n\nThe dom_elements array provides information about clickable elements and their text content.\nUse this metadata to understand what's available on the page and help users interact with it.\n\nYou must respond with JSON in one of these formats:\n\n1. Simple message:\n{\n \"action\": \"message\",\n \"text\": \"Your response text here\"\n}\n\n2. Navigate then show message (for navigation to another page):\n{\n \"action\": \"nav_then_click\",\n \"page\": \"http://site.com/page-url\",\n \"on_load_text\": \"Message to show after navigation\"\n}\n\n3. Show message and click an element:\n{\n \"action\": \"message_and_click\",\n \"element\": \".className-of-element\",\n \"text\": \"Your message text\"\n}\n\n4. Create Stripe checkout:\n{\n \"action\": \"checkout\",\n \"text\": \"Your message text\",\n \"items\": [\n {\"name\": \"Product Name\", \"price\": 2999, \"quantity\": 1}\n ]\n}\n\nGuidelines:\n- Use \"message\" for simple conversational responses\n- Use \"nav_then_click\" when you need to navigate to a different page (like a product detail page)\n- Use \"message_and_click\" when you want to click a button or element on the current page\n- Use \"checkout\" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)\n- When selecting elements, use the class names from the dom_elements in the metadata\n- Always respond with valid JSON only, no additional text\n- For product searches, format results as markdown links: [Product Name](url)\n- Be helpful and conversational in your messages\n- Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)\n\nExample conversation flow:\n- User: \"I am looking for a black shirt in medium\"\n- You: {\"action\": \"message\", \"text\": \"Here are the products I found:\\\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\\\n\\\\nWould you like me to navigate to the first result and add it to your cart?\"}\n\n- User: \"No, I would like to add another shirt to the cart\"\n- You: {\"action\": \"message_and_click\", \"element\": \".AddToCartButton-blue-shirt-large\", \"text\": \"I've added the Blue Shirt - Large to your cart. Ready to checkout?\"}\n\n- User: \"yes\"\n- You: {\"action\": \"checkout\", \"text\": \"Perfect! I'll set up the checkout for you.\", \"items\": [{\"name\": \"Black Shirt - Medium\", \"price\": 2999, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Component-aware flow for custom component rendering\n * This flow instructs the AI to respond with component directives in JSON format\n */\nexport const COMPONENT_FLOW: RuntypeFlowConfig = {\n name: \"Component Flow\",\n description: \"Flow configured for custom component rendering\",\n steps: [\n {\n id: \"component_prompt\",\n name: \"Component Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful assistant that can both have conversations and render custom UI components.\n\nRESPONSE FORMAT:\nAlways respond with valid JSON. Choose the appropriate format based on the user's request:\n\n1. For CONVERSATIONAL questions or text responses:\n {\"text\": \"Your response here\"}\n\n2. For VISUAL DISPLAYS or when the user asks to SHOW/DISPLAY something:\n {\"component\": \"ComponentName\", \"props\": {...}}\n\n3. For BOTH explanation AND visual:\n {\"text\": \"Your explanation here\", \"component\": \"ComponentName\", \"props\": {...}}\n\nAvailable components for visual displays:\n- ProductCard: Display product information. Props: title (string), price (number), description (string, optional), image (string, optional)\n- SimpleChart: Display a bar chart. Props: title (string), data (array of numbers), labels (array of strings, optional)\n- StatusBadge: Display a status badge. Props: status (string: \"success\", \"error\", \"warning\", \"info\", \"pending\"), message (string)\n- InfoCard: Display an information card. Props: title (string), content (string), icon (string, optional)\n\nExamples:\n- User asks \"What is the capital of France?\": {\"text\": \"The capital of France is Paris.\"}\n- User asks \"What does that chart show?\": {\"text\": \"The chart shows sales data increasing from 100 to 200 over three months.\"}\n- User asks \"Show me a product card\": {\"component\": \"ProductCard\", \"props\": {\"title\": \"Laptop\", \"price\": 999, \"description\": \"A great laptop\"}}\n- User asks \"Display a chart\": {\"component\": \"SimpleChart\", \"props\": {\"title\": \"Sales\", \"data\": [100, 150, 200], \"labels\": [\"Jan\", \"Feb\", \"Mar\"]}}\n- User asks \"Show me a chart and explain it\": {\"text\": \"Here's the sales data for Q1:\", \"component\": \"SimpleChart\", \"props\": {\"title\": \"Q1 Sales\", \"data\": [100, 150, 200], \"labels\": [\"Jan\", \"Feb\", \"Mar\"]}}\n\nIMPORTANT:\n- Use {\"text\": \"...\"} for questions, explanations, discussions, and general chat\n- Use {\"component\": \"...\", \"props\": {...}} ONLY when the user explicitly wants to SEE/VIEW/DISPLAY visual content\n- You can combine both: {\"text\": \"...\", \"component\": \"...\", \"props\": {...}} when you want to explain something AND show a visual\n- Never force a component when the user just wants information`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","import type { RuntypeFlowConfig } from \"../index.js\";\n\n/**\n * Bakery assistant flow configuration for \"Flour & Stone\" bakery demo\n * This flow returns JSON actions for page interaction including:\n * - Simple messages with bakery brand voice\n * - Navigation to bakery pages\n * - Add to cart interactions\n * - Stripe checkout\n *\n * Designed to guide users toward the gift card when asking for gift recommendations.\n */\nexport const BAKERY_ASSISTANT_FLOW: RuntypeFlowConfig = {\n name: \"Bakery Assistant Flow\",\n description: \"Flour & Stone bakery shopping assistant with gift recommendations\",\n steps: [\n {\n id: \"bakery_action_prompt\",\n name: \"Bakery Action Prompt\",\n type: \"prompt\",\n enabled: true,\n config: {\n model: \"mercury-2\",\n reasoning: false,\n responseFormat: \"JSON\",\n outputVariable: \"prompt_result\",\n userPrompt: \"{{user_message}}\",\n systemPrompt: `You are a helpful shopping assistant for Flour & Stone, a premium artisan bakery known for traditional bread-making and exceptional pastries.\n\nBrand voice: Warm, knowledgeable, passionate about craft baking. Use phrases like \"fresh from the oven\", \"handcrafted with care\", \"artisan tradition\". Do not explain selectors, JSON, or templating to the user.\n\n## Live context (request inputs — substituted each turn)\n\nThe widget sends **only** these keys as dispatch **inputs** (nothing extra on the record for this demo).\n\n**Orientation**\n- Path: {{current_page}} (compare before nav_then_click; e.g. /bakery-goods.html)\n- Full URL: {{page_url}}\n- Title: {{page_title}}\n\n**Page DOM**\n- page_elements: JSON array of enriched nodes (selector, tagName, text, role, interactivity, attributes including data-*). Prefer **selector** for message_and_click when you click a specific control.\n- page_context: Same slice formatted for the LLM (structured card summaries when matched, then groups by interactivity).\n\n{{page_elements}}\n\n{{page_context}}\n\n**Cart (for checkout — mirror cart.items when user pays)**\n{{cart}}\n\n**Recent order (if any)**\n{{recent_order}}\n\nIf {{current_page}} already equals the page you would navigate to, use {\"action\":\"message\",...} instead of nav_then_click.\n\n## Discovering products\n\nUse {{page_context}} for a quick scan and {{page_elements}} for exact selectors and attributes. Product rows often include data-product in **attributes**; prices appear in **text**; add-to-cart controls are usually **clickable** with stable **selector** values.\n\n## Output: one JSON object only\n\nNo markdown fences, no commentary before/after. Valid JSON only.\n\n### 1. message\n{\"action\": \"message\", \"text\": \"...\"}\nUse for chat, clarifying questions, \"we're already on that page\", or when you need the user to choose (e.g. $25 vs $50 gift card).\n\n### 2. nav_then_click\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"...\"}\nUse root-relative paths starting with /. Only when current_page is different from the target. This **only** changes pages — it does **not** open Stripe or payment.\n\n### 3. add_to_cart\n{\"action\": \"add_to_cart\", \"text\": \"...\", \"item\": {\"id\": \"product-id\", \"name\": \"Product Name\", \"price\": 1200}}\nUse when adding from context without scrolling (optional; on goods page prefer scroll_then_add).\n\n### 4. scroll_then_add (preferred on /bakery-goods.html)\n{\"action\": \"scroll_then_add\", \"text\": \"...\", \"item\": {\"id\": \"...\", \"name\": \"...\", \"price\": 1200}}\nScrolls the product into view then adds one unit (cart merges duplicate ids into quantity).\n\n### 5. checkout → Stripe (this demo)\n{\"action\": \"checkout\", \"text\": \"Brief message\", \"items\": [{\"name\": \"...\", \"price\": 1200, \"quantity\": 2}, ...]}\n**Only** this action starts hosted checkout (Stripe). **Never** use nav_then_click to a \"/checkout\" URL for payment here.\nRequirements: cart in context must have items; **items array must list every cart line** with the same name, cent prices, and quantities as cart.items. If cart is null or empty, use message — do not checkout.\n\n### 6. message_and_click (rare)\nIf page_elements show a specific button selector and scroll_then_add is wrong, you may use message_and_click with a CSS selector — prefer scroll_then_add on bakery-goods.html.\n\n## Rules\n\n- Prices in JSON are always **integer cents** (1200 = $12.00).\n- After adding to cart, invite checkout or more shopping.\n- On checkout confirmation (\"yes\", \"checkout\", \"pay\", \"proceed\", etc.), build **items** from **cart.items** (all rows, correct quantity). Do not drop lines or invent prices.\n\n## Product catalog (ids and cent prices)\n\n- Sourdough Loaf: sourdough-loaf, 1200\n- Croissant Box (6): croissant-box, 2400\n- Cinnamon Rolls (4): cinnamon-rolls, 1800\n- Baguette Trio: baguette-trio, 900\n- Almond Tart: almond-tart, 800\n- Fruit Danish: fruit-danish, 600\n- $50 Gift Card: gift-card-50, 5000\n- $25 Gift Card: gift-card-25, 2500\n\n## Examples\n\nGift seeker on /bakery-locations.html:\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"Here are our goods! You'll find our gift cards below — $50 is our most popular. Want me to add one?\"}\n\nOn /bakery-goods.html, user wants $50 gift card:\n{\"action\": \"scroll_then_add\", \"text\": \"Added the $50 gift card. Ready to check out?\", \"item\": {\"id\": \"gift-card-50\", \"name\": \"$50 Gift Card\", \"price\": 5000}}\n\nUser on /bakery.html agrees to see products:\n{\"action\": \"nav_then_click\", \"page\": \"/bakery-goods.html\", \"on_load_text\": \"Here are our handcrafted goods — what sounds good today?\"}\n\nOn /bakery-goods.html, add sourdough:\n{\"action\": \"scroll_then_add\", \"text\": \"Sourdough is in your cart. Anything else, or shall we check out?\", \"item\": {\"id\": \"sourdough-loaf\", \"name\": \"Sourdough Loaf\", \"price\": 1200}}\n\nCart has one $50 gift card; user says yes to checkout:\n{\"action\": \"checkout\", \"text\": \"Opening secure checkout...\", \"items\": [{\"name\": \"$50 Gift Card\", \"price\": 5000, \"quantity\": 1}]}\n\nCart has sourdough (qty 1) and croissant box (qty 1); user says \"pay\":\n{\"action\": \"checkout\", \"text\": \"Taking you to checkout...\", \"items\": [{\"name\": \"Sourdough Loaf\", \"price\": 1200, \"quantity\": 1}, {\"name\": \"Croissant Box (6)\", \"price\": 2400, \"quantity\": 1}]}`,\n previousMessages: \"{{messages}}\"\n }\n }\n ]\n};\n","/**\n * Stripe checkout helpers using the REST API\n * This approach works on all platforms including Cloudflare Workers, Vercel Edge, etc.\n */\n\n/**\n * Pinned API version for raw HTTP calls (no SDK). Required for organization API keys and\n * keeps behavior stable across accounts. See https://docs.stripe.com/api/versioning\n */\nconst STRIPE_API_VERSION = \"2026-03-25.dahlia\";\n\nexport interface CheckoutItem {\n name: string;\n price: number; // Price in cents\n quantity: number;\n}\n\nexport interface CreateCheckoutSessionOptions {\n secretKey: string;\n items: CheckoutItem[];\n successUrl: string;\n cancelUrl: string;\n}\n\nexport interface CheckoutSessionResponse {\n success: boolean;\n checkoutUrl?: string;\n sessionId?: string;\n error?: string;\n}\n\nfunction parseStripeApiErrorBody(body: string): string | undefined {\n try {\n const parsed = JSON.parse(body) as {\n error?: { message?: string; type?: string };\n };\n const msg = parsed?.error?.message;\n return typeof msg === \"string\" && msg.length > 0 ? msg : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Creates a Stripe checkout session using the REST API\n * @param options - Checkout session configuration\n * @returns Checkout session response with URL and session ID\n */\nexport async function createCheckoutSession(\n options: CreateCheckoutSessionOptions\n): Promise<CheckoutSessionResponse> {\n const { secretKey, items, successUrl, cancelUrl } = options;\n\n try {\n // Validate items\n if (!items || !Array.isArray(items) || items.length === 0) {\n return {\n success: false,\n error: \"Items array is required\"\n };\n }\n\n for (const item of items) {\n if (!item.name || typeof item.price !== \"number\" || typeof item.quantity !== \"number\") {\n return {\n success: false,\n error: \"Each item must have name (string), price (number in cents), and quantity (number)\"\n };\n }\n if (\n !Number.isFinite(item.price) ||\n !Number.isInteger(item.price) ||\n item.price < 1 ||\n !Number.isInteger(item.quantity) ||\n item.quantity < 1\n ) {\n return {\n success: false,\n error:\n \"Each item needs a positive integer price (cents) and quantity (Stripe rejects decimals or zero)\",\n };\n }\n }\n\n // Build line items for URL encoding\n const lineItems = items.map((item) => ({\n price_data: {\n currency: \"usd\",\n product_data: {\n name: item.name,\n },\n unit_amount: item.price,\n },\n quantity: item.quantity,\n }));\n\n // Convert line items to URL-encoded format\n const params = new URLSearchParams({\n \"payment_method_types[0]\": \"card\",\n \"mode\": \"payment\",\n \"success_url\": successUrl,\n \"cancel_url\": cancelUrl,\n });\n\n // Add line items to params\n lineItems.forEach((item, index) => {\n params.append(`line_items[${index}][price_data][currency]`, item.price_data.currency);\n params.append(`line_items[${index}][price_data][product_data][name]`, item.price_data.product_data.name);\n params.append(`line_items[${index}][price_data][unit_amount]`, item.price_data.unit_amount.toString());\n params.append(`line_items[${index}][quantity]`, item.quantity.toString());\n });\n\n // Create Stripe checkout session using REST API\n const stripeResponse = await fetch(\"https://api.stripe.com/v1/checkout/sessions\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${secretKey}`,\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Stripe-Version\": STRIPE_API_VERSION,\n },\n body: params,\n });\n\n if (!stripeResponse.ok) {\n const errorData = await stripeResponse.text();\n const stripeMessage = parseStripeApiErrorBody(errorData);\n console.error(\"Stripe API error:\", errorData);\n return {\n success: false,\n error: stripeMessage ?? \"Failed to create checkout session\",\n };\n }\n\n const session = await stripeResponse.json() as { url: string; id: string };\n\n return {\n success: true,\n checkoutUrl: session.url,\n sessionId: session.id,\n };\n } catch (error) {\n console.error(\"Stripe checkout error:\", error);\n return {\n success: false,\n error: error instanceof Error ? error.message : \"Failed to create checkout session\"\n };\n }\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAErB,SAAS,cAAc;;;ACIhB,IAAM,sBAAyC;AAAA,EACpD,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO;AAAA,IACL;AAAA,MACE,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM;AAAA,MACN,SAAS;A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AAQ,IAAI,uCAAuC,CAAC;AAAA,QACtD;AAAA,MACF;AACA,cAAQ,IAAI,qCAAqC;AAAA,IACnD;AAEA,WAAO,IAAI,SAAS,SAAS,MAAM;AAAA,MACjC,QAAQ,SAAS;AAAA,MACjB,SAAS;AAAA,QACP,iBACE,cAAS,QAAQ,IAAI,cAAc,MAAnC,YAAwC;AAAA,QAC1C,iBAAiB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;AAEO,IAAM,sBAAsB,CAAC,YAClC,OAAO,mBAAmB,OAAO,CAAC;AAQpC,IAAO,gBAAQ;","names":["_a","_b","_c"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtypelabs/persona-proxy",
3
- "version": "2.3.0",
3
+ "version": "3.8.4",
4
4
  "description": "Proxy server for @runtypelabs/persona widget - handles flow configuration and forwards requests to AI backends.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -18,7 +18,7 @@
18
18
  "src"
19
19
  ],
20
20
  "dependencies": {
21
- "hono": "^4.4.9"
21
+ "hono": "^4.12.7"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@types/node": "^20.12.7",
@@ -32,7 +32,7 @@
32
32
  "vitest": "^4.1.0"
33
33
  },
34
34
  "engines": {
35
- "node": ">=18.17.0"
35
+ "node": ">=20.0.0"
36
36
  },
37
37
  "author": "Runtype",
38
38
  "license": "MIT",
package/src/index.ts CHANGED
@@ -16,7 +16,7 @@ export type RuntypeFlowConfig = {
16
16
  steps: RuntypeFlowStep[];
17
17
  };
18
18
 
19
-
19
+ type RuntimeEnv = Record<string, string | undefined>;
20
20
 
21
21
  /**
22
22
  * Payload for message feedback (upvote/downvote)
@@ -63,6 +63,17 @@ export type ChatProxyOptions = {
63
63
  const DEFAULT_ENDPOINT = "https://api.runtype.com/v1/dispatch";
64
64
  const DEFAULT_PATH = "/api/chat/dispatch";
65
65
 
66
+ const getRuntimeEnv = (): RuntimeEnv | undefined => {
67
+ const maybeProcess = (
68
+ globalThis as typeof globalThis & { process?: { env?: RuntimeEnv } }
69
+ ).process;
70
+ return maybeProcess?.env;
71
+ };
72
+
73
+ /** True only when `NODE_ENV` is exactly `"development"` (unset = production). Safe when `process` is missing (e.g. some Workers runtimes). */
74
+ const isDevelopmentRuntime = (): boolean =>
75
+ getRuntimeEnv()?.NODE_ENV === "development";
76
+
66
77
  const DEFAULT_FLOW: RuntypeFlowConfig = {
67
78
  name: "Streaming Prompt Flow",
68
79
  description: "Streaming chat generated by the widget",
@@ -93,7 +104,7 @@ const withCors =
93
104
  (allowedOrigins: string[] | undefined) =>
94
105
  async (c: Context, next: () => Promise<void>) => {
95
106
  const origin = c.req.header("origin");
96
- const isDevelopment = process.env.NODE_ENV === "development";
107
+ const isDevelopment = isDevelopmentRuntime();
97
108
 
98
109
  // Determine the CORS origin to allow
99
110
  let corsOrigin: string;
@@ -166,17 +177,13 @@ export const createChatProxyApp = (options: ChatProxyOptions = {}) => {
166
177
  // Add timestamp if not provided
167
178
  payload.timestamp = payload.timestamp ?? new Date().toISOString();
168
179
 
169
- const isDevelopment =
170
- process.env.NODE_ENV === "development";
180
+ const isDevelopment = isDevelopmentRuntime();
171
181
 
172
182
  if (isDevelopment) {
173
183
  console.log("\n=== Feedback Received ===");
174
184
  console.log("Type:", payload.type);
175
185
  console.log("Message ID:", payload.messageId);
176
- console.log(
177
- "Content Preview:",
178
- payload.content?.substring(0, 100) ?? "(none)"
179
- );
186
+ console.log("Content Length:", payload.content?.length ?? 0);
180
187
  console.log("Timestamp:", payload.timestamp);
181
188
  console.log("=== End Feedback ===\n");
182
189
  }
@@ -204,7 +211,7 @@ export const createChatProxyApp = (options: ChatProxyOptions = {}) => {
204
211
 
205
212
  // Chat dispatch endpoint
206
213
  app.post(path, async (c) => {
207
- const apiKey = options.apiKey ?? process.env.RUNTYPE_API_KEY;
214
+ const apiKey = options.apiKey ?? getRuntimeEnv()?.RUNTYPE_API_KEY;
208
215
  if (!apiKey) {
209
216
  return c.json(
210
217
  { error: "Missing API key. Set RUNTYPE_API_KEY." },
@@ -222,7 +229,7 @@ export const createChatProxyApp = (options: ChatProxyOptions = {}) => {
222
229
  );
223
230
  }
224
231
 
225
- const isDevelopment = process.env.NODE_ENV === "development";
232
+ const isDevelopment = isDevelopmentRuntime();
226
233
 
227
234
  // Detect agent mode: if the payload contains an `agent` field, forward it directly
228
235
  const isAgentMode = !!clientPayload.agent;
@@ -275,6 +282,7 @@ export const createChatProxyApp = (options: ChatProxyOptions = {}) => {
275
282
  }
276
283
  }
277
284
 
285
+ // Development only: do not log key material or full bodies in production.
278
286
  if (isDevelopment) {
279
287
  console.log(`\n=== Runtype Proxy Request (${isAgentMode ? "agent" : "flow"}) ===`);
280
288
  console.log("URL:", upstream);
@@ -332,4 +340,3 @@ export * from "./flows/index.js";
332
340
  export * from "./utils/index.js";
333
341
 
334
342
  export default createChatProxyApp;
335
-
@@ -3,6 +3,12 @@
3
3
  * This approach works on all platforms including Cloudflare Workers, Vercel Edge, etc.
4
4
  */
5
5
 
6
+ /**
7
+ * Pinned API version for raw HTTP calls (no SDK). Required for organization API keys and
8
+ * keeps behavior stable across accounts. See https://docs.stripe.com/api/versioning
9
+ */
10
+ const STRIPE_API_VERSION = "2026-03-25.dahlia";
11
+
6
12
  export interface CheckoutItem {
7
13
  name: string;
8
14
  price: number; // Price in cents
@@ -23,6 +29,18 @@ export interface CheckoutSessionResponse {
23
29
  error?: string;
24
30
  }
25
31
 
32
+ function parseStripeApiErrorBody(body: string): string | undefined {
33
+ try {
34
+ const parsed = JSON.parse(body) as {
35
+ error?: { message?: string; type?: string };
36
+ };
37
+ const msg = parsed?.error?.message;
38
+ return typeof msg === "string" && msg.length > 0 ? msg : undefined;
39
+ } catch {
40
+ return undefined;
41
+ }
42
+ }
43
+
26
44
  /**
27
45
  * Creates a Stripe checkout session using the REST API
28
46
  * @param options - Checkout session configuration
@@ -49,6 +67,19 @@ export async function createCheckoutSession(
49
67
  error: "Each item must have name (string), price (number in cents), and quantity (number)"
50
68
  };
51
69
  }
70
+ if (
71
+ !Number.isFinite(item.price) ||
72
+ !Number.isInteger(item.price) ||
73
+ item.price < 1 ||
74
+ !Number.isInteger(item.quantity) ||
75
+ item.quantity < 1
76
+ ) {
77
+ return {
78
+ success: false,
79
+ error:
80
+ "Each item needs a positive integer price (cents) and quantity (Stripe rejects decimals or zero)",
81
+ };
82
+ }
52
83
  }
53
84
 
54
85
  // Build line items for URL encoding
@@ -83,18 +114,20 @@ export async function createCheckoutSession(
83
114
  const stripeResponse = await fetch("https://api.stripe.com/v1/checkout/sessions", {
84
115
  method: "POST",
85
116
  headers: {
86
- "Authorization": `Bearer ${secretKey}`,
117
+ Authorization: `Bearer ${secretKey}`,
87
118
  "Content-Type": "application/x-www-form-urlencoded",
119
+ "Stripe-Version": STRIPE_API_VERSION,
88
120
  },
89
121
  body: params,
90
122
  });
91
123
 
92
124
  if (!stripeResponse.ok) {
93
125
  const errorData = await stripeResponse.text();
126
+ const stripeMessage = parseStripeApiErrorBody(errorData);
94
127
  console.error("Stripe API error:", errorData);
95
128
  return {
96
129
  success: false,
97
- error: "Failed to create checkout session"
130
+ error: stripeMessage ?? "Failed to create checkout session",
98
131
  };
99
132
  }
100
133