diff --git a/migrations/0002_ai_generate.sql b/migrations/0002_ai_generate.sql
new file mode 100644
index 0000000..203faba
--- /dev/null
+++ b/migrations/0002_ai_generate.sql
@@ -0,0 +1,31 @@
+-- POST /api/generate (worker/generate.ts, worker/ai-budget.ts): the AI pipeline builder's
+-- daily spend, per-IP daily counts and answer cache. Pruned daily (worker/index.ts, scheduled):
+-- ip rows after 2 days, spend rows after 92 days, cached answers after 30 days.
+
+-- One row per UTC day. reserved_micro is in micro-dollars: each call reserves its worst case
+-- here before it runs and is corrected to its actual cost afterwards.
+CREATE TABLE ai_spend (
+ day TEXT PRIMARY KEY,
+ reserved_micro INTEGER NOT NULL DEFAULT 0,
+ calls INTEGER NOT NULL DEFAULT 0
+);
+
+-- Model calls per client per UTC day. ip_hash is an HMAC (secret AI_IP_SALT) of the day and the
+-- client's address bucket, so the address is never stored and hashes do not link across days.
+CREATE TABLE ai_ip_daily (
+ day TEXT NOT NULL,
+ ip_hash TEXT NOT NULL,
+ count INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (day, ip_hash)
+);
+
+-- Generated steps by a SHA-256 of the normalised description, model id and catalog version;
+-- the description itself is not stored. created_at is Unix milliseconds.
+CREATE TABLE ai_answer_cache (
+ key TEXT PRIMARY KEY,
+ steps TEXT NOT NULL,
+ notes TEXT NOT NULL DEFAULT '',
+ created_at INTEGER NOT NULL
+);
+
+CREATE INDEX ai_answer_cache_created ON ai_answer_cache (created_at);
diff --git a/package-lock.json b/package-lock.json
index 2049416..c1863b7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9,6 +9,7 @@
"version": "1.18.2",
"license": "MIT",
"dependencies": {
+ "@anthropic-ai/sdk": "^1.14.0",
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
@@ -107,6 +108,28 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/@anthropic-ai/sdk": {
+ "version": "1.14.0",
+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-1.14.0.tgz",
+ "integrity": "sha512-nADYXUd5fn9Zgw2nHi1iKyt/kb1UUt1cN3RbdxEI6XjTDTxbx4LLG4GnMrxWyS9GgXQllFOyAKSiFM3joDNK9A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api": "^1.4.1",
+ "json-schema-to-ts": "^3.1.1",
+ "standardwebhooks": "^1.0.0"
+ },
+ "bin": {
+ "anthropic-ai-sdk": "bin/cli"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.0 || ^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "zod": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@asamuzakjp/css-color": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-4.0.5.tgz",
@@ -2370,6 +2393,15 @@
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT"
},
+ "node_modules/@opentelemetry/api": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz",
+ "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
"node_modules/@oxc-project/types": {
"version": "0.155.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz",
@@ -2759,6 +2791,12 @@
"dev": true,
"license": "CC0-1.0"
},
+ "node_modules/@stablelib/base64": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
+ "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
+ "license": "MIT"
+ },
"node_modules/@tailwindcss/node": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz",
@@ -5135,6 +5173,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/fast-sha256": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
+ "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
+ "license": "Unlicense"
+ },
"node_modules/fast-uri": {
"version": "3.1.9",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz",
@@ -5822,6 +5866,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/json-schema-to-ts": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
+ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.18.3",
+ "ts-algebra": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
"node_modules/json-schema-traverse": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
@@ -7427,6 +7484,16 @@
"sql-formatter": "bin/sql-formatter-cli.cjs"
}
},
+ "node_modules/standardwebhooks": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.3.0.tgz",
+ "integrity": "sha512-5W9skHjqAm2dlA9wWvglTP+oX47JX4lFXVk1aJV7+TG1snvTR4QXaVgPscEzvOw9GRreeavMwbqEeL+MGhZHCg==",
+ "license": "MIT",
+ "dependencies": {
+ "@stablelib/base64": "^1.0.0",
+ "fast-sha256": "^1.3.0"
+ }
+ },
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@@ -7636,6 +7703,12 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/ts-algebra": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
+ "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
+ "license": "MIT"
+ },
"node_modules/ts-api-utils": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",
diff --git a/package.json b/package.json
index 9f3a8a6..9335070 100644
--- a/package.json
+++ b/package.json
@@ -48,6 +48,7 @@
"release": "vite-node scripts/release.ts"
},
"dependencies": {
+ "@anthropic-ai/sdk": "^1.14.0",
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
diff --git a/src/app/commands/commands.test.ts b/src/app/commands/commands.test.ts
index 5500bd8..5c7f9c3 100644
--- a/src/app/commands/commands.test.ts
+++ b/src/app/commands/commands.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
commands, commandById, listShortcuts, TOOL_COMMAND_EVENT, EVENT_MAGIC, EVENT_OPEN_SHARE,
- EVENT_OPEN_LIBRARY, EVENT_OPEN_PRESETS, EVENT_TOGGLE_THEME, EVENT_OPEN_SHORTCUTS,
+ EVENT_OPEN_LIBRARY, EVENT_OPEN_PRESETS, EVENT_OPEN_GENERATE, EVENT_TOGGLE_THEME, EVENT_OPEN_SHORTCUTS,
attachToolBridge, hasToolBridge, queueToolCommand, type ToolCommandDetail,
} from './commands'
@@ -63,6 +63,7 @@ describe('commands', () => {
['share', EVENT_OPEN_SHARE],
['library', EVENT_OPEN_LIBRARY],
['presets', EVENT_OPEN_PRESETS],
+ ['generate', EVENT_OPEN_GENERATE],
]
it.each(TOOL_DIALOGS)('%s fires the %s window event straight away while an editor is on screen', (id, eventName) => {
diff --git a/src/app/commands/commands.ts b/src/app/commands/commands.ts
index 86f0d92..e4ea243 100644
--- a/src/app/commands/commands.ts
+++ b/src/app/commands/commands.ts
@@ -21,6 +21,8 @@ export const EVENT_MAGIC = 'sub:magic'
export const EVENT_OPEN_SHARE = 'sub:open-share'
export const EVENT_OPEN_LIBRARY = 'sub:open-library'
export const EVENT_OPEN_PRESETS = 'sub:open-presets'
+/** Opens the describe dialog (the AI pipeline builder, `src/app/generate/`). */
+export const EVENT_OPEN_GENERATE = 'sub:open-generate'
export const EVENT_TOGGLE_THEME = 'sub:toggle-theme'
export const EVENT_OPEN_SHORTCUTS = 'sub:open-shortcuts'
export const EVENT_OPEN_PALETTE = 'sub:open-palette'
@@ -142,6 +144,7 @@ export const commands: Command[] = [
{ id: 'share', title: 'Share', group: 'Pipeline', keywords: ['share', 'link', 'url'], run: fireInTool(EVENT_OPEN_SHARE) },
{ id: 'library', title: 'Library', group: 'Pipeline', keywords: ['library', 'save', 'load', 'pipelines'], run: fireInTool(EVENT_OPEN_LIBRARY) },
{ id: 'presets', title: 'Start from a preset', group: 'Pipeline', keywords: ['presets', 'recipes', 'examples', 'templates', 'gallery'], run: fireInTool(EVENT_OPEN_PRESETS) },
+ { id: 'generate', title: 'Describe a pipeline (AI)', group: 'Pipeline', keywords: ['ai', 'describe', 'generate', 'build', 'prompt', 'natural language'], run: fireInTool(EVENT_OPEN_GENERATE) },
{ id: 'toggle-theme', title: 'Toggle theme', group: 'View', keywords: ['theme', 'dark', 'light', 'mode'], run: fire(EVENT_TOGGLE_THEME) },
{ id: 'shortcuts', title: 'Keyboard shortcuts', group: 'Help', keywords: ['shortcuts', 'help', 'keys'], run: fire(EVENT_OPEN_SHORTCUTS) },
{ id: 'goto-tool', title: 'Go to Tool', group: 'Navigate', keywords: ['tool', 'home', 'pipeline'], run: goToTool },
diff --git a/src/app/generate/GenerateButton.tsx b/src/app/generate/GenerateButton.tsx
new file mode 100644
index 0000000..4ef41fb
--- /dev/null
+++ b/src/app/generate/GenerateButton.tsx
@@ -0,0 +1,51 @@
+import React, { Suspense, lazy, useEffect, useRef, useState } from 'react'
+import { Sparkles } from 'lucide-react'
+import { EVENT_OPEN_GENERATE } from '@/app/commands/commands'
+import { useT } from '@/app/i18n/useT'
+import Dialog from '@/app/library/Dialog'
+import type { GenerateDialogProps } from './GenerateDialog'
+
+/** What the dialog shows when its chunk cannot be fetched (offline, or a stale tab after a deploy). */
+function GenerateUnavailable({ onClose, returnFocus }: GenerateDialogProps) {
+ const { t } = useT()
+ return (
+
+ )
+}
+
+// Lazy, so the dialog stays out of the editor's entry chunk until someone opens it.
+const GenerateDialog = lazy(() =>
+ import('./GenerateDialog').catch(() => ({ default: GenerateUnavailable })),
+)
+
+/**
+ * Opens the describe dialog (REQ-027) from beside the step list. Also opens on the
+ * `sub:open-generate` window event, which the command palette fires.
+ */
+export default function GenerateButton({ className = 'btn h-[30px] px-2.5' }: { className?: string }) {
+ const { t } = useT()
+ const [open, setOpen] = useState(false)
+ const buttonRef = useRef(null)
+
+ useEffect(() => {
+ const onOpen = () => setOpen(true)
+ window.addEventListener(EVENT_OPEN_GENERATE, onOpen)
+ return () => window.removeEventListener(EVENT_OPEN_GENERATE, onOpen)
+ }, [])
+
+ return (
+ <>
+
+ {open && (
+
+ setOpen(false)} returnFocus={buttonRef} />
+
+ )}
+ >
+ )
+}
diff --git a/src/app/generate/GenerateDialog.test.tsx b/src/app/generate/GenerateDialog.test.tsx
new file mode 100644
index 0000000..8e32d81
--- /dev/null
+++ b/src/app/generate/GenerateDialog.test.tsx
@@ -0,0 +1,159 @@
+import React from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { ToolProvider, useTool } from '@/app/ToolContext'
+import type { PipelineStep } from '@/types/utility'
+import GenerateDialog from './GenerateDialog'
+import GenerateButton from './GenerateButton'
+import { EVENT_OPEN_GENERATE } from '@/app/commands/commands'
+
+const EXISTING: PipelineStep[] = [{ id: 'old', utilityId: 'url_decode', enabled: true, params: {} }]
+
+const OK = {
+ steps: [
+ { id: 's1', utilityId: 'base64_decode', enabled: true, params: {} },
+ { id: 's2', utilityId: 'json_pretty', enabled: true, params: { indent: 4 } },
+ ],
+ why: ['turns the base64 back into text', 'indents the JSON'],
+ notes: 'Left out sort keys (unknown utility).',
+ cached: false,
+}
+
+let fetchMock: ReturnType
+const answer = (status: number, body: unknown, headers: Record = {}) => {
+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(body), {
+ status, headers: { 'content-type': 'application/json; charset=utf-8', ...headers },
+ }))
+}
+
+beforeEach(() => {
+ fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+})
+afterEach(() => { vi.unstubAllGlobals() })
+
+function Probe() {
+ const { state, dispatch } = useTool()
+ return (
+ <>
+
{state.steps.map(s => ('utilityId' in s ? s.utilityId : s.type)).join(',')}
+
+ >
+ )
+}
+
+function Harness({ steps = EXISTING, onClose = () => {} }: { steps?: PipelineStep[]; onClose?: () => void }) {
+ return (
+
+
+
+
+ )
+}
+
+const ids = () => screen.getByTestId('ids').textContent
+
+async function describeAndSubmit(text = 'decode base64 then pretty-print') {
+ const user = userEvent.setup()
+ await user.type(screen.getByLabelText('What should the pipeline do?'), text)
+ await user.click(screen.getByRole('button', { name: 'Build steps' }))
+ return user
+}
+
+describe('GenerateDialog', () => {
+ it('sends only the description and lists each step with its reason and the notes', async () => {
+ answer(200, OK)
+ render()
+ await describeAndSubmit()
+ expect(await screen.findByText('base64 decode')).toBeInTheDocument()
+ expect(screen.getByText(/turns the base64 back into text/)).toBeInTheDocument()
+ expect(screen.getByText(/indents the JSON/)).toBeInTheDocument()
+ expect(screen.getByText('Left out sort keys (unknown utility).')).toBeInTheDocument()
+ expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ description: 'decode base64 then pretty-print' })
+ })
+
+ it('replaces the pipeline in one undoable step and closes', async () => {
+ answer(200, OK)
+ const onClose = vi.fn()
+ render()
+ const user = await describeAndSubmit()
+ await user.click(await screen.findByRole('button', { name: 'Replace pipeline' }))
+ expect(ids()).toBe('base64_decode,json_pretty')
+ expect(onClose).toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'probe undo' }))
+ expect(ids()).toBe('url_decode')
+ })
+
+ it('adds the steps to the end in one undoable step', async () => {
+ answer(200, OK)
+ render()
+ const user = await describeAndSubmit()
+ await user.click(await screen.findByRole('button', { name: 'Add to the end' }))
+ expect(ids()).toBe('url_decode,base64_decode,json_pretty')
+ await user.click(screen.getByRole('button', { name: 'probe undo' }))
+ expect(ids()).toBe('url_decode')
+ })
+
+ it('offers only "Use these steps" when the pipeline is empty', async () => {
+ answer(200, OK)
+ render()
+ const user = await describeAndSubmit()
+ const use = await screen.findByRole('button', { name: 'Use these steps' })
+ expect(screen.queryByRole('button', { name: 'Add to the end' })).toBeNull()
+ await user.click(use)
+ expect(ids()).toBe('base64_decode,json_pretty')
+ })
+
+ it.each([
+ [503, { code: 'ai_off' }, {}, /not switched on/, true],
+ [503, { code: 'ai_budget' }, {}, /used up today’s budget/, true],
+ [429, { code: 'ai_rate' }, { 'retry-after': '20' }, /Try again in 20 s/, true],
+ [429, { code: 'ai_rate' }, { 'retry-after': '43200' }, /all the AI pipelines for today/, true],
+ [400, { code: 'ai_invalid' }, {}, /at most 500 characters/, false],
+ [422, { code: 'ai_unusable', notes: 'Left out custom js.' }, {}, /No usable steps/, true],
+ [502, { code: 'ai_upstream' }, {}, /could not be reached. Try again in a minute/, true],
+ ])('shows its own message for %s %j', async (status, body, headers, message, fallback) => {
+ answer(status, { error: 'server text', ...body }, headers)
+ render()
+ await describeAndSubmit()
+ const alert = await screen.findByRole('alert')
+ expect(alert).toHaveTextContent(message)
+ if ('notes' in body) expect(alert).toHaveTextContent('Left out custom js.')
+ const search = screen.queryByRole('link', { name: 'search the utilities' })
+ if (fallback) {
+ expect(search).toHaveAttribute('href', '/utilities/')
+ expect(screen.getByRole('link', { name: /MCP server/ })).toHaveAttribute('href', '/integrations/#mcp-server-for-ai-agents')
+ } else {
+ expect(search).toBeNull()
+ }
+ expect(ids()).toBe('url_decode')
+ })
+
+ it('says it could not reach the builder when there is no Worker (a dev server page)', async () => {
+ fetchMock.mockResolvedValueOnce(new Response('', { status: 200, headers: { 'content-type': 'text/html' } }))
+ render()
+ await describeAndSubmit()
+ expect(await screen.findByRole('alert')).toHaveTextContent(/could not be reached. Check your connection/)
+ })
+
+ it('keeps the button off for an empty description and caps it at 500 characters', () => {
+ render()
+ expect(screen.getByRole('button', { name: 'Build steps' })).toBeDisabled()
+ expect(screen.getByLabelText('What should the pipeline do?')).toHaveAttribute('maxLength', '500')
+ expect(screen.getByRole('link', { name: 'What is kept' })).toHaveAttribute('href', '/privacy/#features-that-contact-our-server')
+ })
+})
+
+describe('GenerateButton', () => {
+ it('opens the dialog on click and on the command palette event', async () => {
+ const user = userEvent.setup()
+ render()
+ await user.click(screen.getByRole('button', { name: /Describe it/ }))
+ expect(await screen.findByRole('dialog', { name: 'Describe a pipeline' })).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'close dialog' }))
+ expect(screen.queryByRole('dialog')).toBeNull()
+ window.dispatchEvent(new CustomEvent(EVENT_OPEN_GENERATE))
+ expect(await screen.findByRole('dialog', { name: 'Describe a pipeline' })).toBeInTheDocument()
+ })
+})
diff --git a/src/app/generate/GenerateDialog.tsx b/src/app/generate/GenerateDialog.tsx
new file mode 100644
index 0000000..b1e2f1b
--- /dev/null
+++ b/src/app/generate/GenerateDialog.tsx
@@ -0,0 +1,166 @@
+import React, { useEffect, useId, useRef, useState } from 'react'
+import { cloneWithNewIds, isUtilityStep } from '@/core/steps'
+import { useTool } from '@/app/ToolContext'
+import { registry } from '@/app/registry'
+import { useT } from '@/app/i18n/useT'
+import Dialog from '@/app/library/Dialog'
+import { generatePipeline, MAX_DESCRIPTION_CHARS, type GenerateResult } from './generate'
+
+export interface GenerateDialogProps {
+ onClose: () => void
+ /** Focus target on close when the dialog was not opened from a focused control. */
+ returnFocus?: React.RefObject
+}
+
+/** A daily-count refusal waits until midnight UTC; a burst refusal waits seconds. */
+const TODAY_WAIT_S = 15 * 60
+
+const LINK = 'underline underline-offset-[3px] hover:text-fg'
+
+/**
+ * The describe dialog (REQ-027): the visitor writes what the pipeline should do, the
+ * Worker's AI builder answers with steps and a reason for each, and the visitor either
+ * replaces the pipeline or adds them to the end. Either is one reducer action, so one
+ * undo puts the previous pipeline back.
+ */
+export default function GenerateDialog({ onClose, returnFocus }: GenerateDialogProps) {
+ const { state, dispatch } = useTool()
+ const { t } = useT()
+ const [description, setDescription] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [result, setResult] = useState(null)
+ const boxRef = useRef(null)
+ const boxId = useId()
+ const countId = useId()
+ // a reply that lands after the dialog closed must not touch anything
+ const abort = useRef(null)
+ useEffect(() => () => abort.current?.abort(), [])
+
+ const trimmed = description.trim()
+ const hasPipeline = state.steps.length > 0
+
+ const submit = async (e?: React.FormEvent) => {
+ e?.preventDefault()
+ if (!trimmed || busy) return
+ abort.current?.abort()
+ const ctl = new AbortController()
+ abort.current = ctl
+ setBusy(true)
+ setResult(null)
+ try {
+ const r = await generatePipeline(trimmed, { signal: ctl.signal })
+ if (!ctl.signal.aborted) setResult(r)
+ } catch {
+ // aborted: the dialog closed or a newer request replaced this one
+ } finally {
+ if (!ctl.signal.aborted) setBusy(false)
+ }
+ }
+
+ const apply = (mode: 'replace' | 'append') => {
+ if (result?.status !== 'ok') return
+ const steps = result.steps.map(s => cloneWithNewIds(s.step))
+ dispatch(mode === 'replace' ? { type: 'LOAD', steps } : { type: 'INSERT_STEPS', steps })
+ onClose()
+ }
+
+ const errorText = (r: Extract) => {
+ if (r.code === 'ai_rate') {
+ return r.retryAfter && r.retryAfter < TODAY_WAIT_S
+ ? t('generate.error.rateSoon', { seconds: r.retryAfter })
+ : t('generate.error.rateToday')
+ }
+ if (r.code === 'ai_invalid') return t('generate.error.ai_invalid', { max: MAX_DESCRIPTION_CHARS })
+ return t(`generate.error.${r.code}`)
+ }
+ // when the builder cannot help today, point at the ways to build it by hand
+ // REQ-027: whenever generation is unavailable, point to search and the MCP server.
+ // A description that is too long is the visitor's to fix, so it gets no links.
+ const offersFallback = (r: GenerateResult) => r.status === 'error' && r.code !== 'ai_invalid'
+
+ return (
+
+ )
+}
+
+function Notes({ title, notes }: { title: string; notes: string }) {
+ return (
+
+ {title}
+
{notes}
+
+ )
+}
diff --git a/src/app/generate/generate.test.ts b/src/app/generate/generate.test.ts
new file mode 100644
index 0000000..dacded2
--- /dev/null
+++ b/src/app/generate/generate.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it, vi } from 'vitest'
+import { checkGenerated, generatePipeline } from './generate'
+
+const reply = (status: number, body: unknown, headers: Record = {}) =>
+ new Response(typeof body === 'string' ? body : JSON.stringify(body), {
+ status,
+ headers: { 'content-type': typeof body === 'string' ? 'text/html' : 'application/json; charset=utf-8', ...headers },
+ })
+
+const fake = (res: Response | Error) => vi.fn(async () => { if (res instanceof Error) throw res; return res })
+
+describe('generatePipeline', () => {
+ it('sends only the trimmed description, without cookies, to POST /api/generate', async () => {
+ const f = fake(reply(200, { steps: [{ id: 'a', utilityId: 'base64_decode', params: {} }], why: ['decode it'], cached: false }))
+ await generatePipeline(' decode base64 ', { fetchImpl: f })
+ const [url, init] = f.mock.calls[0] as unknown as [string, RequestInit]
+ expect(url).toBe('/api/generate')
+ expect(init.method).toBe('POST')
+ expect(init.credentials).toBe('omit')
+ expect(JSON.parse(String(init.body))).toEqual({ description: 'decode base64' })
+ })
+
+ it('returns the checked steps with their reasons, notes and cache flag', async () => {
+ const f = fake(reply(200, {
+ steps: [{ id: 'a', utilityId: 'base64_decode', params: {} }, { id: 'b', utilityId: 'json_pretty', params: { indent: 4 } }],
+ why: ['decode it', 'indent it'],
+ notes: 'Left out x.',
+ cached: true,
+ }))
+ const r = await generatePipeline('x', { fetchImpl: f })
+ expect(r).toMatchObject({ status: 'ok', notes: 'Left out x.', cached: true })
+ if (r.status !== 'ok') throw new Error('not ok')
+ expect(r.steps.map(s => [('utilityId' in s.step) && s.step.utilityId, s.why])).toEqual([['base64_decode', 'decode it'], ['json_pretty', 'indent it']])
+ })
+
+ it('maps each error code, with its notes and Retry-After', async () => {
+ for (const [status, code] of [[503, 'ai_off'], [503, 'ai_budget'], [400, 'ai_invalid'], [502, 'ai_upstream']] as const) {
+ expect(await generatePipeline('x', { fetchImpl: fake(reply(status, { error: 'e', code })) })).toMatchObject({ status: 'error', code })
+ }
+ expect(await generatePipeline('x', { fetchImpl: fake(reply(429, { error: 'e', code: 'ai_rate' }, { 'retry-after': '43200' })) }))
+ .toMatchObject({ status: 'error', code: 'ai_rate', retryAfter: 43200 })
+ expect(await generatePipeline('x', { fetchImpl: fake(reply(422, { error: 'e', code: 'ai_unusable', notes: 'Left out y.' })) }))
+ .toMatchObject({ status: 'error', code: 'ai_unusable', notes: 'Left out y.' })
+ })
+
+ it('says offline for a network error, a dev server page, a 403 without a code, or a broken body', async () => {
+ for (const res of [new TypeError('failed'), reply(200, ''), reply(403, { error: 'no' }), reply(200, '[1')]) {
+ expect(await generatePipeline('x', { fetchImpl: fake(res) })).toEqual({ status: 'error', code: 'offline' })
+ }
+ })
+
+ it('treats a reply with no step left after checking as unusable', async () => {
+ const f = fake(reply(200, { steps: [{ id: 'a', utilityId: 'custom_js', params: {} }], why: ['run code'], cached: false }))
+ expect(await generatePipeline('x', { fetchImpl: f })).toEqual({ status: 'error', code: 'ai_unusable' })
+ })
+
+ it('lets an abort through instead of reporting it', async () => {
+ const err = Object.assign(new Error('aborted'), { name: 'AbortError' })
+ await expect(generatePipeline('x', { fetchImpl: fake(err) })).rejects.toBe(err)
+ })
+})
+
+describe('checkGenerated', () => {
+ it('drops unknown, code and non-utility steps and keeps each reason beside its own step', () => {
+ const out = checkGenerated(
+ [
+ { id: 'a', utilityId: 'no_such_utility', params: {} },
+ { id: 'b', utilityId: 'custom_js', params: { code: 'x' } },
+ { id: 'c', type: 'branch', branches: [[{ id: 'd', utilityId: 'base64_decode' }]] },
+ 'junk',
+ { id: 'e', utilityId: 'base64_decode', params: {} },
+ ],
+ ['one', 'two', 'three', 'four', 'five'],
+ )
+ expect(out.map(s => s.why)).toEqual(['five'])
+ expect(checkGenerated('nope', [])).toEqual([])
+ })
+})
diff --git a/src/app/generate/generate.ts b/src/app/generate/generate.ts
new file mode 100644
index 0000000..852df97
--- /dev/null
+++ b/src/app/generate/generate.ts
@@ -0,0 +1,76 @@
+/**
+ * Asks the Worker's AI pipeline builder (`POST /api/generate`) for steps that do what a
+ * description says (REQ-027). Only the description is sent: never the input, output or
+ * current pipeline. The reply is checked again here before the editor sees it, the same
+ * way a share link is: steps are sanitized, and only known, non-code utilities are kept.
+ */
+import type { PipelineStep } from '@/types/utility'
+import { sanitizeSteps } from '@/core/serialize'
+import { isUtilityStep } from '@/core/steps'
+import { registry } from '@/app/registry'
+import { CODE_UTILITIES } from '@/app/share/trust'
+import { GENERATE_ERROR_CODES, GENERATE_PATH, MAX_DESCRIPTION_CHARS, type GenerateErrorCode } from '@/lib/generate'
+
+export { MAX_DESCRIPTION_CHARS }
+
+export interface GeneratedStep {
+ step: PipelineStep
+ /** The model's one-line reason for this step ('' when it gave none). */
+ why: string
+}
+
+/** What a request came to. `offline` covers no Worker (a dev server), a network error or a reply that is not the route's. */
+export type GenerateResult =
+ | { status: 'ok'; steps: GeneratedStep[]; notes?: string; cached: boolean }
+ | { status: 'error'; code: GenerateErrorCode | 'offline'; message?: string; notes?: string; retryAfter?: number }
+
+const MAX_WHY = 200
+const MAX_NOTES = 2000
+
+const isObj = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v)
+const text = (v: unknown, max: number) => (typeof v === 'string' ? v.trim().slice(0, max) : '')
+const isCode = (v: unknown): v is GenerateErrorCode => (GENERATE_ERROR_CODES as readonly unknown[]).includes(v)
+
+/** Keeps each reply step that sanitizes to one known, non-code utility step, with its reason. */
+export function checkGenerated(rawSteps: unknown, rawWhy: unknown): GeneratedStep[] {
+ if (!Array.isArray(rawSteps)) return []
+ const why = Array.isArray(rawWhy) ? rawWhy : []
+ const out: GeneratedStep[] = []
+ rawSteps.forEach((raw, i) => {
+ const [step] = sanitizeSteps([raw])
+ if (!step || !isUtilityStep(step) || !registry.has(step.utilityId) || CODE_UTILITIES.has(step.utilityId)) return
+ out.push({ step, why: text(why[i], MAX_WHY) })
+ })
+ return out
+}
+
+export async function generatePipeline(description: string, opts: { signal?: AbortSignal; fetchImpl?: typeof fetch } = {}): Promise {
+ const fetchImpl = opts.fetchImpl ?? fetch
+ let res: Response
+ try {
+ res = await fetchImpl(GENERATE_PATH, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ description: description.trim().slice(0, MAX_DESCRIPTION_CHARS) }),
+ credentials: 'omit',
+ signal: opts.signal,
+ })
+ } catch (e) {
+ if ((e as Error)?.name === 'AbortError') throw e
+ return { status: 'error', code: 'offline' }
+ }
+ // a dev server's fallback page is a 200 HTML page, not an answer
+ if (!(res.headers.get('content-type') ?? '').includes('application/json')) return { status: 'error', code: 'offline' }
+ const body: unknown = await res.json().catch(() => null)
+ if (!isObj(body)) return { status: 'error', code: 'offline' }
+ const notes = text(body.notes, MAX_NOTES) || undefined
+
+ if (res.ok) {
+ const steps = checkGenerated(body.steps, body.why)
+ if (!steps.length) return { status: 'error', code: 'ai_unusable', notes }
+ return { status: 'ok', steps, notes, cached: body.cached === true }
+ }
+ if (!isCode(body.code)) return { status: 'error', code: 'offline' }
+ const retryAfter = Number(res.headers.get('retry-after')) || undefined
+ return { status: 'error', code: body.code, message: text(body.error, 300) || undefined, notes, retryAfter }
+}
diff --git a/src/app/i18n/locales/en.ts b/src/app/i18n/locales/en.ts
index a5d65d7..9efabfa 100644
--- a/src/app/i18n/locales/en.ts
+++ b/src/app/i18n/locales/en.ts
@@ -58,4 +58,37 @@ export const en = {
dark: 'Dark',
toggleAria: 'Theme: {current}. Click for {next}.',
},
+ generate: {
+ button: 'Describe it',
+ buttonTitle: 'Describe a job in words and get a chain of steps to start from',
+ title: 'Describe a pipeline',
+ intro: 'Say what should happen to your text, step by step if you like. You get a chain of utilities to start from, which you can then edit, save to your library and reuse. Only this description is sent, to our server and on to Anthropic’s AI model; your input and output stay in your browser.',
+ privacy: 'What is kept',
+ label: 'What should the pipeline do?',
+ placeholder: 'e.g. decode this base64, pretty-print the JSON, then sort its keys',
+ count: '{count} / {max}',
+ submit: 'Build steps',
+ building: 'Building…',
+ stepsHeading: 'Suggested steps',
+ notesHeading: 'Notes',
+ replace: 'Replace pipeline',
+ use: 'Use these steps',
+ append: 'Add to the end',
+ review: 'Check each step on your own input before relying on the result.',
+ unknownUtility: 'unknown utility',
+ fallback: 'You can still build it yourself:',
+ search: 'search the utilities',
+ or: ', or ',
+ mcp: 'use the MCP server from your own AI agent',
+ error: {
+ ai_off: 'The AI pipeline builder is not switched on right now.',
+ ai_budget: 'The AI pipeline builder has used up today’s budget. It starts again at midnight UTC.',
+ rateSoon: 'Too many requests at once. Try again in {seconds} s.',
+ rateToday: 'That is all the AI pipelines for today. More are available after midnight UTC.',
+ ai_invalid: 'That description could not be used. Describe the job in at most {max} characters.',
+ ai_unusable: 'No usable steps came back for that description. Try naming the formats involved, such as base64, JSON or CSV.',
+ ai_upstream: 'The AI model could not be reached. Try again in a minute.',
+ offline: 'The AI pipeline builder could not be reached. Check your connection and try again.',
+ },
+ },
} as const
diff --git a/src/app/pages/SitePage.test.tsx b/src/app/pages/SitePage.test.tsx
index 829a9c4..d087e21 100644
--- a/src/app/pages/SitePage.test.tsx
+++ b/src/app/pages/SitePage.test.tsx
@@ -21,6 +21,19 @@ describe('SitePage', () => {
expect(document.title).toBe('String Utility Belt')
})
+ it('says what the AI pipeline builder sends, to whom and what is kept, where the describe dialog links', () => {
+ const { container } = render()
+ expect(container.querySelector('#features-that-contact-our-server')?.tagName).toBe('H2')
+ const item = screen.getAllByRole('listitem').find(li => li.textContent?.startsWith('AI pipeline builder.'))!
+ expect(item).toHaveTextContent('only the description you typed')
+ expect(item).toHaveTextContent('Your input, output and current pipeline are not sent')
+ expect(item).toHaveTextContent('Anthropic')
+ expect(item).toHaveTextContent('up to 30 days')
+ expect(item).toHaveTextContent('deleted after 2 days')
+ expect(within(item).getByRole('link', { name: 'its privacy policy' })).toHaveAttribute('href', 'https://www.anthropic.com/legal/privacy')
+ expect(container.textContent).toMatch(/held briefly in memory and is not written to storage; the AI pipeline builder's daily limit keeps only the hash/)
+ })
+
it('lists the sections beside the page, by in-page links, with one of our own tools under them', () => {
const { container } = render()
const toc = screen.getByRole('navigation', { name: 'On this page' })
diff --git a/src/app/pages/content/privacy.md b/src/app/pages/content/privacy.md
index 95b67e7..7c4c69c 100644
--- a/src/app/pages/content/privacy.md
+++ b/src/app/pages/content/privacy.md
@@ -5,7 +5,7 @@ description: How String Utility Belt handles data: your text is processed in you
# Privacy Policy
-*Last updated: 6 November 2026*
+*Last updated: 25 November 2026*
String Utility Belt ("we", "us") runs the website at stringutilitybelt.com and publishes the String Utility Belt browser extension, VS Code extension, command-line tool (`subelt`), MCP server and code library. This policy explains what information is collected when you use the site or these tools, why, and the choices you have. Questions about it can be sent to [contact@stringutilitybelt.com](mailto:contact@stringutilitybelt.com).
@@ -31,10 +31,11 @@ When you create a share link, your pipeline (and your input, if you choose to in
- **Fetching a web address.** When you load input from a URL, your browser first tries to fetch it directly. If the other site does not allow that, the request goes through our fetch proxy, which retrieves the address on your behalf and passes the response back to you. The proxy sees the address you requested and your IP address; it does not keep the content it fetches.
- **The public API.** Developers can send text to our HTTP API to run a pipeline. Requests are processed in memory and are not stored.
+- **AI pipeline builder.** When you use **Describe it** in the editor, your browser sends our server only the description you typed (at most 500 characters). Your input, output and current pipeline are not sent. Our server passes the description to Anthropic's AI model, which suggests the steps; Anthropic handles it under its commercial terms and [its privacy policy](https://www.anthropic.com/legal/privacy). So that a repeated description is answered without asking the model again, we keep a one-way hash of the description, never the text itself, with the suggested steps for up to 30 days. To limit how many pipelines one visitor can build a day, we keep a count under a hash of your IP address made with a secret key and the date, so it differs every day; it cannot be turned back into your address and is deleted after 2 days.
- **Feedback and suggestions.** When you send a message with the feedback form (on the contact page, from **Feedback** at the foot of a page, or after a utility search that finds nothing), your browser sends our server what you wrote, the kind of message you chose, the email address you gave for a reply, if any, and the address of the page you sent it from, without anything after a `?` or `#`. Our server emails exactly that to contact@stringutilitybelt.com through Cloudflare's email service and keeps no copy; your IP address and browser details are not in the email. We keep the email for as long as we need it to answer you or act on your suggestion, use your address only to reply, and delete the message if you ask us to. If the form cannot send a message, it offers to open it in your own email app instead, which then sends it like any other email.
- **Text sent to the site in its web address.** When you share text into the installed app from your device's share menu, or use the browser extension's "Open in String Utility Belt", the text is placed in the page address (`?text=…`), so it is sent to our host along with the request for the page, and may appear in the short-lived operational logs described next. The site then processes it in your browser like any other input. Our analytics never record it: Cloudflare Web Analytics drops everything after a `?` or `#` in the address.
-To protect the fetch proxy, the API, the feedback form and the counts we keep ourselves (see "Cookies and analytics") from abuse, your IP address is used for rate limiting. It is held briefly in memory and is not written to storage. Requests to them, and page requests that carry text in their address, may also appear in short-lived operational logs (for example the requested address, the time and the response status), which we use only to keep the service running and secure, and which are deleted automatically.
+To protect the fetch proxy, the API, the feedback form and the counts we keep ourselves (see "Cookies and analytics") from abuse, your IP address is used for rate limiting. For these it is held briefly in memory and is not written to storage; the AI pipeline builder's daily limit keeps only the hash described above. Requests to them, and page requests that carry text in their address, may also appear in short-lived operational logs (for example the requested address, the time and the response status), which we use only to keep the service running and secure, and which are deleted automatically.
The site is hosted by Cloudflare, which processes every request to deliver the site and protect it from attacks. See [Cloudflare's privacy policy](https://www.cloudflare.com/privacypolicy/).
@@ -85,7 +86,7 @@ The site sets no cookies, and the tools work the same whatever your browser bloc
Depending on where you live (for example under the GDPR or the UK GDPR), you may have the right to access, correct or delete personal data about you, to restrict or object to its processing, and to withdraw consent at any time. Because the site has no accounts and keeps your tool data on your own device, we usually hold no personal data that identifies you, apart from messages you send us. For data Google received through Google Fonts or Google Analytics before October 2026, see [Google's privacy policy](https://policies.google.com/privacy), which also explains how to exercise your rights with Google. You can contact us with any request, and you can complain to your local data protection authority.
-We process data on the basis of our legitimate interest in understanding how the site is used (cookieless page, click, editor-use and extension counts), in running a secure and reliable service (rate limiting and operational logs) and in answering the messages you choose to send us.
+We process data on the basis of our legitimate interest in understanding how the site is used (cookieless page, click, editor-use and extension counts), in running a secure and reliable service (rate limiting and operational logs) in answering the messages you choose to send us and in building the pipelines you ask the AI pipeline builder for.
## Children
diff --git a/src/app/tool/steps/StepsSection.tsx b/src/app/tool/steps/StepsSection.tsx
index 6657768..47d51d9 100644
--- a/src/app/tool/steps/StepsSection.tsx
+++ b/src/app/tool/steps/StepsSection.tsx
@@ -21,6 +21,7 @@ import { seededParams } from '@/app/magic/seed'
import Select from '@/components/Select'
import UtilityPicker from '@/components/UtilityPicker'
import { suggestUtility } from '@/app/feedback/open'
+import GenerateButton from '@/app/generate/GenerateButton'
import EmptyState from '../EmptyState'
import PipelineToolbar from '../PipelineToolbar'
import { StepList } from '../stepListChunk'
@@ -122,6 +123,7 @@ export default function StepsSection() {
onClick={() => dispatch({ type: 'ADD_EACH' })}>
Run on each
+
{next && }
{!hasSteps && (