@ember-marquetry/sse 0.0.0-stage → 1.0.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/CHANGELOG.md +31 -0
- package/LICENSE.md +21 -0
- package/NOTICE +13 -0
- package/README.md +58 -2
- package/dist/index.d.ts +29 -0
- package/dist/index.js +154 -0
- package/dist/index.js.map +1 -0
- package/dist/transport.d.ts +22 -0
- package/package.json +48 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# @ember-marquetry/sse
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 8f2790b: The first release of Marquetry: generative UI for Ember.
|
|
8
|
+
|
|
9
|
+
- `core`: the spec format, the JSONL patch stream, expressions, actions, the catalog, agent events, chat threads and stream replay.
|
|
10
|
+
- `ember`: the `<Render>` component and the `Generation` state machine.
|
|
11
|
+
- `joinery`: a catalog of 69 Joinery components, with layout templates and the chart, data table and code block add-ons. The `/a2ui` subpath is the A2UI v0.9.1 basic catalog on Joinery components, for the specs of `a2ui`.
|
|
12
|
+
- `chat`: a chat thread on Joinery components, with streamed markdown, agent surfaces, tool calls, approvals and MCP Apps.
|
|
13
|
+
- `formwright`: forms with validation from a JSON Schema, field rules and named validators.
|
|
14
|
+
- `inspector`: a dev panel for `<Render>` that shows the spec, the patches with their line numbers, the state and the problems.
|
|
15
|
+
- `ai-sdk`, `ag-ui`, `a2ui` and `sse`: adapters and chat transports for the AI SDK, AG-UI 1.0, A2UI v0.9.1 and plain JSONL or SSE endpoints.
|
|
16
|
+
- `markdown`: a streamed markdown parser that makes no HTML.
|
|
17
|
+
- `mcp-apps`: a host for MCP Apps in a sandbox frame on a second origin.
|
|
18
|
+
- `eslint-plugin`, `skills`, `test-support` and the `ember-marquetry` CLI: tools for catalog authors and app developers.
|
|
19
|
+
|
|
20
|
+
Safety defaults in 1.0:
|
|
21
|
+
|
|
22
|
+
- `joinery`: a URL that the browser loads with no click (the `src` of `Image` and `Avatar`, the `image` of `Attachment`, and the `url` of the A2UI `Image`, `Video` and `AudioPlayer`) must be relative, unless `urls.mediaHosts` lists its host. `isSafeMediaUrl` is the check. `urls.hosts` applies only to links.
|
|
23
|
+
- `markdown` and `chat`: an image must pass `isSafeImageUrl` (`<Chat @isSafeImageUrl>`, `<Markdown @isSafeImageUrl>`). The default, `isRelativeUrl`, accepts only a relative URL. A block of more than 20,000 characters is plain text.
|
|
24
|
+
- `chat`: `<McpApp>` and `McpAppsConfig` have `approveDomain`. Without it, the app gets no domain that it declares in its CSP. An app cannot call a tool that needs the approval of the user (`@needsApproval`).
|
|
25
|
+
- `mcp-apps`: the proxy puts the CSP meta at offset 0 of the app HTML, and gives its own page a `frame-src` with only the approved frame domains.
|
|
26
|
+
- `ai-sdk` and `ag-ui`: a problem in one item is a `data` event named `stream-error`, and a value that the reader does not convert is a `data` event named `unconverted`. `error` is only for a failed run.
|
|
27
|
+
|
|
28
|
+
### Patch Changes
|
|
29
|
+
|
|
30
|
+
- Updated dependencies [8f2790b]
|
|
31
|
+
- @ember-marquetry/core@1.0.0
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joe Gaudet
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Marquetry
|
|
2
|
+
Copyright (c) 2026 Joe Gaudet. MIT licensed; see LICENSE.md.
|
|
3
|
+
|
|
4
|
+
Marquetry is an original design. Two projects gave it ideas and formats, and Marquetry copies
|
|
5
|
+
no code from them:
|
|
6
|
+
|
|
7
|
+
- json-render (Vercel, Apache 2.0): the idea of a catalog that limits a model, a flat element
|
|
8
|
+
map, and a spec that streams as JSON Lines of RFC 6902 patches.
|
|
9
|
+
- A2UI (Google, Apache 2.0): the v0.9 message format that @ember-marquetry/a2ui reads.
|
|
10
|
+
|
|
11
|
+
@ember-marquetry/ag-ui reads the event format of the AG-UI protocol, and
|
|
12
|
+
@ember-marquetry/ai-sdk reads the UI message stream format of the Vercel AI SDK. Marquetry
|
|
13
|
+
depends on neither package.
|
package/README.md
CHANGED
|
@@ -1,3 +1,59 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ember-marquetry/sse
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small fetch client for [Marquetry](https://joegaudet.com/ember-marquetry/). It reads a JSONL
|
|
4
|
+
or a Server-Sent Events endpoint, and gives the text to the spec compiler. It has no
|
|
5
|
+
dependency on an AI SDK.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @ember-marquetry/sse
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { streamFrom } from '@ember-marquetry/sse'
|
|
13
|
+
|
|
14
|
+
const source = streamFrom('/api/ui', {
|
|
15
|
+
method: 'POST',
|
|
16
|
+
headers: { 'content-type': 'application/json' },
|
|
17
|
+
body: JSON.stringify({ prompt }),
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
generation.run(source) // `Generation` from @ember-marquetry/ember
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`streamFrom` returns a function that takes an `AbortSignal` and makes one request for each
|
|
24
|
+
call. A JSONL body goes out unchanged. A `text/event-stream` body gives one line for each
|
|
25
|
+
event, and stops at `[DONE]`. A response that is not ok throws an `HttpError` with `status`
|
|
26
|
+
and `body`.
|
|
27
|
+
|
|
28
|
+
| Export | |
|
|
29
|
+
| ------------------------------ | ------------------------------------------------------------------ |
|
|
30
|
+
| `streamFrom(url, options)` | A stream source. Options: the `fetch` options, `fetch`, `format`. |
|
|
31
|
+
| `parseSse(chunks)` | Parses Server-Sent Events from text chunks. |
|
|
32
|
+
| `readText(stream)` | Decodes a byte stream to text chunks. |
|
|
33
|
+
| `HttpError` | The error for a response that is not ok. |
|
|
34
|
+
| `jsonlTransport(url, options)` | A chat transport for a JSONL spec endpoint. |
|
|
35
|
+
| `guardRun(events, signal)` | Makes a run end with `finish` or `error`, also after an exception. |
|
|
36
|
+
|
|
37
|
+
## A chat transport
|
|
38
|
+
|
|
39
|
+
A transport sends a thread and gives the agent events of the reply. Each adapter package has
|
|
40
|
+
one, and each one has the same shape: `send(thread, signal)`.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { reduceThread, addUserMessage, emptyThread } from '@ember-marquetry/core'
|
|
44
|
+
import { jsonlTransport } from '@ember-marquetry/sse'
|
|
45
|
+
|
|
46
|
+
const transport = jsonlTransport('/api/ui')
|
|
47
|
+
let thread = addUserMessage(emptyThread(), prompt)
|
|
48
|
+
for await (const event of transport.send(thread, controller.signal)) {
|
|
49
|
+
thread = reduceThread(thread, event)
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- `jsonlTransport` posts `{ prompt, spec }`, as the example servers read it. `prompt` is the
|
|
54
|
+
last message of the user. `spec` is the current spec of the surface, when there is one.
|
|
55
|
+
Give `body(thread)` to send a different body.
|
|
56
|
+
- The patches change the surface `main`. Give `surfaceId` to change a different one.
|
|
57
|
+
- A line that is not a patch becomes a `stream-error` data part, and the run continues.
|
|
58
|
+
- With `mixed: true`, a line that is not a patch is text for the user.
|
|
59
|
+
- A failed request gives an `error` event. An abort gives `finish` with `aborted: true`.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** A response whose status is not in the 200 range. */
|
|
2
|
+
export declare class HttpError extends Error {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly statusText: string;
|
|
5
|
+
readonly body: string;
|
|
6
|
+
name: string;
|
|
7
|
+
constructor(status: number, statusText: string, body: string);
|
|
8
|
+
}
|
|
9
|
+
export interface SseEvent {
|
|
10
|
+
event: string;
|
|
11
|
+
data: string;
|
|
12
|
+
id?: string;
|
|
13
|
+
}
|
|
14
|
+
/** Decodes a byte stream to text chunks. It releases the stream when the reader stops. */
|
|
15
|
+
export declare function readText(stream: ReadableStream<Uint8Array>): AsyncGenerator<string>;
|
|
16
|
+
/** Parses Server-Sent Events from text chunks. An event with no data does not go out. */
|
|
17
|
+
export declare function parseSse(chunks: AsyncIterable<string>): AsyncGenerator<SseEvent>;
|
|
18
|
+
export interface StreamFromOptions extends Omit<RequestInit, 'signal'> {
|
|
19
|
+
/** Default: the global `fetch`. */
|
|
20
|
+
fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
21
|
+
/** `auto` reads SSE when the content type is `text/event-stream`. Default: `auto`. */
|
|
22
|
+
format?: 'auto' | 'jsonl' | 'sse';
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Makes a stream source for an endpoint. Each call of the source makes one request. A JSONL
|
|
26
|
+
* body goes out unchanged. An SSE body gives one line for each event, and stops at `[DONE]`.
|
|
27
|
+
*/
|
|
28
|
+
export declare function streamFrom(input: string | URL | Request, options?: StreamFromOptions): (signal: AbortSignal) => AsyncGenerator<string>;
|
|
29
|
+
export { guardRun, jsonlTransport, lastUserText, type JsonlTransportOptions } from './transport';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { findSurface, createSpecStream } from '@ember-marquetry/core';
|
|
2
|
+
|
|
3
|
+
// src/transport.ts
|
|
4
|
+
async function* guardRun(events, signal) {
|
|
5
|
+
let ended = false;
|
|
6
|
+
try {
|
|
7
|
+
for await (const event of events) {
|
|
8
|
+
if (event.type === "finish" || event.type === "error") ended = true;
|
|
9
|
+
yield event;
|
|
10
|
+
}
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (signal.aborted) {
|
|
13
|
+
yield { type: "finish", aborted: true };
|
|
14
|
+
} else {
|
|
15
|
+
yield { type: "error", message: error instanceof Error ? error.message : String(error) };
|
|
16
|
+
}
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (!ended) yield signal.aborted ? { type: "finish", aborted: true } : { type: "finish" };
|
|
20
|
+
}
|
|
21
|
+
function lastUserText(thread) {
|
|
22
|
+
const message = [...thread.messages].reverse().find((m) => m.role === "user");
|
|
23
|
+
return (message?.parts ?? []).map((part) => part.type === "text" ? part.text : "").join("");
|
|
24
|
+
}
|
|
25
|
+
function jsonlTransport(input, options = {}) {
|
|
26
|
+
const { surfaceId = "main", mixed = false, body, headers, ...init } = options;
|
|
27
|
+
async function* run(thread, signal) {
|
|
28
|
+
yield { type: "run-start" };
|
|
29
|
+
const spec = findSurface(thread, surfaceId)?.spec;
|
|
30
|
+
const payload = body ? body(thread) : spec ? { prompt: lastUserText(thread), spec } : { prompt: lastUserText(thread) };
|
|
31
|
+
const requestHeaders = new Headers(headers);
|
|
32
|
+
requestHeaders.set("content-type", "application/json");
|
|
33
|
+
const source = streamFrom(input, {
|
|
34
|
+
...init,
|
|
35
|
+
method: "POST",
|
|
36
|
+
headers: requestHeaders,
|
|
37
|
+
body: JSON.stringify(payload),
|
|
38
|
+
format: "jsonl"
|
|
39
|
+
});
|
|
40
|
+
const stream = createSpecStream(spec ? { spec, mixed } : { mixed });
|
|
41
|
+
const convert = (events) => events.map((event) => {
|
|
42
|
+
if (event.type === "patch") return { type: "spec", surfaceId, op: event.op };
|
|
43
|
+
if (event.type === "text") return { type: "text", messageId: surfaceId, delta: event.text };
|
|
44
|
+
const { type: _type, ...data } = event;
|
|
45
|
+
return { type: "data", name: "stream-error", data };
|
|
46
|
+
});
|
|
47
|
+
for await (const chunk of source(signal)) yield* convert(stream.push(chunk));
|
|
48
|
+
yield* convert(stream.end());
|
|
49
|
+
}
|
|
50
|
+
return { send: (thread, signal) => guardRun(run(thread, signal), signal) };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/index.ts
|
|
54
|
+
var HttpError = class extends Error {
|
|
55
|
+
constructor(status, statusText, body) {
|
|
56
|
+
super(`The request failed with status ${status}${statusText ? ` ${statusText}` : ""}`);
|
|
57
|
+
this.status = status;
|
|
58
|
+
this.statusText = statusText;
|
|
59
|
+
this.body = body;
|
|
60
|
+
}
|
|
61
|
+
status;
|
|
62
|
+
statusText;
|
|
63
|
+
body;
|
|
64
|
+
name = "HttpError";
|
|
65
|
+
};
|
|
66
|
+
async function* readText(stream) {
|
|
67
|
+
const reader = stream.getReader();
|
|
68
|
+
const decoder = new TextDecoder();
|
|
69
|
+
let finished = false;
|
|
70
|
+
try {
|
|
71
|
+
for (; ; ) {
|
|
72
|
+
const { done, value } = await reader.read();
|
|
73
|
+
if (done) {
|
|
74
|
+
finished = true;
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
const text = decoder.decode(value, { stream: true });
|
|
78
|
+
if (text !== "") yield text;
|
|
79
|
+
}
|
|
80
|
+
const rest = decoder.decode();
|
|
81
|
+
if (rest !== "") yield rest;
|
|
82
|
+
} finally {
|
|
83
|
+
if (!finished) await reader.cancel().catch(() => {
|
|
84
|
+
});
|
|
85
|
+
reader.releaseLock();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function* parseSse(chunks) {
|
|
89
|
+
let buffer = "";
|
|
90
|
+
let first = true;
|
|
91
|
+
let event = "message";
|
|
92
|
+
let id;
|
|
93
|
+
let data = [];
|
|
94
|
+
function* line(text) {
|
|
95
|
+
if (text === "") {
|
|
96
|
+
if (data.length > 0) {
|
|
97
|
+
yield id === void 0 ? { event, data: data.join("\n") } : { event, data: data.join("\n"), id };
|
|
98
|
+
}
|
|
99
|
+
event = "message";
|
|
100
|
+
id = void 0;
|
|
101
|
+
data = [];
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (text.startsWith(":")) return;
|
|
105
|
+
const colon = text.indexOf(":");
|
|
106
|
+
const field = colon === -1 ? text : text.slice(0, colon);
|
|
107
|
+
let value = colon === -1 ? "" : text.slice(colon + 1);
|
|
108
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
109
|
+
if (field === "data") data.push(value);
|
|
110
|
+
else if (field === "event") event = value;
|
|
111
|
+
else if (field === "id") id = value;
|
|
112
|
+
}
|
|
113
|
+
for await (let chunk of chunks) {
|
|
114
|
+
if (first) {
|
|
115
|
+
first = false;
|
|
116
|
+
if (chunk.startsWith("\uFEFF")) chunk = chunk.slice(1);
|
|
117
|
+
}
|
|
118
|
+
buffer += chunk;
|
|
119
|
+
for (; ; ) {
|
|
120
|
+
const end = buffer.search(/\r\n|\n|\r/);
|
|
121
|
+
if (end === -1 || buffer[end] === "\r" && end === buffer.length - 1) break;
|
|
122
|
+
const text = buffer.slice(0, end);
|
|
123
|
+
buffer = buffer.slice(end + (buffer.startsWith("\r\n", end) ? 2 : 1));
|
|
124
|
+
yield* line(text);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (buffer !== "") yield* line(buffer.replace(/\r$/, ""));
|
|
128
|
+
yield* line("");
|
|
129
|
+
}
|
|
130
|
+
function streamFrom(input, options = {}) {
|
|
131
|
+
const { fetch: fetcher = globalThis.fetch, format = "auto", ...init } = options;
|
|
132
|
+
return async function* (signal) {
|
|
133
|
+
const response = await fetcher(input, { ...init, signal });
|
|
134
|
+
if (!response.ok) {
|
|
135
|
+
const text = await response.text().catch(() => "");
|
|
136
|
+
throw new HttpError(response.status, response.statusText, text);
|
|
137
|
+
}
|
|
138
|
+
if (!response.body) return;
|
|
139
|
+
const type = response.headers.get("content-type") ?? "";
|
|
140
|
+
const sse = format === "sse" || format === "auto" && type.includes("text/event-stream");
|
|
141
|
+
if (!sse) {
|
|
142
|
+
yield* readText(response.body);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
for await (const event of parseSse(readText(response.body))) {
|
|
146
|
+
if (event.data === "[DONE]") return;
|
|
147
|
+
yield event.data + "\n";
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export { HttpError, guardRun, jsonlTransport, lastUserText, parseSse, readText, streamFrom };
|
|
153
|
+
//# sourceMappingURL=index.js.map
|
|
154
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/transport.ts","../src/index.ts"],"names":[],"mappings":";;;AAaA,gBAAuB,QAAA,CACrB,QACA,MAAA,EAC4B;AAC5B,EAAA,IAAI,KAAA,GAAQ,KAAA;AACZ,EAAA,IAAI;AACF,IAAA,WAAA,MAAiB,SAAS,MAAA,EAAQ;AAChC,MAAA,IAAI,MAAM,IAAA,KAAS,QAAA,IAAY,KAAA,CAAM,IAAA,KAAS,SAAS,KAAA,GAAQ,IAAA;AAC/D,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,OAAO,OAAA,EAAS;AAClB,M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AG,IAAA,EAAK,GAAI,OAAA;AAExE,EAAA,OAAO,iBAAiB,MAAA,EAAQ;AAC9B,IAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,KAAA,EAAO,EAAE,GAAG,IAAA,EAAM,QAAQ,CAAA;AACzD,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,MAAA,MAAM,OAAO,MAAM,QAAA,CAAS,MAAK,CAAE,KAAA,CAAM,MAAM,EAAE,CAAA;AACjD,MAAA,MAAM,IAAI,SAAA,CAAU,QAAA,CAAS,MAAA,EAAQ,QAAA,CAAS,YAAY,IAAI,CAAA;AAAA,IAChE;AACA,IAAA,IAAI,CAAC,SAAS,IAAA,EAAM;AACpB,IAAA,MAAM,IAAA,GAAO,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,cAAc,CAAA,IAAK,EAAA;AACrD,IAAA,MAAM,MAAM,MAAA,KAAW,KAAA,IAAU,WAAW,MAAA,IAAU,IAAA,CAAK,SAAS,mBAAmB,CAAA;AACvF,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,OAAO,QAAA,CAAS,SAAS,IAAI,CAAA;AAC7B,MAAA;AAAA,IACF;AACA,IAAA,WAAA,MAAiB,SAAS,QAAA,CAAS,QAAA,CAAS,QAAA,CAAS,IAAI,CAAC,CAAA,EAAG;AAC3D,MAAA,IAAI,KAAA,CAAM,SAAS,QAAA,EAAU;AAC7B,MAAA,MAAM,MAAM,IAAA,GAAO,IAAA;AAAA,IACrB;AAAA,EACF,CAAA;AACF","file":"index.js","sourcesContent":["import {\n createSpecStream,\n findSurface,\n type AgentEvent,\n type ChatTransport,\n type Thread,\n} from '@ember-marquetry/core'\nimport { streamFrom, type StreamFromOptions } from './index'\n\n/**\n * Makes a run safe for a thread. An exception becomes an `error` event, an abort becomes an\n * aborted `finish` event, and a stream that stops without `finish` or `error` gets `finish`.\n */\nexport async function* guardRun(\n events: AsyncIterable<AgentEvent>,\n signal: AbortSignal,\n): AsyncGenerator<AgentEvent> {\n let ended = false\n try {\n for await (const event of events) {\n if (event.type === 'finish' || event.type === 'error') ended = true\n yield event\n }\n } catch (error) {\n if (signal.aborted) {\n yield { type: 'finish', aborted: true }\n } else {\n yield { type: 'error', message: error instanceof Error ? error.message : String(error) }\n }\n return\n }\n if (!ended) yield signal.aborted ? { type: 'finish', aborted: true } : { type: 'finish' }\n}\n\n/** The text of the last message of the user. */\nexport function lastUserText(thread: Thread): string {\n const message = [...thread.messages].reverse().find(m => m.role === 'user')\n return (message?.parts ?? []).map(part => (part.type === 'text' ? part.text : '')).join('')\n}\n\nexport interface JsonlTransportOptions extends Omit<StreamFromOptions, 'body' | 'format'> {\n /** The surface that the patches change. Default: `main`. */\n surfaceId?: string\n /** True when the endpoint writes text lines between the patches. */\n mixed?: boolean\n /** Makes the request body. Default: `{ prompt, spec? }`, as the example servers read it. */\n body?: (thread: Thread) => unknown\n}\n\n/**\n * A transport for an endpoint that streams JSONL spec patches, such as the example servers.\n * A line that is not a patch becomes a `stream-error` data part, and the run continues.\n */\nexport function jsonlTransport(\n input: string | URL,\n options: JsonlTransportOptions = {},\n): ChatTransport {\n const { surfaceId = 'main', mixed = false, body, headers, ...init } = options\n\n async function* run(thread: Thread, signal: AbortSignal): AsyncGenerator<AgentEvent> {\n yield { type: 'run-start' }\n const spec = findSurface(thread, surfaceId)?.spec\n const payload = body\n ? body(thread)\n : spec\n ? { prompt: lastUserText(thread), spec }\n : { prompt: lastUserText(thread) }\n const requestHeaders = new Headers(headers)\n requestHeaders.set('content-type', 'application/json')\n const source = streamFrom(input, {\n ...init,\n method: 'POST',\n headers: requestHeaders,\n body: JSON.stringify(payload),\n format: 'jsonl',\n })\n const stream = createSpecStream(spec ? { spec, mixed } : { mixed })\n const convert = (events: ReturnType<typeof stream.push>): AgentEvent[] =>\n events.map(event => {\n if (event.type === 'patch') return { type: 'spec', surfaceId, op: event.op }\n if (event.type === 'text') return { type: 'text', messageId: surfaceId, delta: event.text }\n const { type: _type, ...data } = event\n return { type: 'data', name: 'stream-error', data }\n })\n for await (const chunk of source(signal)) yield* convert(stream.push(chunk))\n yield* convert(stream.end())\n }\n\n return { send: (thread, signal) => guardRun(run(thread, signal), signal) }\n}\n","/** A response whose status is not in the 200 range. */\nexport class HttpError extends Error {\n override name = 'HttpError'\n constructor(\n readonly status: number,\n readonly statusText: string,\n readonly body: string,\n ) {\n super(`The request failed with status ${status}${statusText ? ` ${statusText}` : ''}`)\n }\n}\n\nexport interface SseEvent {\n event: string\n data: string\n id?: string\n}\n\n/** Decodes a byte stream to text chunks. It releases the stream when the reader stops. */\nexport async function* readText(stream: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const reader = stream.getReader()\n const decoder = new TextDecoder()\n let finished = false\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) {\n finished = true\n break\n }\n const text = decoder.decode(value, { stream: true })\n if (text !== '') yield text\n }\n const rest = decoder.decode()\n if (rest !== '') yield rest\n } finally {\n if (!finished) await reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n}\n\n/** Parses Server-Sent Events from text chunks. An event with no data does not go out. */\nexport async function* parseSse(chunks: AsyncIterable<string>): AsyncGenerator<SseEvent> {\n let buffer = ''\n let first = true\n let event = 'message'\n let id: string | undefined\n let data: string[] = []\n\n function* line(text: string): Generator<SseEvent> {\n if (text === '') {\n if (data.length > 0) {\n yield id === undefined\n ? { event, data: data.join('\\n') }\n : { event, data: data.join('\\n'), id }\n }\n event = 'message'\n id = undefined\n data = []\n return\n }\n if (text.startsWith(':')) return\n const colon = text.indexOf(':')\n const field = colon === -1 ? text : text.slice(0, colon)\n let value = colon === -1 ? '' : text.slice(colon + 1)\n if (value.startsWith(' ')) value = value.slice(1)\n if (field === 'data') data.push(value)\n else if (field === 'event') event = value\n else if (field === 'id') id = value\n }\n\n for await (let chunk of chunks) {\n if (first) {\n first = false\n if (chunk.startsWith('')) chunk = chunk.slice(1)\n }\n buffer += chunk\n for (;;) {\n const end = buffer.search(/\\r\\n|\\n|\\r/)\n // A lone \"\\r\" at the end of the buffer can be the first half of \"\\r\\n\".\n if (end === -1 || (buffer[end] === '\\r' && end === buffer.length - 1)) break\n const text = buffer.slice(0, end)\n buffer = buffer.slice(end + (buffer.startsWith('\\r\\n', end) ? 2 : 1))\n yield* line(text)\n }\n }\n if (buffer !== '') yield* line(buffer.replace(/\\r$/, ''))\n yield* line('')\n}\n\nexport interface StreamFromOptions extends Omit<RequestInit, 'signal'> {\n /** Default: the global `fetch`. */\n fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n /** `auto` reads SSE when the content type is `text/event-stream`. Default: `auto`. */\n format?: 'auto' | 'jsonl' | 'sse'\n}\n\n/**\n * Makes a stream source for an endpoint. Each call of the source makes one request. A JSONL\n * body goes out unchanged. An SSE body gives one line for each event, and stops at `[DONE]`.\n */\nexport function streamFrom(\n input: string | URL | Request,\n options: StreamFromOptions = {},\n): (signal: AbortSignal) => AsyncGenerator<string> {\n const { fetch: fetcher = globalThis.fetch, format = 'auto', ...init } = options\n\n return async function* (signal) {\n const response = await fetcher(input, { ...init, signal })\n if (!response.ok) {\n const text = await response.text().catch(() => '')\n throw new HttpError(response.status, response.statusText, text)\n }\n if (!response.body) return\n const type = response.headers.get('content-type') ?? ''\n const sse = format === 'sse' || (format === 'auto' && type.includes('text/event-stream'))\n if (!sse) {\n yield* readText(response.body)\n return\n }\n for await (const event of parseSse(readText(response.body))) {\n if (event.data === '[DONE]') return\n yield event.data + '\\n'\n }\n }\n}\n\nexport { guardRun, jsonlTransport, lastUserText, type JsonlTransportOptions } from './transport'\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type AgentEvent, type ChatTransport, type Thread } from '@ember-marquetry/core';
|
|
2
|
+
import { type StreamFromOptions } from './index';
|
|
3
|
+
/**
|
|
4
|
+
* Makes a run safe for a thread. An exception becomes an `error` event, an abort becomes an
|
|
5
|
+
* aborted `finish` event, and a stream that stops without `finish` or `error` gets `finish`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function guardRun(events: AsyncIterable<AgentEvent>, signal: AbortSignal): AsyncGenerator<AgentEvent>;
|
|
8
|
+
/** The text of the last message of the user. */
|
|
9
|
+
export declare function lastUserText(thread: Thread): string;
|
|
10
|
+
export interface JsonlTransportOptions extends Omit<StreamFromOptions, 'body' | 'format'> {
|
|
11
|
+
/** The surface that the patches change. Default: `main`. */
|
|
12
|
+
surfaceId?: string;
|
|
13
|
+
/** True when the endpoint writes text lines between the patches. */
|
|
14
|
+
mixed?: boolean;
|
|
15
|
+
/** Makes the request body. Default: `{ prompt, spec? }`, as the example servers read it. */
|
|
16
|
+
body?: (thread: Thread) => unknown;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A transport for an endpoint that streams JSONL spec patches, such as the example servers.
|
|
20
|
+
* A line that is not a patch becomes a `stream-error` data part, and the run continues.
|
|
21
|
+
*/
|
|
22
|
+
export declare function jsonlTransport(input: string | URL, options?: JsonlTransportOptions): ChatTransport;
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ember-marquetry/sse",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A plain fetch client for Marquetry: reads a JSONL or SSE endpoint and gives the stream to the spec compiler.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"generative-ui",
|
|
7
|
+
"genui",
|
|
8
|
+
"llm",
|
|
9
|
+
"ember",
|
|
10
|
+
"json-patch",
|
|
11
|
+
"streaming"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Joe Gaudet joe@joegaudet.com",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/joegaudet/ember-marquetry.git",
|
|
18
|
+
"directory": "packages/sse"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://joegaudet.com/ember-marquetry/",
|
|
21
|
+
"bugs": "https://github.com/joegaudet/ember-marquetry/issues",
|
|
22
|
+
"type": "module",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"CHANGELOG.md",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE.md",
|
|
36
|
+
"NOTICE"
|
|
37
|
+
],
|
|
38
|
+
"sideEffects": false,
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=22.12.0"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"@ember-marquetry/core": "1.0.0"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsup"
|
|
50
|
+
}
|
|
6
51
|
}
|