@emabuild/ai 0.1.0 → 0.8.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 +122 -11
- package/dist/cli.js +24 -6
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +9 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -2
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +26 -0
- package/dist/loop.d.ts.map +1 -0
- package/dist/loop.js +215 -0
- package/dist/loop.js.map +1 -0
- package/dist/providers/anthropic.d.ts +58 -0
- package/dist/providers/anthropic.d.ts.map +1 -0
- package/dist/providers/anthropic.js +217 -0
- package/dist/providers/anthropic.js.map +1 -0
- package/dist/providers/errors.d.ts +12 -0
- package/dist/providers/errors.d.ts.map +1 -0
- package/dist/providers/errors.js +39 -0
- package/dist/providers/errors.js.map +1 -0
- package/dist/providers/model-call.d.ts +17 -0
- package/dist/providers/model-call.d.ts.map +1 -0
- package/dist/providers/model-call.js +65 -0
- package/dist/providers/model-call.js.map +1 -0
- package/dist/providers/openai-format.d.ts +89 -0
- package/dist/providers/openai-format.d.ts.map +1 -0
- package/dist/providers/openai-format.js +107 -0
- package/dist/providers/openai-format.js.map +1 -0
- package/dist/providers/types.d.ts +168 -0
- package/dist/providers/types.d.ts.map +1 -0
- package/dist/providers/types.js +22 -0
- package/dist/providers/types.js.map +1 -0
- package/dist/run.d.ts +38 -37
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +44 -323
- package/dist/run.js.map +1 -1
- package/dist/usage.d.ts +7 -1
- package/dist/usage.d.ts.map +1 -1
- package/dist/usage.js +35 -6
- package/dist/usage.js.map +1 -1
- package/package.json +17 -7
package/README.md
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
# @emabuild/ai
|
|
2
2
|
|
|
3
|
-
Server side of the Emabuild editor's AI connector. It takes an `AIRequest` from the editor (prompt, business context, current design, tool schema),
|
|
3
|
+
Server side of the Emabuild editor's AI connector. It takes an `AIRequest` from the editor (prompt, business context, current design, tool schema), runs the editing flow with a model, 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
4
|
|
|
5
|
-
-
|
|
5
|
+
- **The library runs the flow; you choose the model.** Prompts, tools, validation of every batch, corrections sent back to the model, image search, turn limit and the editor events are handled here. The model answering each turn is Claude by default, or anything you plug in with `callModel` (OpenAI, Azure OpenAI, Cerebras, Groq, a local server…).
|
|
6
|
+
- The built-in Claude adapter uses `@anthropic-ai/sdk`, an **optional** peer dependency: install it only if you use Claude (`npm install @anthropic-ai/sdk`). The default model is `claude-opus-5-5`.
|
|
6
7
|
- 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
8
|
- Includes a standalone dev server (`emabuild-ai-server`).
|
|
8
9
|
|
|
@@ -13,7 +14,7 @@ pnpm add @emabuild/ai
|
|
|
13
14
|
## Quick start (dev server)
|
|
14
15
|
|
|
15
16
|
```bash
|
|
16
|
-
ANTHROPIC_API_KEY
|
|
17
|
+
ANTHROPIC_API_KEY=<your-key> npx emabuild-ai-server
|
|
17
18
|
# → listening on http://127.0.0.1:8787/ai
|
|
18
19
|
```
|
|
19
20
|
|
|
@@ -25,8 +26,11 @@ editor.init({ ai: { endpoint: 'http://127.0.0.1:8787/ai' } });
|
|
|
25
26
|
|
|
26
27
|
| Env var | Default | Description |
|
|
27
28
|
|---|---|---|
|
|
29
|
+
| `EMABUILD_AI_PROVIDER` | `anthropic` | `anthropic`, or `openai` for any OpenAI-compatible server |
|
|
28
30
|
| `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
|
-
| `
|
|
31
|
+
| `OPENAI_API_KEY` / `EMABUILD_AI_API_KEY` | none | Key for `EMABUILD_AI_PROVIDER=openai` |
|
|
32
|
+
| `EMABUILD_AI_BASE_URL` | OpenAI | Base URL of an OpenAI-compatible server, e.g. `https://api.cerebras.ai/v1` |
|
|
33
|
+
| `EMABUILD_AI_MODEL` | `claude-opus-5-5` (`gpt-4o` with openai) | Model id |
|
|
30
34
|
| `EMABUILD_AI_EFFORT` | `medium` | `low` \| `medium` \| `high` \| `xhigh` \| `max` |
|
|
31
35
|
| `EMABUILD_AI_CORS` | `*` | Allowed origin(s), comma separated, or `false` |
|
|
32
36
|
| `PORT` | `8787` | Port |
|
|
@@ -34,6 +38,95 @@ editor.init({ ai: { endpoint: 'http://127.0.0.1:8787/ai' } });
|
|
|
34
38
|
|
|
35
39
|
Routes: `POST /ai` (plus `OPTIONS` preflight) and `GET /health`.
|
|
36
40
|
|
|
41
|
+
## Choosing the model
|
|
42
|
+
|
|
43
|
+
Each run is a conversation: the library sends out the prompt, your model answers, the library validates the answer, applies it in the editor and sends the next turn (with the errors to fix, if any), until the model calls `finish`.
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
editor ──AIRequest──▶ flow (this library) ──ModelRequest──▶ your callModel ──▶ any model
|
|
47
|
+
editor ◀──events──── flow ◀──────────────── ModelResponse ◀──────────────────┘
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### `callModel`: any model, your code
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
createAIHandler({
|
|
54
|
+
callModel: async ({ system, messages, tools, maxTokens, effort, signal }) => {
|
|
55
|
+
// call any model here…
|
|
56
|
+
return { text, toolCalls, stop, usage, model };
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
| `ModelRequest` field | Description |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `system` | System prompt (stable parts first: good for providers that cache prefixes) |
|
|
64
|
+
| `messages` | Conversation in a neutral format: `{ role: 'user', content }`, `{ role: 'assistant', content, toolCalls? }`, `{ role: 'tool', toolCallId, content, isError? }` |
|
|
65
|
+
| `tools` | `{ name, description, inputSchema }` (JSON Schema; send it non-strict) |
|
|
66
|
+
| `maxTokens`, `effort` | What the caller asked for; map them where your model supports them |
|
|
67
|
+
| `signal` | Aborted when the user stops the run: pass it to your HTTP call |
|
|
68
|
+
|
|
69
|
+
| `ModelResponse` field | Description |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `text` | Assistant text (shown in the AI panel) |
|
|
72
|
+
| `toolCalls` | `{ id, name, arguments }` with `arguments` as a JSON string |
|
|
73
|
+
| `stop` | `'end' \| 'tool_calls' \| 'max_tokens' \| 'refusal'` (inferred from `toolCalls` when omitted) |
|
|
74
|
+
| `usage` | `{ input, output, cacheRead? }` tokens, for the `usage` event and the cost estimate |
|
|
75
|
+
| `model` | Model that answered (for pricing) |
|
|
76
|
+
|
|
77
|
+
Errors thrown by `callModel` end the run with an `error` event (HTTP `status` 401 / 403 / 404 / 429 / 400 become the usual messages). They are not retried.
|
|
78
|
+
|
|
79
|
+
#### OpenAI (official SDK)
|
|
80
|
+
|
|
81
|
+
`toOpenAIChat` / `fromOpenAIChat` convert between this contract and Chat Completions (plain data, no SDK inside the library):
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import OpenAI from 'openai';
|
|
85
|
+
import { createAIHandler, toOpenAIChat, fromOpenAIChat } from '@emabuild/ai';
|
|
86
|
+
|
|
87
|
+
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
|
|
88
|
+
|
|
89
|
+
createAIHandler({
|
|
90
|
+
model: 'gpt-4o',
|
|
91
|
+
callModel: async (req) => fromOpenAIChat(
|
|
92
|
+
await openai.chat.completions.create({ model: 'gpt-4o', ...toOpenAIChat(req) }, { signal: req.signal }),
|
|
93
|
+
),
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
#### OpenAI-compatible servers (Cerebras, Groq, Azure, local), no SDK
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { createAIHandler, openAICompatibleModel } from '@emabuild/ai';
|
|
101
|
+
|
|
102
|
+
createAIHandler({
|
|
103
|
+
callModel: openAICompatibleModel({
|
|
104
|
+
baseURL: 'https://api.cerebras.ai/v1',
|
|
105
|
+
apiKey: process.env.CEREBRAS_API_KEY,
|
|
106
|
+
model: 'gpt-oss-120b',
|
|
107
|
+
}),
|
|
108
|
+
});
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`openAICompatibleModel({ model, apiKey?, baseURL?, headers?, body?, maxTokensParam?, fetch? })` posts to `{baseURL}/chat/completions` with `fetch`. Default base URL: OpenAI. Errors keep the provider's message, never your key.
|
|
112
|
+
|
|
113
|
+
#### Claude (built in, default)
|
|
114
|
+
|
|
115
|
+
No `callModel`: the built-in adapter streams from the Messages API with prompt caching, progress notes, server-side refusal fallbacks and `effort`. Pass `client` for Bedrock / Vertex / Foundry.
|
|
116
|
+
|
|
117
|
+
#### Capabilities
|
|
118
|
+
|
|
119
|
+
| | Claude (built in) | `callModel` |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| Live operations while the model writes | per tool call, streamed | per turn |
|
|
122
|
+
| Progress notes in the AI panel | yes | no |
|
|
123
|
+
| Prompt caching | explicit (system + conversation) | whatever your provider does (OpenAI caches long prefixes automatically) |
|
|
124
|
+
| Refusal handling | `refusal` stop + server fallbacks | `stop: 'refusal'` if you report it |
|
|
125
|
+
| Token usage / cost | yes | if you return `usage` (prices for common OpenAI models are built in) |
|
|
126
|
+
| Extra dependency | `@anthropic-ai/sdk` | none (your own SDK, if any) |
|
|
127
|
+
|
|
128
|
+
For full control (streaming, your own conversation format) implement a `ModelAdapter` and pass it as `adapter`.
|
|
129
|
+
|
|
37
130
|
## Protocol
|
|
38
131
|
|
|
39
132
|
**Request:** `POST` with a JSON `AIRequest` (from `@emabuild/types`):
|
|
@@ -99,7 +192,23 @@ app.listen(8787);
|
|
|
99
192
|
|
|
100
193
|
Plain `node:http`: `http.createServer(toNodeHandler(createAIHandler())).listen(8787)`.
|
|
101
194
|
|
|
102
|
-
>
|
|
195
|
+
> The stream is sent with `Cache-Control: no-transform`, which the `compression` middleware respects, so it is not buffered. If your compression ignores that header, disable it on this route.
|
|
196
|
+
|
|
197
|
+
#### CommonJS apps (dynamic import) with your own session auth
|
|
198
|
+
|
|
199
|
+
```js
|
|
200
|
+
// server.js (CommonJS), after app.use(express.json())
|
|
201
|
+
(async () => {
|
|
202
|
+
const { createAIHandler, toNodeHandler, openAICompatibleModel } = await import('@emabuild/ai');
|
|
203
|
+
const ai = toNodeHandler(createAIHandler({
|
|
204
|
+
callModel: openAICompatibleModel({ model: 'gpt-4o', apiKey: config.openai.apiKey }),
|
|
205
|
+
transformRequest: (request) => ({ ...request, context: { ...request.context, brand: currentBrand } }),
|
|
206
|
+
}));
|
|
207
|
+
app.post('/api/newsletters/ai', requireSession, ai); // your auth middleware first
|
|
208
|
+
})();
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
The editor only needs `ai: { endpoint: '/api/newsletters/ai' }`.
|
|
103
212
|
|
|
104
213
|
### Next.js (App Router)
|
|
105
214
|
|
|
@@ -152,17 +261,19 @@ for await (const event of runAI(aiRequest, { signal })) {
|
|
|
152
261
|
|
|
153
262
|
| Option | Description |
|
|
154
263
|
|---|---|
|
|
155
|
-
| `
|
|
156
|
-
| `
|
|
157
|
-
| `
|
|
158
|
-
| `
|
|
264
|
+
| `callModel` | Your function that answers each model turn (any provider). See *Choosing the model*. |
|
|
265
|
+
| `adapter` | A full `ModelAdapter` (takes precedence over `callModel`) |
|
|
266
|
+
| `client` | Claude: pre-configured `Anthropic` client (Bedrock/Vertex/Foundry, custom `baseURL`, retries) |
|
|
267
|
+
| `apiKey` | Claude: API key. If omitted, the SDK resolves credentials itself. |
|
|
268
|
+
| `model` | Claude model (default `claude-opus-5-5`); with `callModel`, the name used for pricing when the response has none |
|
|
269
|
+
| `effort` | Default `medium`. Claude: `output_config.effort`; with `callModel` it is passed on. `null` omits it. |
|
|
159
270
|
| `maxTokens` | Output cap per model response. Default `64000` (responses are streamed). |
|
|
160
271
|
| `maxTurns` | Maximum number of model round-trips. Default `30`. |
|
|
161
272
|
| `systemPrompt` | Extra instructions appended to the built-in system prompt |
|
|
162
|
-
| `fallbacks` |
|
|
273
|
+
| `fallbacks` | Claude only: server-side refusal fallbacks (`fallbacks: "default"`). On by default for supported models. Set to `false` on Bedrock/Vertex/Foundry or behind proxies. |
|
|
163
274
|
| `reportUsage` | Send a `usage` event (tokens and estimated cost) right before `done` / `error`. Default `true`; set `false` to keep usage on the server. |
|
|
164
275
|
| `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` |
|
|
276
|
+
| `progressUpdates` | Claude only: forward the model's progress notes as `status` events (`thinking.display: "updates"`). On by default for supported models. |
|
|
166
277
|
| `cors` | `"*"`, an origin, a list of origins, or `false`. The default is `false`, which allows same-origin requests only. |
|
|
167
278
|
| `authorize(req)` | Return `false` to reject the request with `401` |
|
|
168
279
|
| `transformRequest(aiRequest, req)` | Inject server-side context, such as tenant brand, products or a forced language |
|
package/dist/cli.js
CHANGED
|
@@ -3,28 +3,46 @@
|
|
|
3
3
|
* Standalone development server for the Emabuild AI connector.
|
|
4
4
|
*
|
|
5
5
|
* ANTHROPIC_API_KEY=... npx emabuild-ai-server
|
|
6
|
+
* EMABUILD_AI_PROVIDER=openai OPENAI_API_KEY=... EMABUILD_AI_MODEL=gpt-4o npx emabuild-ai-server
|
|
6
7
|
*
|
|
7
8
|
* Env: PORT (default 8787), HOST (default 127.0.0.1; use 0.0.0.0 to expose it),
|
|
8
|
-
*
|
|
9
|
-
*
|
|
9
|
+
* EMABUILD_AI_PROVIDER ("anthropic", default, or "openai" for any OpenAI-compatible server),
|
|
10
|
+
* EMABUILD_AI_MODEL, EMABUILD_AI_BASE_URL (OpenAI-compatible base URL, e.g. Cerebras),
|
|
11
|
+
* ANTHROPIC_API_KEY / OPENAI_API_KEY (or EMABUILD_AI_API_KEY), EMABUILD_AI_EFFORT,
|
|
12
|
+
* EMABUILD_AI_CORS (default "*"), EMABUILD_AI_IMAGES ("off" disables the free-image search tool).
|
|
13
|
+
* Keys are read from the environment only and never logged.
|
|
10
14
|
*/
|
|
11
15
|
import { createServer } from 'node:http';
|
|
12
16
|
import { createAIHandler } from './handler.js';
|
|
13
17
|
import { toNodeHandler } from '@emabuild/shared/node';
|
|
14
18
|
import { DEFAULT_MODEL } from './run.js';
|
|
19
|
+
import { openAICompatibleModel } from './providers/openai-format.js';
|
|
15
20
|
const port = Number(process.env.PORT ?? 8787);
|
|
16
21
|
const host = process.env.HOST ?? '127.0.0.1';
|
|
17
|
-
const
|
|
22
|
+
const provider = (process.env.EMABUILD_AI_PROVIDER || 'anthropic').toLowerCase();
|
|
23
|
+
const openai = provider === 'openai' || provider === 'openai-compatible';
|
|
24
|
+
const model = process.env.EMABUILD_AI_MODEL || (openai ? 'gpt-4o' : DEFAULT_MODEL);
|
|
18
25
|
const effort = (process.env.EMABUILD_AI_EFFORT || undefined);
|
|
19
26
|
const corsEnv = process.env.EMABUILD_AI_CORS ?? '*';
|
|
20
27
|
const cors = corsEnv === 'false' ? false : corsEnv.includes(',') ? corsEnv.split(',').map((s) => s.trim()) : corsEnv;
|
|
21
|
-
if (
|
|
28
|
+
if (openai) {
|
|
29
|
+
if (!process.env.EMABUILD_AI_API_KEY && !process.env.OPENAI_API_KEY)
|
|
30
|
+
console.warn('[emabuild-ai] No API key: set OPENAI_API_KEY or EMABUILD_AI_API_KEY.');
|
|
31
|
+
}
|
|
32
|
+
else if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) {
|
|
22
33
|
console.warn('[emabuild-ai] ANTHROPIC_API_KEY is not set; falling back to the SDK credential chain (e.g. `ant auth login`).');
|
|
23
34
|
}
|
|
24
35
|
const ai = toNodeHandler(createAIHandler({
|
|
25
36
|
model,
|
|
26
37
|
effort,
|
|
27
38
|
cors,
|
|
39
|
+
...(openai ? {
|
|
40
|
+
callModel: openAICompatibleModel({
|
|
41
|
+
model,
|
|
42
|
+
apiKey: process.env.EMABUILD_AI_API_KEY || process.env.OPENAI_API_KEY,
|
|
43
|
+
...(process.env.EMABUILD_AI_BASE_URL ? { baseURL: process.env.EMABUILD_AI_BASE_URL } : {}),
|
|
44
|
+
}),
|
|
45
|
+
} : {}),
|
|
28
46
|
...(process.env.EMABUILD_AI_IMAGES === 'off' ? { imageSearch: false } : {}),
|
|
29
47
|
onError: (err) => console.error('[emabuild-ai]', err),
|
|
30
48
|
}));
|
|
@@ -36,14 +54,14 @@ const server = createServer((req, res) => {
|
|
|
36
54
|
}
|
|
37
55
|
if (path === '/health' && req.method === 'GET') {
|
|
38
56
|
res.writeHead(200, { 'content-type': 'application/json' });
|
|
39
|
-
res.end(JSON.stringify({ ok: true, model }));
|
|
57
|
+
res.end(JSON.stringify({ ok: true, provider: openai ? 'openai' : 'anthropic', model }));
|
|
40
58
|
return;
|
|
41
59
|
}
|
|
42
60
|
res.writeHead(404, { 'content-type': 'application/json' });
|
|
43
61
|
res.end(JSON.stringify({ error: 'Not found' }));
|
|
44
62
|
});
|
|
45
63
|
server.listen(port, host, () => {
|
|
46
|
-
console.log(`[emabuild-ai] listening on http://${host}:${port}/ai (model: ${model})`);
|
|
64
|
+
console.log(`[emabuild-ai] listening on http://${host}:${port}/ai (${openai ? 'openai-compatible' : 'anthropic'}, model: ${model})`);
|
|
47
65
|
});
|
|
48
66
|
const shutdown = () => server.close(() => process.exit(0));
|
|
49
67
|
process.on('SIGINT', shutdown);
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,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|
* @emabuild/ai — server side of the Emabuild editor's AI connector.
|
|
3
3
|
*
|
|
4
|
-
* Turns an `AIRequest` into a stream of `AIStreamEvent`s
|
|
5
|
-
*
|
|
4
|
+
* Turns an `AIRequest` into a stream of `AIStreamEvent`s: the library runs the
|
|
5
|
+
* flow, the model is Claude (default) or anything you plug in with `callModel`.
|
|
6
|
+
* Exposed over HTTP as NDJSON.
|
|
6
7
|
*/
|
|
7
8
|
export { runAI, buildRequestParams, DEFAULT_MODEL, DEFAULT_MAX_TOKENS, DEFAULT_MAX_TURNS, type RunAIOptions, type RequestParams, type AIEffort, } from './run.js';
|
|
8
9
|
export { MODEL_PRICING, pricingFor, UsageMeter, type ModelPricing, type MessageUsage } from './usage.js';
|
|
10
|
+
export { runLoop, MAX_STREAM_RETRIES, type LoopOptions } from './loop.js';
|
|
11
|
+
export { createAnthropicAdapter, systemParts, toolSpecs, type AnthropicOptions } from './providers/anthropic.js';
|
|
12
|
+
export { adapterFromModelCall } from './providers/model-call.js';
|
|
13
|
+
export { toOpenAIChat, fromOpenAIChat, openAICompatibleModel, OpenAICompatibleError, type OpenAIChatParams, type OpenAIChatCompletion, type OpenAICompatibleOptions, } from './providers/openai-format.js';
|
|
14
|
+
export { providerErrorMessage, describeAnyError, type ProviderErrorKind } from './providers/errors.js';
|
|
15
|
+
export { ProviderSetupError, type ModelCall, type ModelRequest, type ModelResponse, type ConversationMessage, type ToolCall, type ToolSpec, type ModelAdapter, type AdapterEvent, type NormalizedUsage, type StopReason, type SystemPart, type ToolResult, type TurnSettings, } from './providers/types.js';
|
|
9
16
|
export { createAIHandler, validateAIRequest, NDJSON_CONTENT_TYPE, type AIHandlerOptions } from './handler.js';
|
|
10
17
|
export { toNodeHandler, type FetchHandler, type NodeHandler } from '@emabuild/shared/node';
|
|
11
18
|
export { BASE_SYSTEM_PROMPT, buildSchemaPrompt, buildUserPrompt, flattenMergeTags, compactSourceHtml, MAX_SOURCE_HTML } from './prompt.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EACL,KAAK,EACL,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,iBAAiB,EACjB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,QAAQ,GACd,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AACzG,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,WAAW,EAAE,SAAS,EAAE,KAAK,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACjH,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EACL,YAAY,EAAE,cAAc,EAAE,qBAAqB,EAAE,qBAAqB,EAC1E,KAAK,gBAAgB,EAAE,KAAK,oBAAoB,EAAE,KAAK,uBAAuB,GAC/E,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACvG,OAAO,EACL,kBAAkB,EAClB,KAAK,SAAS,EAAE,KAAK,YAAY,EAAE,KAAK,aAAa,EAAE,KAAK,mBAAmB,EAAE,KAAK,QAAQ,EAAE,KAAK,QAAQ,EAC7G,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,KAAK,eAAe,EAAE,KAAK,UAAU,EAAE,KAAK,UAAU,EAAE,KAAK,UAAU,EAAE,KAAK,YAAY,GACjI,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC9G,OAAO,EAAE,aAAa,EAAE,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,eAAe,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3I,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAE,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7H,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACvF,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC5F,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @emabuild/ai — server side of the Emabuild editor's AI connector.
|
|
3
3
|
*
|
|
4
|
-
* Turns an `AIRequest` into a stream of `AIStreamEvent`s
|
|
5
|
-
*
|
|
4
|
+
* Turns an `AIRequest` into a stream of `AIStreamEvent`s: the library runs the
|
|
5
|
+
* flow, the model is Claude (default) or anything you plug in with `callModel`.
|
|
6
|
+
* Exposed over HTTP as NDJSON.
|
|
6
7
|
*/
|
|
7
8
|
export { runAI, buildRequestParams, DEFAULT_MODEL, DEFAULT_MAX_TOKENS, DEFAULT_MAX_TURNS, } from './run.js';
|
|
8
9
|
export { MODEL_PRICING, pricingFor, UsageMeter } from './usage.js';
|
|
10
|
+
export { runLoop, MAX_STREAM_RETRIES } from './loop.js';
|
|
11
|
+
export { createAnthropicAdapter, systemParts, toolSpecs } from './providers/anthropic.js';
|
|
12
|
+
export { adapterFromModelCall } from './providers/model-call.js';
|
|
13
|
+
export { toOpenAIChat, fromOpenAIChat, openAICompatibleModel, OpenAICompatibleError, } from './providers/openai-format.js';
|
|
14
|
+
export { providerErrorMessage, describeAnyError } from './providers/errors.js';
|
|
15
|
+
export { ProviderSetupError, } from './providers/types.js';
|
|
9
16
|
export { createAIHandler, validateAIRequest, NDJSON_CONTENT_TYPE } from './handler.js';
|
|
10
17
|
export { toNodeHandler } from '@emabuild/shared/node';
|
|
11
18
|
export { BASE_SYSTEM_PROMPT, buildSchemaPrompt, buildUserPrompt, flattenMergeTags, compactSourceHtml, MAX_SOURCE_HTML } from './prompt.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EACL,KAAK,EACL,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,iBAAiB,GAIlB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,UAAU,EAAwC,MAAM,YAAY,CAAC;AACzG,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAoB,MAAM,WAAW,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,WAAW,EAAE,SAAS,EAAyB,MAAM,0BAA0B,CAAC;AACjH,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EACL,YAAY,EAAE,cAAc,EAAE,qBAAqB,EAAE,qBAAqB,GAE3E,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAA0B,MAAM,uBAAuB,CAAC;AACvG,OAAO,EACL,kBAAkB,GAGnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,mBAAmB,EAAyB,MAAM,cAAc,CAAC;AAC9G,OAAO,EAAE,aAAa,EAAuC,MAAM,uBAAuB,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,eAAe,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3I,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAsB,MAAM,cAAc,CAAC;AAC7H,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAyB,MAAM,eAAe,CAAC;AACvF,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/loop.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module loop
|
|
3
|
+
*
|
|
4
|
+
* The provider-agnostic agent loop: it owns the flow (prompts, tools,
|
|
5
|
+
* validation, retries, turn limit, editor events) and asks a
|
|
6
|
+
* {@link ModelAdapter} for each model turn. The `AIStreamEvent`s it yields are
|
|
7
|
+
* the editor's NDJSON protocol, identical whatever model answers.
|
|
8
|
+
*/
|
|
9
|
+
import type { AIRequest, AIStreamEvent, FreeImage, FreeImageSearchOptions } from '@emabuild/types';
|
|
10
|
+
import type { ModelAdapter, TurnSettings } from './providers/types.js';
|
|
11
|
+
import type { UsageMeter } from './usage.js';
|
|
12
|
+
/** Retries of a turn whose stream failed for a non-API reason (only if it changed nothing yet) */
|
|
13
|
+
export declare const MAX_STREAM_RETRIES = 2;
|
|
14
|
+
export interface LoopOptions {
|
|
15
|
+
/** Max model round-trips */
|
|
16
|
+
maxTurns: number;
|
|
17
|
+
settings: TurnSettings;
|
|
18
|
+
/** Free-image search behind `search_images` (false: the tool is not offered) */
|
|
19
|
+
imageSearch?: ((query: string, options: FreeImageSearchOptions) => Promise<FreeImage[]>) | false;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Run the agent loop with `adapter`. Never throws: problems end the run with
|
|
23
|
+
* an `error` event. Usage of every completed turn is recorded in `meter`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function runLoop(adapter: ModelAdapter, request: AIRequest, options: LoopOptions, meter: UsageMeter): AsyncGenerator<AIStreamEvent>;
|
|
26
|
+
//# sourceMappingURL=loop.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAmB,SAAS,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAMpH,OAAO,KAAK,EAAE,YAAY,EAAoC,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,kGAAkG;AAClG,eAAO,MAAM,kBAAkB,IAAI,CAAC;AAEpC,MAAM,WAAW,WAAW;IAC1B,4BAA4B;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,YAAY,CAAC;IACvB,gFAAgF;IAChF,WAAW,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,sBAAsB,KAAK,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC;CAClG;AA+ED;;;GAGG;AACH,wBAAuB,OAAO,CAC5B,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,SAAS,EAClB,OAAO,EAAE,WAAW,EACpB,KAAK,EAAE,UAAU,GAChB,cAAc,CAAC,aAAa,CAAC,CA+H/B"}
|
package/dist/loop.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module loop
|
|
3
|
+
*
|
|
4
|
+
* The provider-agnostic agent loop: it owns the flow (prompts, tools,
|
|
5
|
+
* validation, retries, turn limit, editor events) and asks a
|
|
6
|
+
* {@link ModelAdapter} for each model turn. The `AIStreamEvent`s it yields are
|
|
7
|
+
* the editor's NDJSON protocol, identical whatever model answers.
|
|
8
|
+
*/
|
|
9
|
+
import { searchOpenverse } from '@emabuild/shared';
|
|
10
|
+
import { buildUserPrompt } from './prompt.js';
|
|
11
|
+
import { APPLY_OPERATIONS_TOOL, FINISH_TOOL, SEARCH_IMAGES_TOOL } from './tools.js';
|
|
12
|
+
import { DesignState, validateOperations } from './validate.js';
|
|
13
|
+
import { describeAnyError } from './providers/errors.js';
|
|
14
|
+
/** Retries of a turn whose stream failed for a non-API reason (only if it changed nothing yet) */
|
|
15
|
+
export const MAX_STREAM_RETRIES = 2;
|
|
16
|
+
const defaultImageSearch = async (query, options) => (await searchOpenverse(query, options)).images;
|
|
17
|
+
const errorResult = (id, content) => ({ id, content, isError: true });
|
|
18
|
+
/** Parse tool arguments; `null` when the JSON is invalid */
|
|
19
|
+
function parseArgs(json) {
|
|
20
|
+
try {
|
|
21
|
+
const v = json.trim() ? JSON.parse(json) : {};
|
|
22
|
+
return v && typeof v === 'object' ? v : {};
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** Runs a `search_images` call; failures go back to the model so it can fall back to placeholders */
|
|
29
|
+
async function searchImagesResult(call, options, describe) {
|
|
30
|
+
const args = parseArgs(call.arguments);
|
|
31
|
+
if (!args)
|
|
32
|
+
return errorResult(call.id, JSON.stringify({ INVALID_JSON: call.arguments }));
|
|
33
|
+
const query = typeof args.query === 'string' ? args.query.trim() : '';
|
|
34
|
+
if (!query)
|
|
35
|
+
return errorResult(call.id, '`query` is required.');
|
|
36
|
+
const orientation = ['landscape', 'portrait', 'square'].includes(args.orientation)
|
|
37
|
+
? args.orientation : undefined;
|
|
38
|
+
const count = Math.min(Math.max(Number(args.count) || 5, 1), 10);
|
|
39
|
+
const search = options.imageSearch || defaultImageSearch;
|
|
40
|
+
try {
|
|
41
|
+
const images = (await search(query, { orientation, count, signal: options.settings.signal })).slice(0, count);
|
|
42
|
+
if (!images.length)
|
|
43
|
+
return { id: call.id, content: 'No results. Try a broader query, or use a placeholder.' };
|
|
44
|
+
const compact = images.map(({ url, width, height, title }) => ({ url, width, height, title }));
|
|
45
|
+
return { id: call.id, content: JSON.stringify(compact) };
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
return errorResult(call.id, `Image search failed (${describe(err)}). Use placeholders instead.`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function handleToolCall(call, state) {
|
|
52
|
+
const args = parseArgs(call.arguments);
|
|
53
|
+
if (!args)
|
|
54
|
+
return { result: errorResult(call.id, JSON.stringify({ INVALID_JSON: call.arguments })) };
|
|
55
|
+
if (call.name === APPLY_OPERATIONS_TOOL) {
|
|
56
|
+
const v = validateOperations(args.operations, state);
|
|
57
|
+
if (!v.ok) {
|
|
58
|
+
return {
|
|
59
|
+
result: errorResult(call.id, `Batch rejected, nothing was applied. Fix these problems and send the whole batch again:\n- ${v.errors.join('\n- ')}`),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const refs = v.state.describeRefs();
|
|
63
|
+
return {
|
|
64
|
+
operations: v.operations,
|
|
65
|
+
state: v.state,
|
|
66
|
+
result: {
|
|
67
|
+
id: call.id,
|
|
68
|
+
content: `Applied ${v.operations.length} operation${v.operations.length === 1 ? '' : 's'}.${refs.length ? ` Available refs: ${refs.join('; ')}.` : ''}`,
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
if (call.name === FINISH_TOOL) {
|
|
73
|
+
const summary = typeof args.summary === 'string' ? args.summary.trim() : '';
|
|
74
|
+
return { summary, result: { id: call.id, content: 'Done.' } };
|
|
75
|
+
}
|
|
76
|
+
return { result: errorResult(call.id, `Unknown tool "${call.name}".`) };
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Run the agent loop with `adapter`. Never throws: problems end the run with
|
|
80
|
+
* an `error` event. Usage of every completed turn is recorded in `meter`.
|
|
81
|
+
*/
|
|
82
|
+
export async function* runLoop(adapter, request, options, meter) {
|
|
83
|
+
const { settings } = options;
|
|
84
|
+
const signal = settings.signal;
|
|
85
|
+
const describe = (err) => adapter.describeError(err) ?? describeAnyError(err);
|
|
86
|
+
const isAbort = (err) => signal?.aborted || adapter.isAbortError(err);
|
|
87
|
+
const fatal = (err) => err?.fatal === true;
|
|
88
|
+
let conversation;
|
|
89
|
+
try {
|
|
90
|
+
conversation = await adapter.createConversation(buildUserPrompt(request), settings);
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
yield { type: 'error', error: fatal(err) || adapter.isProviderError(err) ? describe(err) : `Invalid AI request: ${describe(err)}` };
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
let state = new DesignState(request.design, request.schema);
|
|
97
|
+
let lastStatus = '';
|
|
98
|
+
let lastMessage;
|
|
99
|
+
let summary;
|
|
100
|
+
let finished = false;
|
|
101
|
+
let retries = 0;
|
|
102
|
+
let ended = false;
|
|
103
|
+
const status = (message) => {
|
|
104
|
+
if (!message || message === lastStatus)
|
|
105
|
+
return null;
|
|
106
|
+
lastStatus = message;
|
|
107
|
+
return { type: 'status', message };
|
|
108
|
+
};
|
|
109
|
+
const first = status(request.action === 'generate' ? 'Designing your email…' : 'Working on your request…');
|
|
110
|
+
if (first)
|
|
111
|
+
yield first;
|
|
112
|
+
for (let turn = 0; turn < options.maxTurns && !finished; turn++) {
|
|
113
|
+
if (signal?.aborted) {
|
|
114
|
+
yield { type: 'error', error: 'Request aborted' };
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const results = new Map();
|
|
118
|
+
let emittedThisTurn = false;
|
|
119
|
+
let stop = { reason: 'end', toolCallIds: [] };
|
|
120
|
+
try {
|
|
121
|
+
for await (const ev of adapter.streamTurn(conversation, settings)) {
|
|
122
|
+
if (ev.type === 'text') {
|
|
123
|
+
if (ev.text.trim()) {
|
|
124
|
+
lastMessage = ev.text.trim();
|
|
125
|
+
yield { type: 'message', text: lastMessage };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
else if (ev.type === 'status') {
|
|
129
|
+
const s = status(ev.text);
|
|
130
|
+
if (s)
|
|
131
|
+
yield s;
|
|
132
|
+
}
|
|
133
|
+
else if (ev.type === 'toolStart') {
|
|
134
|
+
if (ev.name === APPLY_OPERATIONS_TOOL) {
|
|
135
|
+
const s = status('Updating the design…');
|
|
136
|
+
if (s)
|
|
137
|
+
yield s;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
else if (ev.type === 'toolCall') {
|
|
141
|
+
const call = ev.call;
|
|
142
|
+
if (call.name === SEARCH_IMAGES_TOOL) {
|
|
143
|
+
const s = status('Looking for free images…');
|
|
144
|
+
if (s)
|
|
145
|
+
yield s;
|
|
146
|
+
results.set(call.id, await searchImagesResult(call, options, describe));
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const outcome = handleToolCall(call, state);
|
|
150
|
+
results.set(call.id, outcome.result);
|
|
151
|
+
if (outcome.state)
|
|
152
|
+
state = outcome.state;
|
|
153
|
+
if (outcome.operations) {
|
|
154
|
+
emittedThisTurn = true;
|
|
155
|
+
yield { type: 'operations', operations: outcome.operations };
|
|
156
|
+
}
|
|
157
|
+
if (outcome.summary !== undefined) {
|
|
158
|
+
summary = outcome.summary;
|
|
159
|
+
finished = true;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
else if (ev.type === 'usage') {
|
|
163
|
+
meter.record(ev.model, ev.usage);
|
|
164
|
+
}
|
|
165
|
+
else if (ev.type === 'stop') {
|
|
166
|
+
stop = { reason: ev.reason, toolCallIds: ev.toolCallIds };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
retries = 0;
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
if (isAbort(err)) {
|
|
173
|
+
yield { type: 'error', error: 'Request aborted' };
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
// Provider API errors are reported as-is; anything else (e.g. a tool input
|
|
177
|
+
// the SDK could not parse) is retried once or twice if this turn has not
|
|
178
|
+
// already changed the canvas.
|
|
179
|
+
if (fatal(err) || adapter.isProviderError(err) || emittedThisTurn || retries >= MAX_STREAM_RETRIES) {
|
|
180
|
+
yield { type: 'error', error: describe(err) };
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
retries++;
|
|
184
|
+
finished = false;
|
|
185
|
+
turn--;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (stop.reason === 'refusal') {
|
|
189
|
+
yield { type: 'error', error: 'The AI model declined this request.' };
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
adapter.commitAssistantTurn(conversation);
|
|
193
|
+
if (stop.reason === 'pause')
|
|
194
|
+
continue;
|
|
195
|
+
if (finished)
|
|
196
|
+
break;
|
|
197
|
+
if (stop.toolCallIds.length === 0) {
|
|
198
|
+
ended = true; // end of turn / max_tokens without tool calls
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
const truncated = stop.reason === 'max_tokens';
|
|
202
|
+
adapter.addToolResults(conversation, stop.toolCallIds.map((id) => results.get(id) ?? errorResult(id, truncated
|
|
203
|
+
? 'Your response hit the output token limit and this tool call was cut off; nothing from it was applied. Send smaller batches.'
|
|
204
|
+
: 'Tool call could not be processed; nothing was applied. Please retry.')));
|
|
205
|
+
}
|
|
206
|
+
if (!finished && !ended) {
|
|
207
|
+
const s = status('Stopped after reaching the maximum number of steps.');
|
|
208
|
+
if (s)
|
|
209
|
+
yield s;
|
|
210
|
+
}
|
|
211
|
+
yield summary !== undefined || lastMessage !== undefined
|
|
212
|
+
? { type: 'done', summary: summary ?? lastMessage }
|
|
213
|
+
: { type: 'done' };
|
|
214
|
+
}
|
|
215
|
+
//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