@cadenya/cadenya 0.97.0 → 0.98.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 +9 -0
- package/README.md +18 -0
- package/client.d.mts +2 -2
- package/client.d.mts.map +1 -1
- package/client.d.ts +2 -2
- package/client.d.ts.map +1 -1
- package/core/streaming.d.mts +33 -0
- package/core/streaming.d.mts.map +1 -0
- package/core/streaming.d.ts +33 -0
- package/core/streaming.d.ts.map +1 -0
- package/core/streaming.js +263 -0
- package/core/streaming.js.map +1 -0
- package/core/streaming.mjs +258 -0
- package/core/streaming.mjs.map +1 -0
- package/internal/decoders/line.d.mts +17 -0
- package/internal/decoders/line.d.mts.map +1 -0
- package/internal/decoders/line.d.ts +17 -0
- package/internal/decoders/line.d.ts.map +1 -0
- package/internal/decoders/line.js +113 -0
- package/internal/decoders/line.js.map +1 -0
- package/internal/decoders/line.mjs +108 -0
- package/internal/decoders/line.mjs.map +1 -0
- package/internal/parse.d.mts.map +1 -1
- package/internal/parse.d.ts.map +1 -1
- package/internal/parse.js +10 -0
- package/internal/parse.js.map +1 -1
- package/internal/parse.mjs +10 -0
- package/internal/parse.mjs.map +1 -1
- package/internal/request-options.d.mts +2 -0
- package/internal/request-options.d.mts.map +1 -1
- package/internal/request-options.d.ts +2 -0
- package/internal/request-options.d.ts.map +1 -1
- package/internal/request-options.js.map +1 -1
- package/internal/request-options.mjs.map +1 -1
- package/internal/tslib.js +17 -17
- package/package.json +11 -1
- package/resources/ai-provider-keys.d.mts +8 -101
- package/resources/ai-provider-keys.d.mts.map +1 -1
- package/resources/ai-provider-keys.d.ts +8 -101
- package/resources/ai-provider-keys.d.ts.map +1 -1
- package/resources/index.d.mts +1 -1
- package/resources/index.d.mts.map +1 -1
- package/resources/index.d.ts +1 -1
- package/resources/index.d.ts.map +1 -1
- package/resources/objectives/index.d.mts +1 -1
- package/resources/objectives/index.d.mts.map +1 -1
- package/resources/objectives/index.d.ts +1 -1
- package/resources/objectives/index.d.ts.map +1 -1
- package/resources/objectives/objectives.d.mts +23 -37
- package/resources/objectives/objectives.d.mts.map +1 -1
- package/resources/objectives/objectives.d.ts +23 -37
- package/resources/objectives/objectives.d.ts.map +1 -1
- package/resources/objectives/objectives.js +12 -0
- package/resources/objectives/objectives.js.map +1 -1
- package/resources/objectives/objectives.mjs +12 -0
- package/resources/objectives/objectives.mjs.map +1 -1
- package/resources/webhooks.d.mts +2 -26
- package/resources/webhooks.d.mts.map +1 -1
- package/resources/webhooks.d.ts +2 -26
- package/resources/webhooks.d.ts.map +1 -1
- package/src/client.ts +6 -6
- package/src/core/streaming.ts +315 -0
- package/src/internal/decoders/line.ts +135 -0
- package/src/internal/parse.ts +14 -0
- package/src/internal/request-options.ts +2 -0
- package/src/resources/ai-provider-keys.ts +8 -116
- package/src/resources/index.ts +3 -3
- package/src/resources/objectives/index.ts +3 -3
- package/src/resources/objectives/objectives.ts +44 -52
- package/src/resources/webhooks.ts +2 -34
- package/src/streaming.ts +2 -0
- package/src/version.ts +1 -1
- package/streaming.d.mts +3 -0
- package/streaming.d.mts.map +1 -0
- package/streaming.d.ts +3 -0
- package/streaming.d.ts.map +1 -0
- package/streaming.js +6 -0
- package/streaming.js.map +1 -0
- package/streaming.mjs +3 -0
- package/streaming.mjs.map +1 -0
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { CadenyaError } from './error';
|
|
2
|
+
import { type ReadableStream } from '../internal/shim-types';
|
|
3
|
+
import { makeReadableStream } from '../internal/shims';
|
|
4
|
+
import { findDoubleNewlineIndex, LineDecoder } from '../internal/decoders/line';
|
|
5
|
+
import { ReadableStreamToAsyncIterable } from '../internal/shims';
|
|
6
|
+
import { isAbortError } from '../internal/errors';
|
|
7
|
+
import { encodeUTF8 } from '../internal/utils/bytes';
|
|
8
|
+
import { loggerFor } from '../internal/utils/log';
|
|
9
|
+
import type { Cadenya } from '../client';
|
|
10
|
+
|
|
11
|
+
type Bytes = string | ArrayBuffer | Uint8Array | null | undefined;
|
|
12
|
+
|
|
13
|
+
export type ServerSentEvent = {
|
|
14
|
+
event: string | null;
|
|
15
|
+
data: string;
|
|
16
|
+
raw: string[];
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export class Stream<Item> implements AsyncIterable<Item> {
|
|
20
|
+
controller: AbortController;
|
|
21
|
+
#client: Cadenya | undefined;
|
|
22
|
+
|
|
23
|
+
constructor(
|
|
24
|
+
private iterator: () => AsyncIterator<Item>,
|
|
25
|
+
controller: AbortController,
|
|
26
|
+
client?: Cadenya,
|
|
27
|
+
) {
|
|
28
|
+
this.controller = controller;
|
|
29
|
+
this.#client = client;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
static fromSSEResponse<Item>(
|
|
33
|
+
response: Response,
|
|
34
|
+
controller: AbortController,
|
|
35
|
+
client?: Cadenya,
|
|
36
|
+
): Stream<Item> {
|
|
37
|
+
let consumed = false;
|
|
38
|
+
const logger = client ? loggerFor(client) : console;
|
|
39
|
+
|
|
40
|
+
async function* iterator(): AsyncIterator<Item, any, undefined> {
|
|
41
|
+
if (consumed) {
|
|
42
|
+
throw new CadenyaError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
|
|
43
|
+
}
|
|
44
|
+
consumed = true;
|
|
45
|
+
let done = false;
|
|
46
|
+
try {
|
|
47
|
+
for await (const sse of _iterSSEMessages(response, controller)) {
|
|
48
|
+
try {
|
|
49
|
+
yield JSON.parse(sse.data) as Item;
|
|
50
|
+
} catch (e) {
|
|
51
|
+
logger.error(`Could not parse message into JSON:`, sse.data);
|
|
52
|
+
logger.error(`From chunk:`, sse.raw);
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
done = true;
|
|
57
|
+
} catch (e) {
|
|
58
|
+
// If the user calls `stream.controller.abort()`, we should exit without throwing.
|
|
59
|
+
if (isAbortError(e)) return;
|
|
60
|
+
throw e;
|
|
61
|
+
} finally {
|
|
62
|
+
// If the user `break`s, abort the ongoing request.
|
|
63
|
+
if (!done) controller.abort();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return new Stream(iterator, controller, client);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Generates a Stream from a newline-separated ReadableStream
|
|
72
|
+
* where each item is a JSON value.
|
|
73
|
+
*/
|
|
74
|
+
static fromReadableStream<Item>(
|
|
75
|
+
readableStream: ReadableStream,
|
|
76
|
+
controller: AbortController,
|
|
77
|
+
client?: Cadenya,
|
|
78
|
+
): Stream<Item> {
|
|
79
|
+
let consumed = false;
|
|
80
|
+
|
|
81
|
+
async function* iterLines(): AsyncGenerator<string, void, unknown> {
|
|
82
|
+
const lineDecoder = new LineDecoder();
|
|
83
|
+
|
|
84
|
+
const iter = ReadableStreamToAsyncIterable<Bytes>(readableStream);
|
|
85
|
+
for await (const chunk of iter) {
|
|
86
|
+
for (const line of lineDecoder.decode(chunk)) {
|
|
87
|
+
yield line;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
for (const line of lineDecoder.flush()) {
|
|
92
|
+
yield line;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function* iterator(): AsyncIterator<Item, any, undefined> {
|
|
97
|
+
if (consumed) {
|
|
98
|
+
throw new CadenyaError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
|
|
99
|
+
}
|
|
100
|
+
consumed = true;
|
|
101
|
+
let done = false;
|
|
102
|
+
try {
|
|
103
|
+
for await (const line of iterLines()) {
|
|
104
|
+
if (done) continue;
|
|
105
|
+
if (line) yield JSON.parse(line) as Item;
|
|
106
|
+
}
|
|
107
|
+
done = true;
|
|
108
|
+
} catch (e) {
|
|
109
|
+
// If the user calls `stream.controller.abort()`, we should exit without throwing.
|
|
110
|
+
if (isAbortError(e)) return;
|
|
111
|
+
throw e;
|
|
112
|
+
} finally {
|
|
113
|
+
// If the user `break`s, abort the ongoing request.
|
|
114
|
+
if (!done) controller.abort();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return new Stream(iterator, controller, client);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
[Symbol.asyncIterator](): AsyncIterator<Item> {
|
|
122
|
+
return this.iterator();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Splits the stream into two streams which can be
|
|
127
|
+
* independently read from at different speeds.
|
|
128
|
+
*/
|
|
129
|
+
tee(): [Stream<Item>, Stream<Item>] {
|
|
130
|
+
const left: Array<Promise<IteratorResult<Item>>> = [];
|
|
131
|
+
const right: Array<Promise<IteratorResult<Item>>> = [];
|
|
132
|
+
const iterator = this.iterator();
|
|
133
|
+
|
|
134
|
+
const teeIterator = (queue: Array<Promise<IteratorResult<Item>>>): AsyncIterator<Item> => {
|
|
135
|
+
return {
|
|
136
|
+
next: () => {
|
|
137
|
+
if (queue.length === 0) {
|
|
138
|
+
const result = iterator.next();
|
|
139
|
+
left.push(result);
|
|
140
|
+
right.push(result);
|
|
141
|
+
}
|
|
142
|
+
return queue.shift()!;
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
return [
|
|
148
|
+
new Stream(() => teeIterator(left), this.controller, this.#client),
|
|
149
|
+
new Stream(() => teeIterator(right), this.controller, this.#client),
|
|
150
|
+
];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Converts this stream to a newline-separated ReadableStream of
|
|
155
|
+
* JSON stringified values in the stream
|
|
156
|
+
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
|
|
157
|
+
*/
|
|
158
|
+
toReadableStream(): ReadableStream {
|
|
159
|
+
const self = this;
|
|
160
|
+
let iter: AsyncIterator<Item>;
|
|
161
|
+
|
|
162
|
+
return makeReadableStream({
|
|
163
|
+
async start() {
|
|
164
|
+
iter = self[Symbol.asyncIterator]();
|
|
165
|
+
},
|
|
166
|
+
async pull(ctrl: any) {
|
|
167
|
+
try {
|
|
168
|
+
const { value, done } = await iter.next();
|
|
169
|
+
if (done) return ctrl.close();
|
|
170
|
+
|
|
171
|
+
const bytes = encodeUTF8(JSON.stringify(value) + '\n');
|
|
172
|
+
|
|
173
|
+
ctrl.enqueue(bytes);
|
|
174
|
+
} catch (err) {
|
|
175
|
+
ctrl.error(err);
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
async cancel() {
|
|
179
|
+
await iter.return?.();
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export async function* _iterSSEMessages(
|
|
186
|
+
response: Response,
|
|
187
|
+
controller: AbortController,
|
|
188
|
+
): AsyncGenerator<ServerSentEvent, void, unknown> {
|
|
189
|
+
if (!response.body) {
|
|
190
|
+
controller.abort();
|
|
191
|
+
if (
|
|
192
|
+
typeof (globalThis as any).navigator !== 'undefined' &&
|
|
193
|
+
(globalThis as any).navigator.product === 'ReactNative'
|
|
194
|
+
) {
|
|
195
|
+
throw new CadenyaError(
|
|
196
|
+
`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
throw new CadenyaError(`Attempted to iterate over a response with no body`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const sseDecoder = new SSEDecoder();
|
|
203
|
+
const lineDecoder = new LineDecoder();
|
|
204
|
+
|
|
205
|
+
const iter = ReadableStreamToAsyncIterable<Bytes>(response.body);
|
|
206
|
+
for await (const sseChunk of iterSSEChunks(iter)) {
|
|
207
|
+
for (const line of lineDecoder.decode(sseChunk)) {
|
|
208
|
+
const sse = sseDecoder.decode(line);
|
|
209
|
+
if (sse) yield sse;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
for (const line of lineDecoder.flush()) {
|
|
214
|
+
const sse = sseDecoder.decode(line);
|
|
215
|
+
if (sse) yield sse;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Given an async iterable iterator, iterates over it and yields full
|
|
221
|
+
* SSE chunks, i.e. yields when a double new-line is encountered.
|
|
222
|
+
*/
|
|
223
|
+
async function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {
|
|
224
|
+
let data = new Uint8Array();
|
|
225
|
+
|
|
226
|
+
for await (const chunk of iterator) {
|
|
227
|
+
if (chunk == null) {
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const binaryChunk =
|
|
232
|
+
chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
|
|
233
|
+
: typeof chunk === 'string' ? encodeUTF8(chunk)
|
|
234
|
+
: chunk;
|
|
235
|
+
|
|
236
|
+
let newData = new Uint8Array(data.length + binaryChunk.length);
|
|
237
|
+
newData.set(data);
|
|
238
|
+
newData.set(binaryChunk, data.length);
|
|
239
|
+
data = newData;
|
|
240
|
+
|
|
241
|
+
let patternIndex;
|
|
242
|
+
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
|
|
243
|
+
yield data.slice(0, patternIndex);
|
|
244
|
+
data = data.slice(patternIndex);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (data.length > 0) {
|
|
249
|
+
yield data;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
class SSEDecoder {
|
|
254
|
+
private data: string[];
|
|
255
|
+
private event: string | null;
|
|
256
|
+
private chunks: string[];
|
|
257
|
+
|
|
258
|
+
constructor() {
|
|
259
|
+
this.event = null;
|
|
260
|
+
this.data = [];
|
|
261
|
+
this.chunks = [];
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
decode(line: string) {
|
|
265
|
+
if (line.endsWith('\r')) {
|
|
266
|
+
line = line.substring(0, line.length - 1);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (!line) {
|
|
270
|
+
// empty line and we didn't previously encounter any messages
|
|
271
|
+
if (!this.event && !this.data.length) return null;
|
|
272
|
+
|
|
273
|
+
const sse: ServerSentEvent = {
|
|
274
|
+
event: this.event,
|
|
275
|
+
data: this.data.join('\n'),
|
|
276
|
+
raw: this.chunks,
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
this.event = null;
|
|
280
|
+
this.data = [];
|
|
281
|
+
this.chunks = [];
|
|
282
|
+
|
|
283
|
+
return sse;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
this.chunks.push(line);
|
|
287
|
+
|
|
288
|
+
if (line.startsWith(':')) {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
let [fieldname, _, value] = partition(line, ':');
|
|
293
|
+
|
|
294
|
+
if (value.startsWith(' ')) {
|
|
295
|
+
value = value.substring(1);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (fieldname === 'event') {
|
|
299
|
+
this.event = value;
|
|
300
|
+
} else if (fieldname === 'data') {
|
|
301
|
+
this.data.push(value);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function partition(str: string, delimiter: string): [string, string, string] {
|
|
309
|
+
const index = str.indexOf(delimiter);
|
|
310
|
+
if (index !== -1) {
|
|
311
|
+
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
return [str, '', ''];
|
|
315
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { concatBytes, decodeUTF8, encodeUTF8 } from '../utils/bytes';
|
|
2
|
+
|
|
3
|
+
export type Bytes = string | ArrayBuffer | Uint8Array | null | undefined;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
|
|
7
|
+
* reading lines from text.
|
|
8
|
+
*
|
|
9
|
+
* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
|
|
10
|
+
*/
|
|
11
|
+
export class LineDecoder {
|
|
12
|
+
// prettier-ignore
|
|
13
|
+
static NEWLINE_CHARS = new Set(['\n', '\r']);
|
|
14
|
+
static NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
15
|
+
|
|
16
|
+
#buffer: Uint8Array;
|
|
17
|
+
#carriageReturnIndex: number | null;
|
|
18
|
+
|
|
19
|
+
constructor() {
|
|
20
|
+
this.#buffer = new Uint8Array();
|
|
21
|
+
this.#carriageReturnIndex = null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
decode(chunk: Bytes): string[] {
|
|
25
|
+
if (chunk == null) {
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const binaryChunk =
|
|
30
|
+
chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
|
|
31
|
+
: typeof chunk === 'string' ? encodeUTF8(chunk)
|
|
32
|
+
: chunk;
|
|
33
|
+
|
|
34
|
+
this.#buffer = concatBytes([this.#buffer, binaryChunk]);
|
|
35
|
+
|
|
36
|
+
const lines: string[] = [];
|
|
37
|
+
let patternIndex;
|
|
38
|
+
while ((patternIndex = findNewlineIndex(this.#buffer, this.#carriageReturnIndex)) != null) {
|
|
39
|
+
if (patternIndex.carriage && this.#carriageReturnIndex == null) {
|
|
40
|
+
// skip until we either get a corresponding `\n`, a new `\r` or nothing
|
|
41
|
+
this.#carriageReturnIndex = patternIndex.index;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// we got double \r or \rtext\n
|
|
46
|
+
if (
|
|
47
|
+
this.#carriageReturnIndex != null &&
|
|
48
|
+
(patternIndex.index !== this.#carriageReturnIndex + 1 || patternIndex.carriage)
|
|
49
|
+
) {
|
|
50
|
+
lines.push(decodeUTF8(this.#buffer.subarray(0, this.#carriageReturnIndex - 1)));
|
|
51
|
+
this.#buffer = this.#buffer.subarray(this.#carriageReturnIndex);
|
|
52
|
+
this.#carriageReturnIndex = null;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const endIndex =
|
|
57
|
+
this.#carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
|
|
58
|
+
|
|
59
|
+
const line = decodeUTF8(this.#buffer.subarray(0, endIndex));
|
|
60
|
+
lines.push(line);
|
|
61
|
+
|
|
62
|
+
this.#buffer = this.#buffer.subarray(patternIndex.index);
|
|
63
|
+
this.#carriageReturnIndex = null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return lines;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
flush(): string[] {
|
|
70
|
+
if (!this.#buffer.length) {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
return this.decode('\n');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* This function searches the buffer for the end patterns, (\r or \n)
|
|
79
|
+
* and returns an object with the index preceding the matched newline and the
|
|
80
|
+
* index after the newline char. `null` is returned if no new line is found.
|
|
81
|
+
*
|
|
82
|
+
* ```ts
|
|
83
|
+
* findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
function findNewlineIndex(
|
|
87
|
+
buffer: Uint8Array,
|
|
88
|
+
startIndex: number | null,
|
|
89
|
+
): { preceding: number; index: number; carriage: boolean } | null {
|
|
90
|
+
const newline = 0x0a; // \n
|
|
91
|
+
const carriage = 0x0d; // \r
|
|
92
|
+
|
|
93
|
+
for (let i = startIndex ?? 0; i < buffer.length; i++) {
|
|
94
|
+
if (buffer[i] === newline) {
|
|
95
|
+
return { preceding: i, index: i + 1, carriage: false };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (buffer[i] === carriage) {
|
|
99
|
+
return { preceding: i, index: i + 1, carriage: true };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function findDoubleNewlineIndex(buffer: Uint8Array): number {
|
|
107
|
+
// This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
|
|
108
|
+
// and returns the index right after the first occurrence of any pattern,
|
|
109
|
+
// or -1 if none of the patterns are found.
|
|
110
|
+
const newline = 0x0a; // \n
|
|
111
|
+
const carriage = 0x0d; // \r
|
|
112
|
+
|
|
113
|
+
for (let i = 0; i < buffer.length - 1; i++) {
|
|
114
|
+
if (buffer[i] === newline && buffer[i + 1] === newline) {
|
|
115
|
+
// \n\n
|
|
116
|
+
return i + 2;
|
|
117
|
+
}
|
|
118
|
+
if (buffer[i] === carriage && buffer[i + 1] === carriage) {
|
|
119
|
+
// \r\r
|
|
120
|
+
return i + 2;
|
|
121
|
+
}
|
|
122
|
+
if (
|
|
123
|
+
buffer[i] === carriage &&
|
|
124
|
+
buffer[i + 1] === newline &&
|
|
125
|
+
i + 3 < buffer.length &&
|
|
126
|
+
buffer[i + 2] === carriage &&
|
|
127
|
+
buffer[i + 3] === newline
|
|
128
|
+
) {
|
|
129
|
+
// \r\n\r\n
|
|
130
|
+
return i + 4;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return -1;
|
|
135
|
+
}
|
package/src/internal/parse.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
2
|
|
|
3
3
|
import type { FinalRequestOptions } from './request-options';
|
|
4
|
+
import { Stream } from '../core/streaming';
|
|
4
5
|
import { type Cadenya } from '../client';
|
|
5
6
|
import { formatRequestDetails, loggerFor } from './utils/log';
|
|
6
7
|
|
|
@@ -16,6 +17,19 @@ export type APIResponseProps = {
|
|
|
16
17
|
export async function defaultParseResponse<T>(client: Cadenya, props: APIResponseProps): Promise<T> {
|
|
17
18
|
const { response, requestLogID, retryOfRequestLogID, startTime } = props;
|
|
18
19
|
const body = await (async () => {
|
|
20
|
+
if (props.options.stream) {
|
|
21
|
+
loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
|
|
22
|
+
|
|
23
|
+
// Note: there is an invariant here that isn't represented in the type system
|
|
24
|
+
// that if you set `stream: true` the response type must also be `Stream<T>`
|
|
25
|
+
|
|
26
|
+
if (props.options.__streamClass) {
|
|
27
|
+
return props.options.__streamClass.fromSSEResponse(response, props.controller, client) as any;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return Stream.fromSSEResponse(response, props.controller, client) as any;
|
|
31
|
+
}
|
|
32
|
+
|
|
19
33
|
// fetch refuses to read the body when the status code is 204.
|
|
20
34
|
if (response.status === 204) {
|
|
21
35
|
return null as T;
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { NullableHeaders } from './headers';
|
|
4
4
|
|
|
5
5
|
import type { BodyInit } from './builtin-types';
|
|
6
|
+
import { Stream } from '../core/streaming';
|
|
6
7
|
import type { HTTPMethod, MergedRequestInit } from './types';
|
|
7
8
|
import { type HeadersLike } from './headers';
|
|
8
9
|
|
|
@@ -76,6 +77,7 @@ export type RequestOptions = {
|
|
|
76
77
|
defaultBaseURL?: string | undefined;
|
|
77
78
|
|
|
78
79
|
__binaryResponse?: boolean | undefined;
|
|
80
|
+
__streamClass?: typeof Stream;
|
|
79
81
|
};
|
|
80
82
|
|
|
81
83
|
export type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit };
|
|
@@ -119,130 +119,22 @@ export namespace AIProviderKey {
|
|
|
119
119
|
|
|
120
120
|
export interface AIProviderKeySpec {
|
|
121
121
|
/**
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
* Gemini) simply leave this unset. The endpoint of a named provider is fixed and
|
|
125
|
-
* intentionally not overridable here; use the OpenAI-compatible provider to target
|
|
126
|
-
* a custom endpoint.
|
|
122
|
+
* The provider credential. Accepted on create/update; never populated in responses
|
|
123
|
+
* (the server returns an empty value to avoid leaking it).
|
|
127
124
|
*/
|
|
128
|
-
|
|
125
|
+
apiKey?: string;
|
|
129
126
|
|
|
130
127
|
/**
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
128
|
+
* OpenRouterConfig holds OpenRouter-specific settings. Empty for now; it exists as
|
|
129
|
+
* the oneof seam so provider-specific options (region, base URL, etc.) can be
|
|
130
|
+
* added later without restructuring the spec.
|
|
134
131
|
*/
|
|
135
|
-
|
|
132
|
+
openrouter?: unknown;
|
|
136
133
|
|
|
137
134
|
/**
|
|
138
135
|
* The AI provider this key authenticates against.
|
|
139
136
|
*/
|
|
140
|
-
provider?:
|
|
141
|
-
| 'AI_PROVIDER_UNSPECIFIED'
|
|
142
|
-
| 'AI_PROVIDER_OPENROUTER'
|
|
143
|
-
| 'AI_PROVIDER_OPENAI'
|
|
144
|
-
| 'AI_PROVIDER_ANTHROPIC'
|
|
145
|
-
| 'AI_PROVIDER_GEMINI'
|
|
146
|
-
| 'AI_PROVIDER_OPENAI_COMPATIBLE';
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
export namespace AIProviderKeySpec {
|
|
150
|
-
/**
|
|
151
|
-
* AIProviderConfig holds non-secret, provider-specific settings. The set case must
|
|
152
|
-
* correspond to AIProviderKeySpec.provider. Providers with no settings (Anthropic,
|
|
153
|
-
* Gemini) simply leave this unset. The endpoint of a named provider is fixed and
|
|
154
|
-
* intentionally not overridable here; use the OpenAI-compatible provider to target
|
|
155
|
-
* a custom endpoint.
|
|
156
|
-
*/
|
|
157
|
-
export interface Config {
|
|
158
|
-
/**
|
|
159
|
-
* OpenAIConfig holds OpenAI-specific settings.
|
|
160
|
-
*/
|
|
161
|
-
openai?: Config.OpenAI;
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* OpenAICompatibleConfig configures a generic endpoint that speaks the OpenAI Chat
|
|
165
|
-
* Completions API. The base URL is required and its model catalog is discovered
|
|
166
|
-
* live via GET {base_url}/models.
|
|
167
|
-
*/
|
|
168
|
-
openaiCompatible?: Config.OpenAICompatible;
|
|
169
|
-
|
|
170
|
-
/**
|
|
171
|
-
* OpenRouterConfig holds OpenRouter-specific settings.
|
|
172
|
-
*/
|
|
173
|
-
openrouter?: Config.Openrouter;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export namespace Config {
|
|
177
|
-
/**
|
|
178
|
-
* OpenAIConfig holds OpenAI-specific settings.
|
|
179
|
-
*/
|
|
180
|
-
export interface OpenAI {
|
|
181
|
-
/**
|
|
182
|
-
* Sent as the OpenAI-Organization header when set.
|
|
183
|
-
*/
|
|
184
|
-
organizationId?: string;
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* Sent as the OpenAI-Project header when set.
|
|
188
|
-
*/
|
|
189
|
-
projectId?: string;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/**
|
|
193
|
-
* OpenAICompatibleConfig configures a generic endpoint that speaks the OpenAI Chat
|
|
194
|
-
* Completions API. The base URL is required and its model catalog is discovered
|
|
195
|
-
* live via GET {base_url}/models.
|
|
196
|
-
*/
|
|
197
|
-
export interface OpenAICompatible {
|
|
198
|
-
baseUrl?: string;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* OpenRouterConfig holds OpenRouter-specific settings.
|
|
203
|
-
*/
|
|
204
|
-
export interface Openrouter {
|
|
205
|
-
/**
|
|
206
|
-
* Data-residency region (e.g. "us", "eu"). Empty uses the provider default.
|
|
207
|
-
*/
|
|
208
|
-
region?: string;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* AIProviderCredential is the secret material used to authenticate with a
|
|
214
|
-
* provider. The set case must correspond to AIProviderKeySpec.provider. The server
|
|
215
|
-
* encrypts the serialized message at rest and never returns it on reads.
|
|
216
|
-
*/
|
|
217
|
-
export interface Credentials {
|
|
218
|
-
/**
|
|
219
|
-
* CredentialAPIKey carries a single bearer/header API key.
|
|
220
|
-
*/
|
|
221
|
-
apiKey?: Credentials.APIKey;
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* CredentialHeaders carries arbitrary HTTP headers sent with every request to the
|
|
225
|
-
* provider (e.g. {"Authorization": "Bearer ...", "X-Api-Key": "..."}).
|
|
226
|
-
*/
|
|
227
|
-
headers?: Credentials.Headers;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
export namespace Credentials {
|
|
231
|
-
/**
|
|
232
|
-
* CredentialAPIKey carries a single bearer/header API key.
|
|
233
|
-
*/
|
|
234
|
-
export interface APIKey {
|
|
235
|
-
apiKey?: string;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/**
|
|
239
|
-
* CredentialHeaders carries arbitrary HTTP headers sent with every request to the
|
|
240
|
-
* provider (e.g. {"Authorization": "Bearer ...", "X-Api-Key": "..."}).
|
|
241
|
-
*/
|
|
242
|
-
export interface Headers {
|
|
243
|
-
headers?: { [key: string]: string };
|
|
244
|
-
}
|
|
245
|
-
}
|
|
137
|
+
provider?: 'AI_PROVIDER_UNSPECIFIED' | 'AI_PROVIDER_OPENROUTER';
|
|
246
138
|
}
|
|
247
139
|
|
|
248
140
|
export interface AIProviderKeyCreateParams {
|
package/src/resources/index.ts
CHANGED
|
@@ -87,6 +87,7 @@ export {
|
|
|
87
87
|
type ObjectiveContextWindow,
|
|
88
88
|
type ObjectiveContextWindowData,
|
|
89
89
|
type ObjectiveError,
|
|
90
|
+
type ObjectiveEvent,
|
|
90
91
|
type ObjectiveEventData,
|
|
91
92
|
type ObjectiveEventInfo,
|
|
92
93
|
type ObjectiveEventWebhookData,
|
|
@@ -102,8 +103,6 @@ export {
|
|
|
102
103
|
type ToolResult,
|
|
103
104
|
type UserMessage,
|
|
104
105
|
type ObjectiveCompactResponse,
|
|
105
|
-
type ObjectiveContinueResponse,
|
|
106
|
-
type ObjectiveListEventsResponse,
|
|
107
106
|
type ObjectiveCreateParams,
|
|
108
107
|
type ObjectiveRetrieveParams,
|
|
109
108
|
type ObjectiveListParams,
|
|
@@ -112,9 +111,10 @@ export {
|
|
|
112
111
|
type ObjectiveContinueParams,
|
|
113
112
|
type ObjectiveListContextWindowsParams,
|
|
114
113
|
type ObjectiveListEventsParams,
|
|
114
|
+
type ObjectiveStreamEventsParams,
|
|
115
115
|
type ObjectivesCursorPagination,
|
|
116
116
|
type ObjectiveContextWindowsCursorPagination,
|
|
117
|
-
type
|
|
117
|
+
type ObjectiveEventsCursorPagination,
|
|
118
118
|
} from './objectives/objectives';
|
|
119
119
|
export { Profiles } from './profiles';
|
|
120
120
|
export {
|
|
@@ -22,6 +22,7 @@ export {
|
|
|
22
22
|
type ObjectiveContextWindow,
|
|
23
23
|
type ObjectiveContextWindowData,
|
|
24
24
|
type ObjectiveError,
|
|
25
|
+
type ObjectiveEvent,
|
|
25
26
|
type ObjectiveEventData,
|
|
26
27
|
type ObjectiveEventInfo,
|
|
27
28
|
type ObjectiveEventWebhookData,
|
|
@@ -37,8 +38,6 @@ export {
|
|
|
37
38
|
type ToolResult,
|
|
38
39
|
type UserMessage,
|
|
39
40
|
type ObjectiveCompactResponse,
|
|
40
|
-
type ObjectiveContinueResponse,
|
|
41
|
-
type ObjectiveListEventsResponse,
|
|
42
41
|
type ObjectiveCreateParams,
|
|
43
42
|
type ObjectiveRetrieveParams,
|
|
44
43
|
type ObjectiveListParams,
|
|
@@ -47,9 +46,10 @@ export {
|
|
|
47
46
|
type ObjectiveContinueParams,
|
|
48
47
|
type ObjectiveListContextWindowsParams,
|
|
49
48
|
type ObjectiveListEventsParams,
|
|
49
|
+
type ObjectiveStreamEventsParams,
|
|
50
50
|
type ObjectivesCursorPagination,
|
|
51
51
|
type ObjectiveContextWindowsCursorPagination,
|
|
52
|
-
type
|
|
52
|
+
type ObjectiveEventsCursorPagination,
|
|
53
53
|
} from './objectives';
|
|
54
54
|
export {
|
|
55
55
|
Tasks,
|