@nyte-ai/protocol 0.0.0-stage → 0.0.19

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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +22 -2
  3. package/THIRD-PARTY-NOTICES.md +866 -0
  4. package/dist/chunks/client-053qg1fq.js +165 -0
  5. package/dist/chunks/client-3sbyne3r.js +22 -0
  6. package/dist/chunks/client-5xm0heem.js +185 -0
  7. package/dist/chunks/client-b8brz84x.js +113 -0
  8. package/dist/chunks/client-eggvt9rc.js +36 -0
  9. package/dist/chunks/client-hrkzqw6w.js +21 -0
  10. package/dist/chunks/client-kq4yq8n4.js +305 -0
  11. package/dist/chunks/client-rk08pxm6.js +12 -0
  12. package/dist/chunks/client-sffw3se8.js +157 -0
  13. package/dist/chunks/client-wffhcyad.js +387 -0
  14. package/dist/chunks/client-x7k53ygp.js +0 -0
  15. package/dist/chunks/client-xscg1xbf.js +44 -0
  16. package/dist/src/client.d.ts +25 -0
  17. package/dist/src/client.js +11 -0
  18. package/dist/src/codec.d.ts +15 -0
  19. package/dist/src/codec.js +19 -0
  20. package/dist/src/declarations.d.ts +25 -0
  21. package/dist/src/declarations.js +1 -0
  22. package/dist/src/digest.d.ts +2 -0
  23. package/dist/src/digest.js +6 -0
  24. package/dist/src/index.d.ts +11 -0
  25. package/dist/src/index.js +98 -0
  26. package/dist/src/json.d.ts +2 -0
  27. package/dist/src/json.js +6 -0
  28. package/dist/src/raw-parts.d.ts +10 -0
  29. package/dist/src/raw-parts.js +6 -0
  30. package/dist/src/stream-buffer.d.ts +7 -0
  31. package/dist/src/stream-buffer.js +6 -0
  32. package/dist/src/stream-channel.d.ts +27 -0
  33. package/dist/src/stream-channel.js +16 -0
  34. package/dist/src/stream-client.d.ts +7 -0
  35. package/dist/src/stream-client.js +10 -0
  36. package/dist/src/streams.d.ts +2 -0
  37. package/dist/src/streams.js +8 -0
  38. package/dist/src/view-frames.d.ts +5 -0
  39. package/dist/src/view-frames.js +9 -0
  40. package/dist/src/wire.d.ts +46 -0
  41. package/dist/src/wire.js +35 -0
  42. package/package.json +44 -3
@@ -0,0 +1,305 @@
1
+ import {
2
+ parseJson2
3
+ } from "./client-rk08pxm6.js";
4
+
5
+ // src/wire.ts
6
+ import { isJsonObject, SdkError, SdkErrorWireSchema, SdkErrorWireType } from "@nyte-ai/schema";
7
+ import { dev } from "@nyte-ai/core";
8
+ var errorStatus2 = {
9
+ invalid: 400,
10
+ unauthenticated: 401,
11
+ denied: 403,
12
+ unknown: 404,
13
+ stale: 409,
14
+ internal: 500,
15
+ unavailable: 503
16
+ };
17
+ var INPUT_HEADER2 = "X-Nyte-Input";
18
+ var HOST_HEADER2 = "X-Nyte-Host";
19
+ var OPERATIONS_HEADER2 = "X-Nyte-Operations";
20
+ var DATA = 0;
21
+ var CONTROL = 1;
22
+ function encodeError2(error) {
23
+ return {
24
+ code: error.code,
25
+ message: error.message,
26
+ hostId: error.hostId,
27
+ issues: error.issues,
28
+ correlation: error.correlation
29
+ };
30
+ }
31
+ function decodeError2(value, status) {
32
+ const result = SdkErrorWireSchema["~standard"].validate(value);
33
+ if (result instanceof Promise || result.issues !== undefined)
34
+ return new SdkError(status === undefined ? "internal" : statusCode2(status), typeof value === "string" && value !== "" ? value : "The host answered with an error it did not describe.");
35
+ const wire = result.value;
36
+ return new SdkError(wire.code, wire.message, {
37
+ hostId: wire.hostId,
38
+ issues: wire.issues,
39
+ correlation: wire.correlation
40
+ });
41
+ }
42
+ function statusCode2(status) {
43
+ if (status === 413)
44
+ return "invalid";
45
+ return SdkErrorWireType.properties.code.enum.find((code) => errorStatus2[code] === status) ?? "internal";
46
+ }
47
+ function sseFrames2(source, options) {
48
+ const iterator = source[Symbol.asyncIterator]();
49
+ const encoder = new TextEncoder;
50
+ let timer;
51
+ return new ReadableStream({
52
+ start(controller) {
53
+ const every = options?.heartbeatMs;
54
+ if (every !== undefined)
55
+ timer = setInterval(() => controller.enqueue(encoder.encode(`: ping
56
+
57
+ `)), every);
58
+ },
59
+ async pull(controller) {
60
+ try {
61
+ const next = await iterator.next();
62
+ if (next.done === true) {
63
+ clearInterval(timer);
64
+ controller.close();
65
+ return;
66
+ }
67
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(next.value)}
68
+
69
+ `));
70
+ } catch (error) {
71
+ clearInterval(timer);
72
+ const wire = JSON.stringify(encodeError2(asSdkError2(error)));
73
+ controller.enqueue(encoder.encode(`event: error
74
+ data: ${wire}
75
+
76
+ `));
77
+ controller.close();
78
+ }
79
+ },
80
+ async cancel() {
81
+ clearInterval(timer);
82
+ await iterator.return?.();
83
+ }
84
+ });
85
+ }
86
+ async function* parseSse2(stream) {
87
+ const reader = stream.getReader();
88
+ const decoder = new TextDecoder;
89
+ let buffer = "";
90
+ try {
91
+ for (;; ) {
92
+ const read = await reader.read();
93
+ buffer += read.done ? decoder.decode() : decoder.decode(read.value, { stream: true });
94
+ const blocks = buffer.replace(/\r\n?/g, `
95
+ `).split(`
96
+
97
+ `);
98
+ buffer = read.done ? "" : blocks.pop() ?? "";
99
+ for (const block of blocks) {
100
+ const frame = parseEventBlock(block);
101
+ if (frame !== null)
102
+ yield frame.data;
103
+ }
104
+ if (read.done)
105
+ return;
106
+ }
107
+ } finally {
108
+ await reader.cancel().catch(() => {
109
+ return;
110
+ });
111
+ }
112
+ }
113
+ function octetStream2(body, signal) {
114
+ const { reader } = body;
115
+ const chunks = reader.chunks()[Symbol.asyncIterator]();
116
+ const headers = new Headers(body.headers);
117
+ headers.set("Content-Type", "application/octet-stream");
118
+ if (reader.mime !== null)
119
+ headers.set("X-Nyte-Mime", reader.mime);
120
+ if (reader.size !== null)
121
+ headers.set("Content-Length", String(reader.size));
122
+ let closing = null;
123
+ const close = () => {
124
+ closing ??= (async () => {
125
+ try {
126
+ await reader.close();
127
+ } finally {
128
+ await chunks.return?.();
129
+ }
130
+ })();
131
+ return closing;
132
+ };
133
+ const stream = new ReadableStream({
134
+ start(controller) {
135
+ const abort = () => {
136
+ controller.error(signal.reason);
137
+ close().catch((error) => {
138
+ dev("protocol", "byte reader close failed", {
139
+ message: error instanceof Error ? error.message : String(error)
140
+ });
141
+ });
142
+ };
143
+ if (signal.aborted)
144
+ abort();
145
+ else
146
+ signal.addEventListener("abort", abort, { once: true });
147
+ },
148
+ async pull(controller) {
149
+ try {
150
+ const next = await chunks.next();
151
+ if (next.done === true) {
152
+ controller.close();
153
+ await close();
154
+ return;
155
+ }
156
+ controller.enqueue(next.value);
157
+ } catch (error) {
158
+ controller.error(error);
159
+ await close();
160
+ }
161
+ },
162
+ cancel: close
163
+ });
164
+ return new Response(stream, { status: 200, headers });
165
+ }
166
+ function outputFrames2(source) {
167
+ const iterator = source[Symbol.asyncIterator]();
168
+ const encoder = new TextEncoder;
169
+ return new ReadableStream({
170
+ async pull(controller) {
171
+ try {
172
+ const next = await iterator.next();
173
+ if (next.done === true) {
174
+ controller.close();
175
+ return;
176
+ }
177
+ const frame = next.value;
178
+ controller.enqueue(frame.kind === "bytes" ? framed(DATA, frame.data) : framed(CONTROL, encoder.encode(JSON.stringify(frame))));
179
+ } catch (error) {
180
+ const failure = { kind: "error", error: encodeError2(asSdkError2(error)) };
181
+ controller.enqueue(framed(CONTROL, encoder.encode(JSON.stringify(failure))));
182
+ controller.close();
183
+ }
184
+ },
185
+ async cancel() {
186
+ await iterator.return?.();
187
+ }
188
+ });
189
+ }
190
+ async function* parseOutputFrames2(stream) {
191
+ const reader = stream.getReader();
192
+ const decoder = new TextDecoder;
193
+ let buffer = new Uint8Array(0);
194
+ try {
195
+ for (;; ) {
196
+ const read = await reader.read();
197
+ if (read.done) {
198
+ if (buffer.byteLength > 0)
199
+ throw new SdkError("internal", "The output stream ended mid-frame.");
200
+ return;
201
+ }
202
+ buffer = joined(buffer, read.value);
203
+ while (buffer.byteLength >= 5) {
204
+ const length = new DataView(buffer.buffer, buffer.byteOffset, 5).getUint32(1);
205
+ if (buffer.byteLength < 5 + length)
206
+ break;
207
+ const tag = buffer[0];
208
+ const payload = buffer.slice(5, 5 + length);
209
+ buffer = buffer.slice(5 + length);
210
+ if (tag === DATA) {
211
+ yield { kind: "bytes", data: payload };
212
+ continue;
213
+ }
214
+ const control = decodeControl(parseJson2(decoder.decode(payload)));
215
+ if (control !== null)
216
+ yield control;
217
+ }
218
+ }
219
+ } finally {
220
+ await reader.cancel().catch(() => {
221
+ return;
222
+ });
223
+ }
224
+ }
225
+ function withInputHeader2(input, body) {
226
+ return {
227
+ method: "POST",
228
+ headers: { "Content-Type": "application/octet-stream", [INPUT_HEADER2]: base64url(input) },
229
+ ...body instanceof ReadableStream ? { body, duplex: "half" } : {
230
+ body: body.buffer instanceof ArrayBuffer ? new Uint8Array(body.buffer, body.byteOffset, body.byteLength) : body.slice()
231
+ }
232
+ };
233
+ }
234
+ function readInputHeader2(request) {
235
+ const header = request.headers.get(INPUT_HEADER2);
236
+ if (header === null)
237
+ return null;
238
+ try {
239
+ const binary = atob(header.replace(/-/g, "+").replace(/_/g, "/"));
240
+ return parseJson2(new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0))));
241
+ } catch {
242
+ throw new SdkError("invalid", `${INPUT_HEADER2} is not base64url JSON.`);
243
+ }
244
+ }
245
+ function asSdkError2(error) {
246
+ if (error instanceof SdkError)
247
+ return error;
248
+ return new SdkError("internal", "The host failed to answer.", {
249
+ correlation: crypto.randomUUID()
250
+ });
251
+ }
252
+ function parseEventBlock(block) {
253
+ let event = "message";
254
+ const data = [];
255
+ for (const line of block.split(`
256
+ `)) {
257
+ if (line === "" || line.startsWith(":"))
258
+ continue;
259
+ const [field, ...rest] = line.split(":");
260
+ const value = rest.join(":").replace(/^ /, "");
261
+ if (field === "event")
262
+ event = value;
263
+ else if (field === "data")
264
+ data.push(value);
265
+ }
266
+ if (data.length === 0)
267
+ return null;
268
+ const json = parseJson2(data.join(`
269
+ `));
270
+ if (event === "error")
271
+ throw decodeError2(json);
272
+ return { data: json };
273
+ }
274
+ function decodeControl(value) {
275
+ if (!isJsonObject(value))
276
+ return null;
277
+ if (value.kind === "gap")
278
+ return { kind: "gap" };
279
+ if (value.kind === "exit")
280
+ return { kind: "exit", code: typeof value.code === "number" ? value.code : null };
281
+ if (value.kind === "error" && value.error !== undefined)
282
+ throw decodeError2(value.error);
283
+ return null;
284
+ }
285
+ function framed(tag, payload) {
286
+ const frame = new Uint8Array(5 + payload.byteLength);
287
+ frame[0] = tag;
288
+ new DataView(frame.buffer).setUint32(1, payload.byteLength);
289
+ frame.set(payload, 5);
290
+ return frame;
291
+ }
292
+ function joined(left, right) {
293
+ if (left.byteLength === 0)
294
+ return right;
295
+ const both = new Uint8Array(left.byteLength + right.byteLength);
296
+ both.set(left);
297
+ both.set(right, left.byteLength);
298
+ return both;
299
+ }
300
+ function base64url(input) {
301
+ const utf8 = encodeURIComponent(JSON.stringify(input)).replace(/%([0-9A-F]{2})/g, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
302
+ return btoa(utf8).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
303
+ }
304
+
305
+ export { errorStatus2, INPUT_HEADER2, HOST_HEADER2, OPERATIONS_HEADER2, encodeError2, decodeError2, statusCode2, sseFrames2, parseSse2, octetStream2, outputFrames2, parseOutputFrames2, withInputHeader2, readInputHeader2, asSdkError2 };
@@ -0,0 +1,12 @@
1
+ // src/json.ts
2
+ import { isJson, SdkError } from "@nyte-ai/schema";
3
+ function parseJson2(text) {
4
+ try {
5
+ const value = JSON.parse(text);
6
+ if (isJson(value))
7
+ return value;
8
+ } catch {}
9
+ throw new SdkError("invalid", "The body is not JSON.");
10
+ }
11
+
12
+ export { parseJson2 };
@@ -0,0 +1,157 @@
1
+ import {
2
+ mapped2
3
+ } from "./client-xscg1xbf.js";
4
+
5
+ // src/view-frames.ts
6
+ import { Type } from "typebox";
7
+ import { Compile } from "typebox/compile";
8
+ import { SdkError } from "@nyte-ai/schema";
9
+ var TAKE = -1;
10
+ var streamed = Compile(Type.Object({ markdown: Type.String() }));
11
+ function viewFrames2(views) {
12
+ let previous = null;
13
+ return mapped2(views, (view) => {
14
+ const frame = previous === null ? { kind: "view", view } : viewDelta(previous, view);
15
+ previous = view;
16
+ return frame;
17
+ });
18
+ }
19
+ function applyViewFrame2(view, frame) {
20
+ if (frame.kind === "view")
21
+ return frame.view;
22
+ if (view === null)
23
+ throw unfit("A view delta arrived before its view.");
24
+ const messages = applySplice(view.messages, frame.messages);
25
+ return {
26
+ revision: frame.revision === undefined ? view.revision : frame.revision,
27
+ seq: frame.seq,
28
+ activation: frame.activation ?? view.activation,
29
+ messages: frame.appends === undefined ? messages : applyAppends(messages, frame.appends),
30
+ leadingPrompt: frame.leadingPrompt === undefined ? view.leadingPrompt : frame.leadingPrompt,
31
+ parts: applySplice(view.parts, frame.parts),
32
+ turns: applySplice(view.turns, frame.turns),
33
+ usage: frame.usage ?? view.usage,
34
+ execution: frame.execution ?? view.execution,
35
+ background: applySplice(view.background, frame.background),
36
+ configuration: frame.configuration ?? view.configuration,
37
+ context: frame.context ?? view.context,
38
+ heads: applySplice(view.heads, frame.heads),
39
+ changes: applySplice(view.changes, frame.changes),
40
+ catalog: frame.catalog ?? view.catalog
41
+ };
42
+ }
43
+ function viewDelta(previous, next) {
44
+ const appends = [];
45
+ const messages = splice(previous.messages, next.messages, (before, after, at) => {
46
+ const grown = appendedText(before, after);
47
+ if (grown !== null)
48
+ appends.push({ at, ...grown });
49
+ return grown !== null;
50
+ });
51
+ return {
52
+ kind: "delta",
53
+ seq: next.seq,
54
+ revision: previous.revision === next.revision ? undefined : next.revision,
55
+ activation: previous.activation === next.activation ? undefined : next.activation,
56
+ messages,
57
+ appends: appends.length === 0 ? undefined : appends,
58
+ leadingPrompt: previous.leadingPrompt === next.leadingPrompt ? undefined : next.leadingPrompt,
59
+ parts: splice(previous.parts, next.parts),
60
+ turns: splice(previous.turns, next.turns),
61
+ usage: previous.usage === next.usage ? undefined : next.usage,
62
+ execution: previous.execution === next.execution ? undefined : next.execution,
63
+ background: splice(previous.background, next.background),
64
+ configuration: previous.configuration === next.configuration ? undefined : next.configuration,
65
+ context: previous.context === next.context ? undefined : next.context,
66
+ heads: splice(previous.heads, next.heads),
67
+ changes: splice(previous.changes, next.changes),
68
+ catalog: previous.catalog === next.catalog ? undefined : next.catalog
69
+ };
70
+ }
71
+ function splice(previous, next, grows) {
72
+ if (previous === next)
73
+ return;
74
+ const runs = [];
75
+ const items = [];
76
+ let positions = null;
77
+ let near = 0;
78
+ next.forEach((item, at) => {
79
+ const found = previous[near] === item ? near : (positions ??= indexed(previous)).get(item);
80
+ if (found !== undefined) {
81
+ extend(runs, found);
82
+ near = found + 1;
83
+ return;
84
+ }
85
+ const before = previous[near];
86
+ if (near < previous.length && before !== undefined && grows?.(before, item, at) === true) {
87
+ extend(runs, near);
88
+ near += 1;
89
+ return;
90
+ }
91
+ extend(runs, TAKE);
92
+ items.push(item);
93
+ });
94
+ return runs.length === 2 && runs[0] === 0 && runs[1] === previous.length && items.length === 0 ? undefined : { runs, items };
95
+ }
96
+ function extend(runs, from) {
97
+ const at = runs.length - 2;
98
+ const last = runs[at];
99
+ const count = runs[at + 1];
100
+ if (last !== undefined && count !== undefined && (from === TAKE ? last === TAKE : last !== TAKE && last + count === from)) {
101
+ runs[at + 1] = count + 1;
102
+ return;
103
+ }
104
+ runs.push(from, 1);
105
+ }
106
+ function indexed(items) {
107
+ const positions = new Map;
108
+ items.forEach((item, at) => positions.set(item, at));
109
+ return positions;
110
+ }
111
+ function applySplice(previous, change) {
112
+ if (change === undefined)
113
+ return previous;
114
+ const next = [];
115
+ let taken = 0;
116
+ for (let at = 0;at < change.runs.length; at += 2) {
117
+ const from = change.runs[at] ?? 0;
118
+ const count = change.runs[at + 1] ?? 0;
119
+ const source = from === TAKE ? change.items : previous;
120
+ const start = from === TAKE ? taken : from;
121
+ if (count < 0 || start < 0 || start + count > source.length)
122
+ throw unfit("A view delta does not fit the view before it.");
123
+ next.push(...source.slice(start, start + count));
124
+ if (from === TAKE)
125
+ taken += count;
126
+ }
127
+ return next;
128
+ }
129
+ function applyAppends(messages, appends) {
130
+ const next = [...messages];
131
+ for (const { at, append, version } of appends) {
132
+ const message = next[at];
133
+ const state = message?.kind === "part" ? message.state : null;
134
+ if (message?.kind !== "part" || !streamed.Check(state))
135
+ throw unfit("A view delta appends to a message that streams no text.");
136
+ next[at] = { ...message, version, state: { ...state, markdown: state.markdown + append } };
137
+ }
138
+ return next;
139
+ }
140
+ function appendedText(before, after) {
141
+ if (before.kind !== "part" || after.kind !== "part" || !streamed.Check(before.state) || !streamed.Check(after.state) || after.state.markdown.length <= before.state.markdown.length || !after.state.markdown.startsWith(before.state.markdown) || !sameBesides(before, after, ["version", "state"]) || !sameBesides(before.state, after.state, ["markdown"]))
142
+ return null;
143
+ return {
144
+ append: after.state.markdown.slice(before.state.markdown.length),
145
+ version: after.version
146
+ };
147
+ }
148
+ function sameBesides(before, after, besides) {
149
+ const kept = new Map(Object.entries(before));
150
+ const entries = Object.entries(after);
151
+ return entries.length === kept.size && entries.every(([key, value]) => besides.includes(key) || kept.has(key) && kept.get(key) === value);
152
+ }
153
+ function unfit(message) {
154
+ return new SdkError("invalid", message);
155
+ }
156
+
157
+ export { viewFrames2, applyViewFrame2 };