@alia.onl/server 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 +28 -0
- package/LICENSE +202 -0
- package/NOTICE +15 -0
- package/README.md +135 -0
- package/dist/index.cjs +291 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +236 -0
- package/dist/index.d.ts +236 -0
- package/dist/index.js +283 -0
- package/dist/index.js.map +1 -0
- package/package.json +51 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# @alia.onl/server
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
### A server-side client, so no consumer hand-parses Alia's stream again
|
|
6
|
+
|
|
7
|
+
`@alia.onl/sdk` is a client SDK — React, React Native, hooks, a browser stream
|
|
8
|
+
reader — and there was nothing for the other side. Every product whose backend
|
|
9
|
+
calls Alia wrote its own SSE parser, and each one got a different subset of the
|
|
10
|
+
wire right.
|
|
11
|
+
|
|
12
|
+
The expensive part was never the framing. It was that Alia writes an error INTO
|
|
13
|
+
the stream (`{"error":{"code":"agent_unavailable"}}`, followed by `[DONE]`), and
|
|
14
|
+
a parser written against text deltas has no branch for it: it either throws
|
|
15
|
+
something that names nothing, or skips the frame and reports an empty answer.
|
|
16
|
+
Homiio shipped both failures in one week, and the second one was invisible for
|
|
17
|
+
hours.
|
|
18
|
+
|
|
19
|
+
So this package makes every shape on that wire a typed event — `text`,
|
|
20
|
+
`reasoning`, `event`, `finish`, `error`, `done` — over a closed union, and owns
|
|
21
|
+
content-type checking, SSE framing, `[DONE]`, abort, and a typed
|
|
22
|
+
`AliaRequestError` for a non-2xx answer. A consumer can be wrong about what to
|
|
23
|
+
DO with an error; it can no longer fail to see one.
|
|
24
|
+
|
|
25
|
+
Text deltas are yielded verbatim and never merged: a consumer reassembling
|
|
26
|
+
markers that span chunk boundaries depends on the exact bytes.
|
|
27
|
+
|
|
28
|
+
Node 22+, no dependencies, ESM and CommonJS.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
=============================================================================
|
|
2
|
+
NOTICE
|
|
3
|
+
@alia.onl/server
|
|
4
|
+
Copyright (c) 2026-present The Oxy Collective, Inc.
|
|
5
|
+
=============================================================================
|
|
6
|
+
|
|
7
|
+
This product is licensed under the Apache License, Version 2.0.
|
|
8
|
+
See the LICENSE file in this directory.
|
|
9
|
+
|
|
10
|
+
-----------------------------------------------------------------------------
|
|
11
|
+
THIRD PARTY COMPONENTS
|
|
12
|
+
-----------------------------------------------------------------------------
|
|
13
|
+
|
|
14
|
+
This package contains no third party source. Its dependencies are resolved and
|
|
15
|
+
installed by the package manager and remain governed by their own licenses.
|
package/README.md
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# @alia.onl/server
|
|
2
|
+
|
|
3
|
+
Alia's client for the **backend** that calls Alia on a person's behalf.
|
|
4
|
+
|
|
5
|
+
`@alia.onl/sdk` is the client SDK: React and React Native components, hooks, a
|
|
6
|
+
browser-side stream reader. This package is the other half — no React, no DOM
|
|
7
|
+
beyond `fetch` and `ReadableStream`, no dependencies, Node 22+. It POSTs one
|
|
8
|
+
turn to `/v1/chat/completions` and gives you a typed async iterable of what Alia
|
|
9
|
+
wrote.
|
|
10
|
+
|
|
11
|
+
## Why it exists
|
|
12
|
+
|
|
13
|
+
Alia writes five different things on that stream:
|
|
14
|
+
|
|
15
|
+
| On the wire | What it is |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `data: {…choices[0].delta.content}` | an assistant text delta |
|
|
18
|
+
| `data: {…choices[0].delta.reasoning}` | a reasoning delta |
|
|
19
|
+
| `event: alia.tool_result` + `data: {…}` | a named product event |
|
|
20
|
+
| `data: {…, "alia_meta": {"synthetic": true}}` | a stand-in message written after a provider died |
|
|
21
|
+
| `data: {"error":{"code":"agent_unavailable"}}` | Alia refusing, mid-stream |
|
|
22
|
+
| `data: [DONE]` | the terminator |
|
|
23
|
+
|
|
24
|
+
Every consumer that called Alia from a server wrote its own reader for that, and
|
|
25
|
+
each got a different subset right. The expensive one is the error payload: a
|
|
26
|
+
reader with no branch for it either throws a bare 502 that names nothing, or —
|
|
27
|
+
worse — skips the frame it does not recognise and reports an empty answer. Both
|
|
28
|
+
happened in production. This package makes that shape a typed `error` event
|
|
29
|
+
carrying the server's own `code`, so a consumer cannot fail to see it.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
bun add @alia.onl/server # or npm / pnpm / yarn
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Use
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { AliaServerClient } from '@alia.onl/server';
|
|
41
|
+
|
|
42
|
+
const alia = new AliaServerClient({
|
|
43
|
+
baseUrl: 'https://api.alia.onl',
|
|
44
|
+
// Your product's Oxy service token — the bearer Oxy bills (ADR 0007).
|
|
45
|
+
token: () => getMyServiceToken(),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const stream = await alia.stream(
|
|
49
|
+
{ agentId: MY_AGENT_ID, messages: [{ role: 'user', content: 'Hola' }] },
|
|
50
|
+
{
|
|
51
|
+
signal: request.signal,
|
|
52
|
+
// Minted per turn: Oxy consumes each assertion on first use.
|
|
53
|
+
headers: { 'X-Oxy-Requester-Assertion': await mintAssertion() },
|
|
54
|
+
},
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
for await (const event of stream) {
|
|
58
|
+
switch (event.type) {
|
|
59
|
+
case 'text': process.stdout.write(event.text); break;
|
|
60
|
+
case 'reasoning': break;
|
|
61
|
+
case 'event': onProductEvent(event.event, event.data); break;
|
|
62
|
+
case 'finish': break;
|
|
63
|
+
case 'error': throw new MyChatError(event.code); // the SERVER's code
|
|
64
|
+
case 'done': break;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The `switch` above is exhaustive: `AliaStreamEvent` is a closed union, so a
|
|
70
|
+
`default: never` branch makes a new event kind a compile error rather than a
|
|
71
|
+
silently dropped frame.
|
|
72
|
+
|
|
73
|
+
### What it owns
|
|
74
|
+
|
|
75
|
+
- **Content-type checking.** A 200 that is not `text/event-stream` is an
|
|
76
|
+
`AliaStreamError('not_event_stream')`, never a buffered fallback parse.
|
|
77
|
+
- **SSE framing.** Multi-line `data:`, comment frames, CRLF, `event: message`
|
|
78
|
+
as SSE's default name, and byte boundaries falling anywhere — including
|
|
79
|
+
mid-UTF-8. **Text deltas are yielded verbatim and never merged**, because a
|
|
80
|
+
consumer reassembling markers across chunks depends on the exact bytes.
|
|
81
|
+
- **`[DONE]`.** Iteration ends on it. A body that ends without it is an
|
|
82
|
+
`AliaStreamError('truncated')` — a truncated turn must not read as a short one.
|
|
83
|
+
- **Error chunks**, as `error` events carrying `code`, `message`, `type`, `param`.
|
|
84
|
+
- **Abort.** Pass an `AbortSignal`; the request and the body read both stop, and
|
|
85
|
+
leaving the `for await` early cancels the body.
|
|
86
|
+
- **Non-2xx**, as `AliaRequestError` with `status` and, when the body carried
|
|
87
|
+
one, `code`. The body's prose is deliberately not retained.
|
|
88
|
+
|
|
89
|
+
### Errors
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import { AliaRequestError, AliaStreamError } from '@alia.onl/server';
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`AliaStreamError` carries `failure` (one of `not_event_stream`, `no_body`,
|
|
96
|
+
`malformed_json`, `unexpected_chunk`, `choice_without_delta`,
|
|
97
|
+
`content_not_string`, `truncated`, `oversized`) and `shape` — the offending
|
|
98
|
+
chunk's keys, its `choices` length or type, and any `error.code`. `shape` holds
|
|
99
|
+
no content: not the assistant's text, not the person's prompt. Log it whole.
|
|
100
|
+
|
|
101
|
+
`AliaRequestError` carries `status` and `code`.
|
|
102
|
+
|
|
103
|
+
An abort throws an `Error` whose `name` is `AbortError`, as `fetch`'s does.
|
|
104
|
+
|
|
105
|
+
### Bring your own request
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { readAliaEventStream } from '@alia.onl/server';
|
|
109
|
+
|
|
110
|
+
for await (const event of readAliaEventStream(response.body!, { signal })) { … }
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Which credential
|
|
114
|
+
|
|
115
|
+
Alia receives the calling product's **Oxy service token** as the bearer, and —
|
|
116
|
+
when the turn is for a signed-in person — a one-use `X-Oxy-Requester-Assertion`
|
|
117
|
+
minted by Oxy for that person. The person's own bearer is never forwarded.
|
|
118
|
+
`headers` accepts a function precisely because the assertion cannot be cached.
|
|
119
|
+
|
|
120
|
+
## Tests
|
|
121
|
+
|
|
122
|
+
The test fixtures are not hand-written chunks. They are produced by the API's
|
|
123
|
+
own SSE writers — `packages/api/src/lib/streaming-helpers.ts`,
|
|
124
|
+
`.../chat/sse-writer.ts`, `.../sse-emitter.ts` — imported directly, so a change
|
|
125
|
+
to what Alia puts on the wire fails this package's tests in the same commit.
|
|
126
|
+
|
|
127
|
+
```sh
|
|
128
|
+
bun run typecheck
|
|
129
|
+
bun run test
|
|
130
|
+
bun run build
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Licence
|
|
134
|
+
|
|
135
|
+
Apache-2.0. See `LICENSE` and `NOTICE`.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/errors.ts
|
|
4
|
+
var AliaStreamError = class extends Error {
|
|
5
|
+
failure;
|
|
6
|
+
shape;
|
|
7
|
+
constructor(failure, shape = {}) {
|
|
8
|
+
super(`Alia stream could not be read: ${failure}`);
|
|
9
|
+
this.name = "AliaStreamError";
|
|
10
|
+
this.failure = failure;
|
|
11
|
+
this.shape = shape;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
var AliaRequestError = class extends Error {
|
|
15
|
+
status;
|
|
16
|
+
code;
|
|
17
|
+
constructor(status, code = null) {
|
|
18
|
+
super(`Alia responded ${status}`);
|
|
19
|
+
this.name = "AliaRequestError";
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.code = code;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
var AliaAbortError = class extends Error {
|
|
25
|
+
constructor(message = "The Alia stream was aborted.") {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "AbortError";
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
var MAX_SHAPE_KEYS = 12;
|
|
31
|
+
function isRecord(value) {
|
|
32
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
33
|
+
}
|
|
34
|
+
function describeChunk(value, event) {
|
|
35
|
+
const named = {} ;
|
|
36
|
+
if (!isRecord(value)) return { ...named, valueType: value === null ? "null" : typeof value };
|
|
37
|
+
const error = isRecord(value.error) ? value.error : void 0;
|
|
38
|
+
const errorCode = error === void 0 ? void 0 : typeof error.code === "string" ? error.code : typeof error.type === "string" ? error.type : void 0;
|
|
39
|
+
return {
|
|
40
|
+
...named,
|
|
41
|
+
keys: Object.keys(value).slice(0, MAX_SHAPE_KEYS),
|
|
42
|
+
choices: Array.isArray(value.choices) ? value.choices.length : typeof value.choices,
|
|
43
|
+
...errorCode === void 0 ? {} : { errorCode }
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/stream.ts
|
|
48
|
+
var MAX_STREAM_BYTES = 32 * 1024 * 1024;
|
|
49
|
+
var MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
50
|
+
var DEFAULT_EVENT_NAME = "message";
|
|
51
|
+
function asOptionalRecord(value) {
|
|
52
|
+
return isRecord(value) ? value : void 0;
|
|
53
|
+
}
|
|
54
|
+
function asStringOrNull(value) {
|
|
55
|
+
return typeof value === "string" ? value : null;
|
|
56
|
+
}
|
|
57
|
+
function* eventsFromChunk(value, shape) {
|
|
58
|
+
if (!isRecord(value)) throw new AliaStreamError("unexpected_chunk", shape());
|
|
59
|
+
if (isRecord(value.error)) {
|
|
60
|
+
const error = value.error;
|
|
61
|
+
yield {
|
|
62
|
+
type: "error",
|
|
63
|
+
code: asStringOrNull(error.code),
|
|
64
|
+
message: typeof error.message === "string" ? error.message : "Alia ended the stream with an error.",
|
|
65
|
+
errorType: asStringOrNull(error.type),
|
|
66
|
+
param: asStringOrNull(error.param)
|
|
67
|
+
};
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (!Array.isArray(value.choices)) throw new AliaStreamError("unexpected_chunk", shape());
|
|
71
|
+
const meta = asOptionalRecord(value.alia_meta);
|
|
72
|
+
for (const rawChoice of value.choices) {
|
|
73
|
+
if (!isRecord(rawChoice) || !isRecord(rawChoice.delta)) {
|
|
74
|
+
throw new AliaStreamError("choice_without_delta", shape());
|
|
75
|
+
}
|
|
76
|
+
const delta = rawChoice.delta;
|
|
77
|
+
if (delta.content !== void 0 && delta.content !== null) {
|
|
78
|
+
if (typeof delta.content !== "string") throw new AliaStreamError("content_not_string", shape());
|
|
79
|
+
yield { type: "text", text: delta.content, ...meta === void 0 ? {} : { meta } };
|
|
80
|
+
}
|
|
81
|
+
if (typeof delta.reasoning === "string" && delta.reasoning !== "") {
|
|
82
|
+
yield { type: "reasoning", text: delta.reasoning };
|
|
83
|
+
}
|
|
84
|
+
if (typeof rawChoice.finish_reason === "string") {
|
|
85
|
+
yield { type: "finish", reason: rawChoice.finish_reason, ...meta === void 0 ? {} : { meta } };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function* readAliaEventStream(body, options = {}) {
|
|
90
|
+
const { signal } = options;
|
|
91
|
+
const reader = body.getReader();
|
|
92
|
+
const onAbort = () => {
|
|
93
|
+
void reader.cancel().catch(() => void 0);
|
|
94
|
+
};
|
|
95
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
96
|
+
const decoder = new TextDecoder("utf-8");
|
|
97
|
+
let buffer = "";
|
|
98
|
+
let eventName = "";
|
|
99
|
+
let dataLines = [];
|
|
100
|
+
let totalBytes = 0;
|
|
101
|
+
let sawDone = false;
|
|
102
|
+
const takeFrame = () => {
|
|
103
|
+
const event = eventName;
|
|
104
|
+
const lines = dataLines;
|
|
105
|
+
eventName = "";
|
|
106
|
+
dataLines = [];
|
|
107
|
+
if (lines.length === 0) return null;
|
|
108
|
+
return { event, data: lines.join("\n") };
|
|
109
|
+
};
|
|
110
|
+
function* dispatch(frame) {
|
|
111
|
+
const named = frame.event !== "" && frame.event !== DEFAULT_EVENT_NAME;
|
|
112
|
+
if (!named && frame.data === "[DONE]") {
|
|
113
|
+
sawDone = true;
|
|
114
|
+
yield { type: "done" };
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
let value;
|
|
118
|
+
try {
|
|
119
|
+
value = JSON.parse(frame.data);
|
|
120
|
+
} catch {
|
|
121
|
+
throw new AliaStreamError("malformed_json", { ...named ? { event: frame.event } : {} });
|
|
122
|
+
}
|
|
123
|
+
if (named) {
|
|
124
|
+
yield { type: "event", event: frame.event, data: value };
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
yield* eventsFromChunk(value, () => describeChunk(value));
|
|
128
|
+
}
|
|
129
|
+
const consumeLine = function* (rawLine) {
|
|
130
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
131
|
+
if (line === "") {
|
|
132
|
+
const frame = takeFrame();
|
|
133
|
+
if (frame !== null) yield* dispatch(frame);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (line.startsWith(":")) return;
|
|
137
|
+
const separator = line.indexOf(":");
|
|
138
|
+
const field = separator === -1 ? line : line.slice(0, separator);
|
|
139
|
+
let value = separator === -1 ? "" : line.slice(separator + 1);
|
|
140
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
141
|
+
if (field === "event") eventName = value;
|
|
142
|
+
else if (field === "data") dataLines.push(value);
|
|
143
|
+
};
|
|
144
|
+
try {
|
|
145
|
+
for (; ; ) {
|
|
146
|
+
if (signal?.aborted) throw new AliaAbortError();
|
|
147
|
+
const { done, value } = await reader.read();
|
|
148
|
+
if (signal?.aborted) throw new AliaAbortError();
|
|
149
|
+
if (value !== void 0) {
|
|
150
|
+
totalBytes += value.byteLength;
|
|
151
|
+
if (totalBytes > MAX_STREAM_BYTES) throw new AliaStreamError("oversized");
|
|
152
|
+
}
|
|
153
|
+
buffer += decoder.decode(value, { stream: !done });
|
|
154
|
+
let newline = buffer.indexOf("\n");
|
|
155
|
+
while (newline !== -1) {
|
|
156
|
+
const line = buffer.slice(0, newline);
|
|
157
|
+
buffer = buffer.slice(newline + 1);
|
|
158
|
+
yield* consumeLine(line);
|
|
159
|
+
if (sawDone) return;
|
|
160
|
+
newline = buffer.indexOf("\n");
|
|
161
|
+
}
|
|
162
|
+
if (buffer.length > MAX_FRAME_BYTES) throw new AliaStreamError("oversized");
|
|
163
|
+
if (done) break;
|
|
164
|
+
}
|
|
165
|
+
if (buffer !== "") {
|
|
166
|
+
yield* consumeLine(buffer);
|
|
167
|
+
if (sawDone) return;
|
|
168
|
+
}
|
|
169
|
+
const trailing = takeFrame();
|
|
170
|
+
if (trailing !== null) {
|
|
171
|
+
yield* dispatch(trailing);
|
|
172
|
+
if (sawDone) return;
|
|
173
|
+
}
|
|
174
|
+
throw new AliaStreamError("truncated");
|
|
175
|
+
} finally {
|
|
176
|
+
signal?.removeEventListener("abort", onAbort);
|
|
177
|
+
await reader.cancel().catch(() => void 0);
|
|
178
|
+
reader.releaseLock();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// src/client.ts
|
|
183
|
+
var ALIA_API_URL = "https://api.alia.onl";
|
|
184
|
+
var CHAT_COMPLETIONS_PATH = "/v1/chat/completions";
|
|
185
|
+
var MAX_ERROR_BODY_BYTES = 4096;
|
|
186
|
+
async function resolve(source) {
|
|
187
|
+
return typeof source === "function" ? await source() : source;
|
|
188
|
+
}
|
|
189
|
+
async function codeFromErrorBody(response) {
|
|
190
|
+
try {
|
|
191
|
+
const reader = response.body?.getReader();
|
|
192
|
+
if (reader === void 0) return null;
|
|
193
|
+
const decoder = new TextDecoder("utf-8");
|
|
194
|
+
let text = "";
|
|
195
|
+
try {
|
|
196
|
+
while (text.length < MAX_ERROR_BODY_BYTES) {
|
|
197
|
+
const { done, value: value2 } = await reader.read();
|
|
198
|
+
if (done) break;
|
|
199
|
+
text += decoder.decode(value2, { stream: true });
|
|
200
|
+
}
|
|
201
|
+
} finally {
|
|
202
|
+
await reader.cancel().catch(() => void 0);
|
|
203
|
+
}
|
|
204
|
+
const value = JSON.parse(text);
|
|
205
|
+
if (!isRecord(value)) return null;
|
|
206
|
+
if (typeof value.code === "string") return value.code;
|
|
207
|
+
if (isRecord(value.error) && typeof value.error.code === "string") return value.error.code;
|
|
208
|
+
return null;
|
|
209
|
+
} catch {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
var AliaServerClient = class {
|
|
214
|
+
#baseUrl;
|
|
215
|
+
#path;
|
|
216
|
+
#token;
|
|
217
|
+
#headers;
|
|
218
|
+
#fetch;
|
|
219
|
+
constructor(options = {}) {
|
|
220
|
+
this.#baseUrl = (options.baseUrl ?? ALIA_API_URL).replace(/\/+$/, "");
|
|
221
|
+
this.#path = options.path ?? CHAT_COMPLETIONS_PATH;
|
|
222
|
+
this.#token = options.token;
|
|
223
|
+
this.#headers = options.headers;
|
|
224
|
+
this.#fetch = options.fetch ?? fetch;
|
|
225
|
+
}
|
|
226
|
+
/** The absolute URL this client posts to. */
|
|
227
|
+
get url() {
|
|
228
|
+
return `${this.#baseUrl}${this.#path}`;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Start one turn.
|
|
232
|
+
*
|
|
233
|
+
* Resolves once Alia has answered with a 2xx `text/event-stream`; the events
|
|
234
|
+
* arrive as they are written. Throws {@link AliaRequestError} for a non-2xx
|
|
235
|
+
* answer and {@link AliaStreamError} when the response is not a stream this
|
|
236
|
+
* client can read.
|
|
237
|
+
*/
|
|
238
|
+
async stream(request, init = {}) {
|
|
239
|
+
const [token, headers] = await Promise.all([
|
|
240
|
+
init.token === void 0 ? resolve(this.#token) : init.token,
|
|
241
|
+
resolve(this.#headers)
|
|
242
|
+
]);
|
|
243
|
+
const response = await this.#fetch(this.url, {
|
|
244
|
+
method: "POST",
|
|
245
|
+
headers: {
|
|
246
|
+
"Content-Type": "application/json",
|
|
247
|
+
Accept: "text/event-stream",
|
|
248
|
+
...token === void 0 ? {} : { Authorization: `Bearer ${token}` },
|
|
249
|
+
...headers,
|
|
250
|
+
...init.headers
|
|
251
|
+
},
|
|
252
|
+
body: JSON.stringify(buildBody(request)),
|
|
253
|
+
...init.signal === void 0 ? {} : { signal: init.signal }
|
|
254
|
+
});
|
|
255
|
+
if (!response.ok) {
|
|
256
|
+
throw new AliaRequestError(response.status, await codeFromErrorBody(response));
|
|
257
|
+
}
|
|
258
|
+
const mime = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
259
|
+
if (mime !== "text/event-stream") {
|
|
260
|
+
await response.body?.cancel().catch(() => void 0);
|
|
261
|
+
throw new AliaStreamError("not_event_stream", { valueType: mime ?? "none" });
|
|
262
|
+
}
|
|
263
|
+
if (!response.body) throw new AliaStreamError("no_body");
|
|
264
|
+
return readAliaEventStream(response.body, {
|
|
265
|
+
...init.signal === void 0 ? {} : { signal: init.signal }
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
function buildBody(request) {
|
|
270
|
+
const { messages, extra, ...rest } = request;
|
|
271
|
+
const body = { ...extra };
|
|
272
|
+
for (const [key, value] of Object.entries(rest)) {
|
|
273
|
+
if (value !== void 0) body[key] = value;
|
|
274
|
+
}
|
|
275
|
+
body.messages = messages;
|
|
276
|
+
body.stream = true;
|
|
277
|
+
return body;
|
|
278
|
+
}
|
|
279
|
+
function createAliaServerClient(options = {}) {
|
|
280
|
+
return new AliaServerClient(options);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
exports.ALIA_API_URL = ALIA_API_URL;
|
|
284
|
+
exports.AliaAbortError = AliaAbortError;
|
|
285
|
+
exports.AliaRequestError = AliaRequestError;
|
|
286
|
+
exports.AliaServerClient = AliaServerClient;
|
|
287
|
+
exports.AliaStreamError = AliaStreamError;
|
|
288
|
+
exports.createAliaServerClient = createAliaServerClient;
|
|
289
|
+
exports.readAliaEventStream = readAliaEventStream;
|
|
290
|
+
//# sourceMappingURL=index.cjs.map
|
|
291
|
+
//# sourceMappingURL=index.cjs.map
|