Stitch Design Agent
Autonomous agent that requests designs from Google Stitch via its API and
integrates them into the active project. The full flow is:
CODEBLOCK0
1. Prerequisites
| Resource | Where to get it |
|---|
Google OAuth 2.0 token with cloud-platform scope | Step 2 below |
| Active project (React / NestJS / any stack) |
Must already be in the workspace |
|
STITCH_TOKEN environment variable |
.env file or agent secret |
2. Obtaining the Google Stitch Token
Option A — User token (interactive flow)
CODEBLOCK1
Option B — Service Account (headless / CI flow)
CODEBLOCK2
The agent must always read the token from the STITCH_TOKEN environment variable.
Never hardcode tokens in source code.
3. Calling the Stitch API with a Design Prompt
Main endpoint
CODEBLOCK3
Request payload
CODEBLOCK4
Example of an effective prompt
CODEBLOCK5
Expected response
{
"design_id": "dsgn_abc123",
"component_name": "FinancialSummaryCard",
"code": "import React from 'react';\n\nexport const FinancialSummaryCard = ...",
"assets": [],
"metadata": {
"tokens_used": 840,
"framework": "react"
}
}
4. Integrating the Design into the Active Project
4.1 — Save the component
CODEBLOCK7
4.2 — Detect where to import it
The agent should scan the project to find the most logical integration point:
CODEBLOCK8
4.3 — Insert the import and usage
CODEBLOCK9
4.4 — Verify it compiles
npx tsc --noEmit # Check TypeScript types
npm run lint -- --fix # Auto-fix linting issues
5. Full Agent Flow (pseudocode)
CODEBLOCK11
6. Error Handling
| Error | Likely cause | Agent action |
|---|
| INLINECODE4 | Token expired or invalid | Ask the user for a new token or refresh automatically |
| INLINECODE5 |
Prompt too vague or invalid payload | Refine the prompt and retry |
|
429 Too Many Requests | Rate limit reached | Wait 60s and retry |
|
TypeScript errors | Generated component has incorrect types | Fix types manually or request regeneration |
|
Import conflicts | Component name already exists in the project | Rename with a
_v2 suffix |
7. OpenClaw Configuration
CODEBLOCK12
8. Important Notes for the Agent
- - Always ask the user for a design prompt before calling Stitch if one was
not explicitly provided.
- - Tokens live for ~1 hour. If the token expires, use the
refresh_token to
renew it automatically before retrying.
- - Check whether the generated component uses libraries not yet installed
(e.g.
recharts,
framer-motion) and run
npm install <pkg> before integrating.
- - Respect the project architecture: in hexagonal/modular layouts, components
belong in
src/modules/<domain>/components/, not at the
src/components/ root.
- - If the project has its own design system, include in the prompt:
"follow the app's existing design system and use its CSS tokens".
- - If the generated code references hardcoded colors or sizes that conflict with
the existing theme, replace them with the project's CSS variables before saving.
Stitch 设计代理
通过 Google Stitch API 请求设计并将其集成到当前项目中的自主代理。完整流程如下:
OAuth 令牌 → 设计提示 → Stitch API → 生成的代码 → 项目集成
1. 前提条件
| 资源 | 获取方式 |
|---|
| 具有 cloud-platform 范围的 Google OAuth 2.0 令牌 | 下方第 2 步 |
| 当前项目(React / NestJS / 任意技术栈) |
必须已存在于工作区中 |
| STITCH_TOKEN 环境变量 | .env 文件或代理密钥 |
2. 获取 Google Stitch 令牌
选项 A — 用户令牌(交互式流程)
bash
1. 将用户重定向到授权 URL
GET https://accounts.google.com/o/oauth2/v2/auth
?client_id=<客户端ID>
&redirect_uri=<重定向URI>
&response_type=code
&scope=https://www.googleapis.com/auth/cloud-platform
&access_type=offline
2. 将授权码交换为令牌
POST https://oauth2.googleapis.com/token
grant
type=authorizationcode
&code=<授权码>
&client_id=<客户端ID>
&client_secret=<客户端密钥>
&redirect_uri=<重定向URI>
响应:
{ accesstoken: ya29.xxx, refreshtoken: 1//xxx, expires_in: 3599 }
选项 B — 服务账号(无头 / CI 流程)
bash
使用服务账号密钥生成签名的 JWT 并进行交换:
POST https://oauth2.googleapis.com/token
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer
&assertion=<签名后的JWT>
代理必须始终从 STITCH_TOKEN 环境变量中读取令牌。
切勿在源代码中硬编码令牌。
3. 使用设计提示调用 Stitch API
主端点
POST https://stitch.googleapis.com/v1/designs:generate
Authorization: Bearer {STITCH_TOKEN}
Content-Type: application/json
请求负载
json
{
prompt: <所需设计的自然语言描述>,
output
format: reactcomponent, // html | react
component | vuecomponent
theme: {
primary_color: #3B82F6,
font_family: Inter
},
context: {
framework: react,
styling: tailwind // css
modules | tailwind | styledcomponents
}
}
有效提示示例
创建一个财务摘要卡片组件,包含:
- - 顶部突出显示总余额
- 显示最近 7 天的小型柱状图
- 两个操作按钮:收入和支出
- 极简风格,带柔和阴影
- 支持深色模式
预期响应
json
{
design
id: dsgnabc123,
component_name: FinancialSummaryCard,
code: import React from react;\n\nexport const FinancialSummaryCard = ...,
assets: [],
metadata: {
tokens_used: 840,
framework: react
}
}
4. 将设计集成到当前项目中
4.1 — 保存组件
typescript
// 代理必须:
// 1. 从 Stitch 响应中提取 response.code
// 2. 根据项目结构确定正确的路径
const componentName = response.component_name; // 例如 FinancialSummaryCard
const targetPath = src/components/${componentName}.tsx;
// 3. 写入文件
fs.writeFileSync(targetPath, response.code, utf-8);
4.2 — 检测导入位置
代理应扫描项目以找到最合理的集成点:
bash
查找可能使用新组件的文件
grep -r Dashboard\|Overview\|Home\|Layout src/pages --include=*.tsx -l
4.3 — 插入导入和使用代码
typescript
// 添加到目标文件:
import { FinancialSummaryCard } from ../components/FinancialSummaryCard;
// 在 JSX 中:
4.4 — 验证编译
bash
npx tsc --noEmit # 检查 TypeScript 类型
npm run lint -- --fix # 自动修复 lint 问题
5. 完整代理流程(伪代码)
typescript
async function stitchDesignFlow(userPrompt: string) {
// 第 1 步:读取令牌
const token = process.env.STITCH_TOKEN;
if (!token) throw new Error(STITCH_TOKEN 未配置);
// 第 2 步:向 Stitch 请求设计
const stitchResponse = await fetch(
https://stitch.googleapis.com/v1/designs:generate,
{
method: POST,
headers: {
Authorization: Bearer ${token},
Content-Type: application/json,
},
body: JSON.stringify({
prompt: userPrompt,
outputformat: reactcomponent,
context: { framework: react, styling: tailwind },
}),
}
);
const design = await stitchResponse.json();
// 第 3 步:保存组件
const filePath = src/components/${design.component_name}.tsx;
fs.writeFileSync(filePath, design.code);
// 第 4 步:查找集成点
const integrationTarget = await detectIntegrationPoint(design.component_name);
// 第 5 步:注入导入和 JSX
await injectComponent(integrationTarget, design.component_name);
// 第 6 步:验证构建
execSync(npx tsc --noEmit);
return { filePath, integrationTarget };
}
6. 错误处理
| 错误 | 可能原因 | 代理操作 |
|---|
| 401 Unauthorized | 令牌已过期或无效 | 要求用户提供新令牌或自动刷新 |
| 400 Bad Request |
提示过于模糊或负载无效 | 优化提示并重试 |
| 429 Too Many Requests | 达到速率限制 | 等待 60 秒后重试 |
| TypeScript 错误 | 生成的组件类型不正确 | 手动修复类型或请求重新生成 |
| 导入冲突 | 组件名称在项目中已存在 | 使用 _v2 后缀重命名 |
7. OpenClaw 配置
yaml
openclaw.config.yml(相关部分)
agents:
stitch-designer:
skill: stitch-design-agent
env:
STITCH
TOKEN: ${secrets.GOOGLESTITCH_TOKEN}
tools:
- file_write
- file_read
- bash
- web_fetch
triggers:
- 设计一个组件
- 让 stitch 设计
- 集成 stitch 的 UI
- 生成视图
- 创建一个界面
8. 代理重要注意事项
- - 始终在调用 Stitch 之前向用户询问设计提示(如果未明确提供)。
- 令牌有效期约为 1 小时。如果令牌过期,请在重试前使用 refresh_token 自动续期。
- 检查生成的组件是否使用了尚未安装的库(例如 recharts、framer-motion),并在集成前运行 npm install <包名>。
- 尊重项目架构:在六边形/模块化布局中,组件应放在 src/modules/<领域>/components/ 中,而不是 src/components/ 根目录。
- 如果项目有自己的设计系统,请在提示中包含:遵循应用现有的设计系统并使用其 CSS 令牌。
- 如果生成的代码引用了与现有主题冲突的硬编码颜色或尺寸,请在保存前将其替换为项目的 CSS 变量。