@emabuild/ai 0.0.0-stage → 0.1.0
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/README.md +194 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +51 -0
- package/dist/cli.js.map +1 -0
- package/dist/compact.d.ts +47 -0
- package/dist/compact.d.ts.map +1 -0
- package/dist/compact.js +157 -0
- package/dist/compact.js.map +1 -0
- package/dist/handler.d.ts +35 -0
- package/dist/handler.d.ts.map +1 -0
- package/dist/handler.js +148 -0
- package/dist/handler.js.map +1 -0
- package/dist/images.d.ts +15 -0
- package/dist/images.d.ts.map +1 -0
- package/dist/images.js +48 -0
- package/dist/images.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/node.d.ts +16 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +117 -0
- package/dist/node.js.map +1 -0
- package/dist/prompt.d.ts +28 -0
- package/dist/prompt.d.ts.map +1 -0
- package/dist/prompt.js +155 -0
- package/dist/prompt.js.map +1 -0
- package/dist/run.d.ts +76 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +349 -0
- package/dist/run.js.map +1 -0
- package/dist/tools.d.ts +27 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +127 -0
- package/dist/tools.js.map +1 -0
- package/dist/usage.d.ts +54 -0
- package/dist/usage.d.ts.map +1 -0
- package/dist/usage.js +98 -0
- package/dist/usage.js.map +1 -0
- package/dist/validate.d.ts +43 -0
- package/dist/validate.d.ts.map +1 -0
- package/dist/validate.js +272 -0
- package/dist/validate.js.map +1 -0
- package/package.json +52 -3
package/README.md
CHANGED
|
@@ -1,3 +1,195 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @emabuild/ai
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Server side of the Emabuild editor's AI connector. It takes an `AIRequest` from the editor (prompt, business context, current design, tool schema), asks Claude to build or edit the template, and streams `AIStreamEvent`s back as NDJSON. The editor applies each `operations` event live on the canvas, so users watch the email being built.
|
|
4
|
+
|
|
5
|
+
- Uses the official `@anthropic-ai/sdk`. The default model is `claude-opus-5-5`.
|
|
6
|
+
- Web Fetch handler (`Request → Response`). It runs on Node 18+, Bun, Deno, Cloudflare Workers, Next.js and Hono. A `node:http` / Express adapter is included.
|
|
7
|
+
- Includes a standalone dev server (`emabuild-ai-server`).
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @emabuild/ai
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick start (dev server)
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
ANTHROPIC_API_KEY=sk-ant-... npx emabuild-ai-server
|
|
17
|
+
# → listening on http://127.0.0.1:8787/ai
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Point the editor at it:
|
|
21
|
+
|
|
22
|
+
```js
|
|
23
|
+
editor.init({ ai: { endpoint: 'http://127.0.0.1:8787/ai' } });
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
| Env var | Default | Description |
|
|
27
|
+
|---|---|---|
|
|
28
|
+
| `ANTHROPIC_API_KEY` | none | Anthropic API key. If it is unset, the SDK's credential chain is used (`ANTHROPIC_AUTH_TOKEN`, `ant auth login` profiles). |
|
|
29
|
+
| `EMABUILD_AI_MODEL` | `claude-opus-5-5` | Model id |
|
|
30
|
+
| `EMABUILD_AI_EFFORT` | `medium` | `low` \| `medium` \| `high` \| `xhigh` \| `max` |
|
|
31
|
+
| `EMABUILD_AI_CORS` | `*` | Allowed origin(s), comma separated, or `false` |
|
|
32
|
+
| `PORT` | `8787` | Port |
|
|
33
|
+
| `HOST` | `127.0.0.1` | Bind address (`0.0.0.0` to expose it) |
|
|
34
|
+
|
|
35
|
+
Routes: `POST /ai` (plus `OPTIONS` preflight) and `GET /health`.
|
|
36
|
+
|
|
37
|
+
## Protocol
|
|
38
|
+
|
|
39
|
+
**Request:** `POST` with a JSON `AIRequest` (from `@emabuild/types`):
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
interface AIRequest {
|
|
43
|
+
action: 'generate' | 'edit' | 'rewrite' | 'shorten' | 'translate' | string;
|
|
44
|
+
prompt: string;
|
|
45
|
+
context: AIContext; // brand, audience, tone, language, goal, data…
|
|
46
|
+
design: EmailDesign; // current design JSON
|
|
47
|
+
selection?: EditorSelection & { content?: DesignContent } | null;
|
|
48
|
+
schema: DesignSchema; // every tool, its property keys, widgets, defaults, options
|
|
49
|
+
mergeTags?: MergeTagGroup[];
|
|
50
|
+
locale?: string;
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**Response:** `200`, `Content-Type: application/x-ndjson`. Each line is one `AIStreamEvent`, flushed as soon as it is available:
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
{"type":"status","message":"Designing your email…"}
|
|
58
|
+
{"type":"message","text":"I'll build a welcome email with a hero, three benefits and a CTA."}
|
|
59
|
+
{"type":"operations","operations":[{"op":"addRow","cells":[1],"ref":"hero","columns":[{"contents":[{"type":"heading","values":{"text":"Welcome!"}}]}]}]}
|
|
60
|
+
{"type":"operations","operations":[{"op":"addContent","columnId":"hero:0","type":"button","values":{"text":"Get started"}}]}
|
|
61
|
+
{"type":"done","summary":"Created a welcome email with a hero, benefits and a call to action."}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
| Event | Meaning |
|
|
65
|
+
|---|---|
|
|
66
|
+
| `status` | Short progress line, including the model's progress updates between tool calls |
|
|
67
|
+
| `message` | Text the assistant wrote for the user |
|
|
68
|
+
| `operations` | `DesignOperation[]`. Apply each batch as one undo step. |
|
|
69
|
+
| `done` | Run finished, with an optional summary |
|
|
70
|
+
| `error` | Run failed. The stream ends after it. |
|
|
71
|
+
|
|
72
|
+
Errors before streaming starts return JSON `{ "error": "..." }`: `400` for an invalid body, `401` when `authorize` rejects the request, `405` for a wrong method, `413` for a body that is too large, and `500` when `transformRequest` fails.
|
|
73
|
+
|
|
74
|
+
### Operation semantics
|
|
75
|
+
|
|
76
|
+
- Existing nodes are addressed by their real ids from `request.design`.
|
|
77
|
+
- The client assigns ids to new nodes. The model sets `ref` on `addRow` / `addContent`. Later operations can then target `rowId: "<ref>"`, `columnId: "<rowRef>:<columnIndex>"` (0-based) or `contentId: "<ref>"`. Refs last for the whole run.
|
|
78
|
+
- `values` only contains the keys to change. The client fills defaults from the tool schema.
|
|
79
|
+
- The server validates each batch: shape, known ids/refs, tool names. An invalid batch is never streamed. Claude receives the errors and sends a corrected batch.
|
|
80
|
+
|
|
81
|
+
## Usage
|
|
82
|
+
|
|
83
|
+
### Express / node:http
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
import express from 'express';
|
|
87
|
+
import { createAIHandler, toNodeHandler } from '@emabuild/ai';
|
|
88
|
+
|
|
89
|
+
const app = express();
|
|
90
|
+
const ai = toNodeHandler(
|
|
91
|
+
createAIHandler({
|
|
92
|
+
cors: ['https://app.example.com'],
|
|
93
|
+
authorize: (req) => req.headers.get('authorization') === `Bearer ${process.env.EDITOR_TOKEN}`,
|
|
94
|
+
}),
|
|
95
|
+
);
|
|
96
|
+
app.all('/ai', ai); // works with or without express.json()
|
|
97
|
+
app.listen(8787);
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Plain `node:http`: `http.createServer(toNodeHandler(createAIHandler())).listen(8787)`.
|
|
101
|
+
|
|
102
|
+
> Disable response compression on this route (e.g. `compression({ filter: () => false })`). Compression buffers the stream.
|
|
103
|
+
|
|
104
|
+
### Next.js (App Router)
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
// app/api/ai/route.ts
|
|
108
|
+
import { createAIHandler } from '@emabuild/ai';
|
|
109
|
+
|
|
110
|
+
export const runtime = 'nodejs';
|
|
111
|
+
export const dynamic = 'force-dynamic';
|
|
112
|
+
|
|
113
|
+
const handler = createAIHandler({
|
|
114
|
+
transformRequest: async (aiRequest, req) => ({
|
|
115
|
+
...aiRequest,
|
|
116
|
+
context: { ...aiRequest.context, brand: await loadBrand(req) },
|
|
117
|
+
}),
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
export const POST = handler;
|
|
121
|
+
export const OPTIONS = handler;
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Hono / Bun / Deno / Cloudflare Workers
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import { Hono } from 'hono';
|
|
128
|
+
import { createAIHandler } from '@emabuild/ai';
|
|
129
|
+
|
|
130
|
+
const ai = createAIHandler({ cors: '*' }); // reads ANTHROPIC_API_KEY; on Workers pass apiKey from env
|
|
131
|
+
const app = new Hono();
|
|
132
|
+
app.on(['POST', 'OPTIONS'], '/ai', (c) => ai(c.req.raw));
|
|
133
|
+
export default app;
|
|
134
|
+
|
|
135
|
+
// Bun: Bun.serve({ port: 8787, fetch: ai });
|
|
136
|
+
// Deno: Deno.serve({ port: 8787 }, ai);
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Using the runner directly
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
import { runAI } from '@emabuild/ai';
|
|
143
|
+
|
|
144
|
+
for await (const event of runAI(aiRequest, { signal })) {
|
|
145
|
+
if (event.type === 'operations') applyOperations(design, event.operations);
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Options
|
|
150
|
+
|
|
151
|
+
`createAIHandler(options)` accepts every `runAI` option, plus the handler options below.
|
|
152
|
+
|
|
153
|
+
| Option | Description |
|
|
154
|
+
|---|---|
|
|
155
|
+
| `client` | Pre-configured `Anthropic` client. Use it for Bedrock/Vertex/Foundry clients, custom `baseURL` or retries. |
|
|
156
|
+
| `apiKey` | API key. If omitted, the SDK resolves credentials itself. |
|
|
157
|
+
| `model` | Default `claude-opus-5-5` |
|
|
158
|
+
| `effort` | `output_config.effort`, default `medium`. `null` omits it. |
|
|
159
|
+
| `maxTokens` | Output cap per model response. Default `64000` (responses are streamed). |
|
|
160
|
+
| `maxTurns` | Maximum number of model round-trips. Default `30`. |
|
|
161
|
+
| `systemPrompt` | Extra instructions appended to the built-in system prompt |
|
|
162
|
+
| `fallbacks` | Server-side refusal fallbacks (`fallbacks: "default"`). On by default for supported models. Set to `false` on Bedrock/Vertex/Foundry or behind proxies. |
|
|
163
|
+
| `reportUsage` | Send a `usage` event (tokens and estimated cost) right before `done` / `error`. Default `true`; set `false` to keep usage on the server. |
|
|
164
|
+
| `pricing` | Prices in USD per million tokens, merged over the built-in Claude API list prices and keyed by model id: `{ 'my-model': { input, output, cacheRead?, cacheWrite?, cacheWrite1h? } }` |
|
|
165
|
+
| `progressUpdates` | Forward the model's progress notes as `status` events (`thinking.display: "updates"`). On by default for supported models. |
|
|
166
|
+
| `cors` | `"*"`, an origin, a list of origins, or `false`. The default is `false`, which allows same-origin requests only. |
|
|
167
|
+
| `authorize(req)` | Return `false` to reject the request with `401` |
|
|
168
|
+
| `transformRequest(aiRequest, req)` | Inject server-side context, such as tenant brand, products or a forced language |
|
|
169
|
+
| `maxBodyBytes` | Default 5 MB |
|
|
170
|
+
| `run` | Replace the runner (tests or custom providers) |
|
|
171
|
+
| `onError(err)` | Logging hook |
|
|
172
|
+
|
|
173
|
+
### Cost and caching
|
|
174
|
+
|
|
175
|
+
The static system prompt and the schema description are marked for prompt caching, together with top-level automatic caching of the conversation. Repeated requests from the same editor configuration therefore read most of their prefix from the cache. The design is compacted before it is sent: `_meta`, empty values and values equal to the tool defaults are removed, and large data URIs are replaced with a placeholder.
|
|
176
|
+
|
|
177
|
+
### Usage per run
|
|
178
|
+
|
|
179
|
+
Each run ends with one `usage` event, sent right before `done` (or `error`):
|
|
180
|
+
|
|
181
|
+
```json
|
|
182
|
+
{"type":"usage","usage":{"model":"claude-opus-5-5","requests":3,"inputTokens":2140,"outputTokens":1890,"cacheReadTokens":18400,"cacheWriteTokens":9200,"costUsd":0.096}}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
All model round-trips of the run are added up. `costUsd` is an estimate at Claude API list prices
|
|
186
|
+
(`MODEL_PRICING`). It is absent when a model has no known price. Partner platforms, fast mode, batch
|
|
187
|
+
discounts and long-prompt tiers bill differently, so pass `pricing` when you need your own rates.
|
|
188
|
+
`UsageMeter` and `pricingFor` are exported for your own logging or billing.
|
|
189
|
+
|
|
190
|
+
In the editor the event becomes `editor.ai.usage`, the `ai:usage` DOM event and `usage` on the
|
|
191
|
+
`ai:done` result. `ai.showUsage: true` shows it in the AI tab.
|
|
192
|
+
|
|
193
|
+
## License
|
|
194
|
+
|
|
195
|
+
MIT
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Standalone development server for the Emabuild AI connector.
|
|
4
|
+
*
|
|
5
|
+
* ANTHROPIC_API_KEY=... npx emabuild-ai-server
|
|
6
|
+
*
|
|
7
|
+
* Env: PORT (default 8787), HOST (default 127.0.0.1; use 0.0.0.0 to expose it),
|
|
8
|
+
* ANTHROPIC_API_KEY, EMABUILD_AI_MODEL, EMABUILD_AI_EFFORT, EMABUILD_AI_CORS (default "*"),
|
|
9
|
+
* EMABUILD_AI_IMAGES ("off" disables the free-image search tool).
|
|
10
|
+
*/
|
|
11
|
+
import { createServer } from 'node:http';
|
|
12
|
+
import { createAIHandler } from './handler.js';
|
|
13
|
+
import { toNodeHandler } from '@emabuild/shared/node';
|
|
14
|
+
import { DEFAULT_MODEL } from './run.js';
|
|
15
|
+
const port = Number(process.env.PORT ?? 8787);
|
|
16
|
+
const host = process.env.HOST ?? '127.0.0.1';
|
|
17
|
+
const model = process.env.EMABUILD_AI_MODEL || DEFAULT_MODEL;
|
|
18
|
+
const effort = (process.env.EMABUILD_AI_EFFORT || undefined);
|
|
19
|
+
const corsEnv = process.env.EMABUILD_AI_CORS ?? '*';
|
|
20
|
+
const cors = corsEnv === 'false' ? false : corsEnv.includes(',') ? corsEnv.split(',').map((s) => s.trim()) : corsEnv;
|
|
21
|
+
if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) {
|
|
22
|
+
console.warn('[emabuild-ai] ANTHROPIC_API_KEY is not set; falling back to the SDK credential chain (e.g. `ant auth login`).');
|
|
23
|
+
}
|
|
24
|
+
const ai = toNodeHandler(createAIHandler({
|
|
25
|
+
model,
|
|
26
|
+
effort,
|
|
27
|
+
cors,
|
|
28
|
+
...(process.env.EMABUILD_AI_IMAGES === 'off' ? { imageSearch: false } : {}),
|
|
29
|
+
onError: (err) => console.error('[emabuild-ai]', err),
|
|
30
|
+
}));
|
|
31
|
+
const server = createServer((req, res) => {
|
|
32
|
+
const path = (req.url ?? '/').split('?')[0];
|
|
33
|
+
if (path === '/ai') {
|
|
34
|
+
void ai(req, res);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (path === '/health' && req.method === 'GET') {
|
|
38
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
39
|
+
res.end(JSON.stringify({ ok: true, model }));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
res.writeHead(404, { 'content-type': 'application/json' });
|
|
43
|
+
res.end(JSON.stringify({ error: 'Not found' }));
|
|
44
|
+
});
|
|
45
|
+
server.listen(port, host, () => {
|
|
46
|
+
console.log(`[emabuild-ai] listening on http://${host}:${port}/ai (model: ${model})`);
|
|
47
|
+
});
|
|
48
|
+
const shutdown = () => server.close(() => process.exit(0));
|
|
49
|
+
process.on('SIGINT', shutdown);
|
|
50
|
+
process.on('SIGTERM', shutdown);
|
|
51
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
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AACxF,CAAC,CAAC,CAAC;AAEH,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3D,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;AAC/B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { DesignContent, DesignSchema, EmailDesign } from '@emabuild/types';
|
|
2
|
+
type Defaults = Record<string, unknown>;
|
|
3
|
+
/**
|
|
4
|
+
* Drops noise from a values object: `_meta`, empty values and values equal to
|
|
5
|
+
* the schema default. Nested objects are pruned recursively.
|
|
6
|
+
*/
|
|
7
|
+
export declare function pruneValues(values: Record<string, unknown> | undefined, defaults?: Defaults): Record<string, unknown>;
|
|
8
|
+
/** Shape of the design as shown to the model */
|
|
9
|
+
export interface CompactDesign {
|
|
10
|
+
body: {
|
|
11
|
+
values: Record<string, unknown>;
|
|
12
|
+
rows: CompactRow[];
|
|
13
|
+
headers?: CompactRow[];
|
|
14
|
+
footers?: CompactRow[];
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
interface CompactRow {
|
|
18
|
+
id: string;
|
|
19
|
+
cells: number[];
|
|
20
|
+
values?: Record<string, unknown>;
|
|
21
|
+
columns: Array<{
|
|
22
|
+
id: string;
|
|
23
|
+
values?: Record<string, unknown>;
|
|
24
|
+
contents: CompactContent[];
|
|
25
|
+
}>;
|
|
26
|
+
}
|
|
27
|
+
export interface CompactContent {
|
|
28
|
+
id: string;
|
|
29
|
+
type: string;
|
|
30
|
+
values?: Record<string, unknown>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Returns a token-efficient copy of a design: strips `_meta`, empty values and
|
|
34
|
+
* values equal to the schema defaults, and drops `counters`.
|
|
35
|
+
*/
|
|
36
|
+
export declare function compactDesign(design: EmailDesign, schema?: DesignSchema): CompactDesign;
|
|
37
|
+
/** Token-efficient copy of a single content block (see {@link compactDesign}) */
|
|
38
|
+
export declare function compactContent(content: DesignContent, schema?: DesignSchema): CompactContent;
|
|
39
|
+
/** True when the design has no rows in any section */
|
|
40
|
+
export declare function isDesignEmpty(design: EmailDesign | undefined): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Renders a DesignSchema as compact plain text for the system prompt: one
|
|
43
|
+
* section per tool, one line per property (key, widget, options, default).
|
|
44
|
+
*/
|
|
45
|
+
export declare function describeSchema(schema: DesignSchema | undefined): string;
|
|
46
|
+
export {};
|
|
47
|
+
//# sourceMappingURL=compact.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compact.d.ts","sourceRoot":"","sources":["../src/compact.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,aAAa,EAEb,YAAY,EACZ,WAAW,EAEZ,MAAM,iBAAiB,CAAC;AAOzB,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAoCxC;;;GAGG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAAE,QAAQ,GAAE,QAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAWzH;AAQD,gDAAgD;AAChD,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE;QACJ,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAChC,IAAI,EAAE,UAAU,EAAE,CAAC;QACnB,OAAO,CAAC,EAAE,UAAU,EAAE,CAAC;QACvB,OAAO,CAAC,EAAE,UAAU,EAAE,CAAC;KACxB,CAAC;CACH;AAED,UAAU,UAAU;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,OAAO,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAAC,QAAQ,EAAE,cAAc,EAAE,CAAA;KAAE,CAAC,CAAC;CAC9F;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAMD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,EAAE,YAAY,GAAG,aAAa,CAwBvF;AAED,iFAAiF;AACjF,wBAAgB,cAAc,CAAC,OAAO,EAAE,aAAa,EAAE,MAAM,CAAC,EAAE,YAAY,GAAG,cAAc,CAG5F;AAED,sDAAsD;AACtD,wBAAgB,aAAa,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,OAAO,CAGtE;AA4BD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,GAAG,MAAM,CAcvE"}
|
package/dist/compact.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/** Longest default value (serialized) printed in the schema description */
|
|
2
|
+
const MAX_DEFAULT_CHARS = 160;
|
|
3
|
+
/** Data URIs above this length are replaced with a placeholder in prompts */
|
|
4
|
+
const MAX_DATA_URI_CHARS = 200;
|
|
5
|
+
function isPlainObject(value) {
|
|
6
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
7
|
+
}
|
|
8
|
+
function deepEqual(a, b) {
|
|
9
|
+
if (a === b)
|
|
10
|
+
return true;
|
|
11
|
+
if (typeof a !== typeof b || a === null || b === null)
|
|
12
|
+
return false;
|
|
13
|
+
if (Array.isArray(a)) {
|
|
14
|
+
return Array.isArray(b) && a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
|
|
15
|
+
}
|
|
16
|
+
if (isPlainObject(a) && isPlainObject(b)) {
|
|
17
|
+
const ka = Object.keys(a);
|
|
18
|
+
const kb = Object.keys(b);
|
|
19
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
function isEmpty(value) {
|
|
24
|
+
if (value === null || value === undefined || value === '')
|
|
25
|
+
return true;
|
|
26
|
+
if (Array.isArray(value))
|
|
27
|
+
return value.length === 0;
|
|
28
|
+
if (isPlainObject(value))
|
|
29
|
+
return Object.keys(value).length === 0;
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
function pruneValue(value) {
|
|
33
|
+
if (typeof value === 'string') {
|
|
34
|
+
return value.startsWith('data:') && value.length > MAX_DATA_URI_CHARS ? '[data-uri omitted]' : value;
|
|
35
|
+
}
|
|
36
|
+
if (Array.isArray(value))
|
|
37
|
+
return value.map(pruneValue);
|
|
38
|
+
if (isPlainObject(value))
|
|
39
|
+
return pruneValues(value);
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Drops noise from a values object: `_meta`, empty values and values equal to
|
|
44
|
+
* the schema default. Nested objects are pruned recursively.
|
|
45
|
+
*/
|
|
46
|
+
export function pruneValues(values, defaults = {}) {
|
|
47
|
+
const out = {};
|
|
48
|
+
if (!values)
|
|
49
|
+
return out;
|
|
50
|
+
for (const [key, raw] of Object.entries(values)) {
|
|
51
|
+
if (key === '_meta')
|
|
52
|
+
continue;
|
|
53
|
+
if (key in defaults && deepEqual(raw, defaults[key]))
|
|
54
|
+
continue;
|
|
55
|
+
const value = pruneValue(raw);
|
|
56
|
+
if (isEmpty(value))
|
|
57
|
+
continue;
|
|
58
|
+
out[key] = value;
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
function defaultsOf(props) {
|
|
63
|
+
const out = {};
|
|
64
|
+
for (const p of props ?? [])
|
|
65
|
+
out[p.key] = p.defaultValue;
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
function withValues(base, values) {
|
|
69
|
+
return Object.keys(values).length > 0 ? { ...base, values } : base;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Returns a token-efficient copy of a design: strips `_meta`, empty values and
|
|
73
|
+
* values equal to the schema defaults, and drops `counters`.
|
|
74
|
+
*/
|
|
75
|
+
export function compactDesign(design, schema) {
|
|
76
|
+
const toolDefaults = new Map();
|
|
77
|
+
for (const tool of schema?.tools ?? [])
|
|
78
|
+
toolDefaults.set(tool.name, defaultsOf(tool.properties));
|
|
79
|
+
const rowDefaults = defaultsOf(schema?.row);
|
|
80
|
+
const columnDefaults = defaultsOf(schema?.column);
|
|
81
|
+
const bodyDefaults = defaultsOf(schema?.body);
|
|
82
|
+
const content = (c) => withValues({ id: c.id, type: c.type }, pruneValues(c.values, toolDefaults.get(c.type)));
|
|
83
|
+
const column = (col) => withValues({ id: col.id, contents: (col.contents ?? []).map(content) }, pruneValues(col.values, columnDefaults));
|
|
84
|
+
const row = (r) => withValues({ id: r.id, cells: r.cells, columns: (r.columns ?? []).map(column) }, pruneValues(r.values, rowDefaults));
|
|
85
|
+
const body = design?.body;
|
|
86
|
+
const out = {
|
|
87
|
+
body: {
|
|
88
|
+
values: pruneValues(body?.values, bodyDefaults),
|
|
89
|
+
rows: (body?.rows ?? []).map(row),
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
if (body?.headers?.length)
|
|
93
|
+
out.body.headers = body.headers.map(row);
|
|
94
|
+
if (body?.footers?.length)
|
|
95
|
+
out.body.footers = body.footers.map(row);
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
/** Token-efficient copy of a single content block (see {@link compactDesign}) */
|
|
99
|
+
export function compactContent(content, schema) {
|
|
100
|
+
const tool = schema?.tools?.find((t) => t.name === content.type);
|
|
101
|
+
return withValues({ id: content.id, type: content.type }, pruneValues(content.values, defaultsOf(tool?.properties)));
|
|
102
|
+
}
|
|
103
|
+
/** True when the design has no rows in any section */
|
|
104
|
+
export function isDesignEmpty(design) {
|
|
105
|
+
const body = design?.body;
|
|
106
|
+
return !body || ((body.rows?.length ?? 0) === 0 && (body.headers?.length ?? 0) === 0 && (body.footers?.length ?? 0) === 0);
|
|
107
|
+
}
|
|
108
|
+
function formatDefault(value) {
|
|
109
|
+
if (value === undefined)
|
|
110
|
+
return '';
|
|
111
|
+
let s;
|
|
112
|
+
try {
|
|
113
|
+
s = JSON.stringify(value);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return '';
|
|
117
|
+
}
|
|
118
|
+
if (s === undefined)
|
|
119
|
+
return '';
|
|
120
|
+
return s.length > MAX_DEFAULT_CHARS ? `${s.slice(0, MAX_DEFAULT_CHARS)}…` : s;
|
|
121
|
+
}
|
|
122
|
+
function describeProps(props) {
|
|
123
|
+
const lines = [];
|
|
124
|
+
for (const p of props ?? []) {
|
|
125
|
+
if (p.key === '_meta')
|
|
126
|
+
continue;
|
|
127
|
+
let line = `- ${p.key} [${p.widget}]`;
|
|
128
|
+
if (p.label && p.label !== p.key)
|
|
129
|
+
line += ` "${p.label}"`;
|
|
130
|
+
if (p.options?.length)
|
|
131
|
+
line += ` options: ${p.options.map((o) => JSON.stringify(o.value)).join(' | ')}`;
|
|
132
|
+
const def = formatDefault(p.defaultValue);
|
|
133
|
+
if (def)
|
|
134
|
+
line += ` default: ${def}`;
|
|
135
|
+
lines.push(line);
|
|
136
|
+
}
|
|
137
|
+
return lines;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Renders a DesignSchema as compact plain text for the system prompt: one
|
|
141
|
+
* section per tool, one line per property (key, widget, options, default).
|
|
142
|
+
*/
|
|
143
|
+
export function describeSchema(schema) {
|
|
144
|
+
if (!schema)
|
|
145
|
+
return 'No schema provided.';
|
|
146
|
+
const parts = [];
|
|
147
|
+
parts.push('## Body properties (updateBody)', ...describeProps(schema.body), '');
|
|
148
|
+
parts.push('## Row properties (addRow.values / updateRow)', ...describeProps(schema.row), '');
|
|
149
|
+
parts.push('## Column properties (columns[].values / updateColumn)', ...describeProps(schema.column), '');
|
|
150
|
+
parts.push('## Content tools (addContent.type / updateContent)');
|
|
151
|
+
for (const tool of schema.tools ?? []) {
|
|
152
|
+
const header = `### ${tool.name}${tool.label && tool.label !== tool.name ? ` (${tool.label})` : ''}${tool.category ? ` — ${tool.category}` : ''}`;
|
|
153
|
+
parts.push(header, ...describeProps(tool.properties), '');
|
|
154
|
+
}
|
|
155
|
+
return parts.join('\n').trim();
|
|
156
|
+
}
|
|
157
|
+
//# sourceMappingURL=compact.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compact.js","sourceRoot":"","sources":["../src/compact.ts"],"names":[],"mappings":"AASA,2EAA2E;AAC3E,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,6EAA6E;AAC7E,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAI/B,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,SAAS,CAAC,CAAU,EAAE,CAAU;IACvC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IACpE,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,CAA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CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC;IAC5D,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AACjC,CAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { AIRequest, AIStreamEvent } from '@emabuild/types';
|
|
2
|
+
import { type RunAIOptions } from './run.js';
|
|
3
|
+
/** NDJSON content type used by the streaming protocol */
|
|
4
|
+
export declare const NDJSON_CONTENT_TYPE = "application/x-ndjson; charset=utf-8";
|
|
5
|
+
/** Options for {@link createAIHandler} */
|
|
6
|
+
export interface AIHandlerOptions extends Omit<RunAIOptions, 'signal'> {
|
|
7
|
+
/**
|
|
8
|
+
* Allowed CORS origins: "*" for any, a single origin, a list of origins, or
|
|
9
|
+
* false (default) to send no CORS headers (same-origin only).
|
|
10
|
+
*/
|
|
11
|
+
cors?: string | string[] | false;
|
|
12
|
+
/** Return false to reject the request with 401 (e.g. check a session or bearer token) */
|
|
13
|
+
authorize?: (req: Request) => boolean | Promise<boolean>;
|
|
14
|
+
/** Adjust the request before running it, e.g. inject tenant brand data server-side */
|
|
15
|
+
transformRequest?: (request: AIRequest, req: Request) => AIRequest | Promise<AIRequest>;
|
|
16
|
+
/** Maximum accepted body size in bytes (default 5 MB) */
|
|
17
|
+
maxBodyBytes?: number;
|
|
18
|
+
/** Replace the runner (defaults to {@link runAI}); useful for tests or custom providers */
|
|
19
|
+
run?: (request: AIRequest, options: RunAIOptions) => AsyncIterable<AIStreamEvent>;
|
|
20
|
+
/** Called with unexpected errors (logging hook) */
|
|
21
|
+
onError?: (error: unknown) => void;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Checks that a parsed body looks like an AIRequest. Returns an error message
|
|
25
|
+
* or null when valid.
|
|
26
|
+
*/
|
|
27
|
+
export declare function validateAIRequest(body: unknown): string | null;
|
|
28
|
+
/**
|
|
29
|
+
* Creates a Web Fetch handler `(req: Request) => Promise<Response>` that
|
|
30
|
+
* speaks the editor's AI protocol: POST an AIRequest as JSON, receive an
|
|
31
|
+
* NDJSON stream of AIStreamEvents. Works in Node 18+, Bun, Deno, Cloudflare
|
|
32
|
+
* Workers, Next.js route handlers, Hono, etc.
|
|
33
|
+
*/
|
|
34
|
+
export declare function createAIHandler(options?: AIHandlerOptions): (req: Request) => Promise<Response>;
|
|
35
|
+
//# sourceMappingURL=handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,EAAS,KAAK,YAAY,EAAE,MAAM,UAAU,CAAC;AAGpD,yDAAyD;AACzD,eAAO,MAAM,mBAAmB,wCAAwC,CAAC;AAEzE,0CAA0C;AAC1C,MAAM,WAAW,gBAAiB,SAAQ,IAAI,CAAC,YAAY,EAAE,QAAQ,CAAC;IACpE;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,KAAK,CAAC;IACjC,yFAAyF;IACzF,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACzD,sFAAsF;IACtF,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,OAAO,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;IACxF,yDAAyD;IACzD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,2FAA2F;IAC3F,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,YAAY,KAAK,aAAa,CAAC,aAAa,CAAC,CAAC;IAClF,mDAAmD;IACnD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CAC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