@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,165 @@
1
+ import {
2
+ CHANNEL_PATH2,
3
+ CANCEL_PATH2,
4
+ CHANNEL_HEADER2,
5
+ STREAM_HEADER2,
6
+ DEFLATE_REQUEST2,
7
+ readStreamFrame2
8
+ } from "./client-3sbyne3r.js";
9
+ import {
10
+ streamBuffer2
11
+ } from "./client-b8brz84x.js";
12
+ import {
13
+ parseJson2
14
+ } from "./client-rk08pxm6.js";
15
+ import {
16
+ decodeError2,
17
+ parseSse2
18
+ } from "./client-kq4yq8n4.js";
19
+
20
+ // src/stream-client.ts
21
+ import { inflateSync } from "fflate";
22
+ import { SdkError } from "@nyte-ai/schema";
23
+ function createStreamClient2(post, deflate) {
24
+ let channel;
25
+ const json = (value) => ({
26
+ body: JSON.stringify(value),
27
+ headers: { "Content-Type": "application/json" }
28
+ });
29
+ const forget = (current, id) => {
30
+ const stream = current.streams.get(id);
31
+ if (stream === undefined)
32
+ return false;
33
+ current.streams.delete(id);
34
+ stream.dispose();
35
+ if (current.streams.size > 0)
36
+ return true;
37
+ current.controller.abort();
38
+ if (channel === current)
39
+ channel = undefined;
40
+ return false;
41
+ };
42
+ const release = (current, id) => {
43
+ if (!forget(current, id))
44
+ return;
45
+ current.ready.then((channelId) => post(CANCEL_PATH2, {
46
+ ...json({ channel: channelId, stream: id }),
47
+ signal: current.controller.signal
48
+ })).catch(() => {
49
+ return;
50
+ });
51
+ };
52
+ const open = () => {
53
+ if (channel !== undefined)
54
+ return channel;
55
+ const controller = new AbortController;
56
+ const ready = Promise.withResolvers();
57
+ const current = { ready: ready.promise, controller, streams: new Map };
58
+ channel = current;
59
+ (async () => {
60
+ try {
61
+ const response = await post(CHANNEL_PATH2, {
62
+ ...json(deflate ? DEFLATE_REQUEST2 : {}),
63
+ signal: controller.signal
64
+ });
65
+ const id = response.headers.get(CHANNEL_HEADER2);
66
+ if (id === null || response.body === null)
67
+ throw new SdkError("invalid", "The host did not open a stream channel.");
68
+ ready.resolve(id);
69
+ for await (const envelope of parseSse2(networkBody(response.body))) {
70
+ const frame = readStreamFrame2(envelope);
71
+ const stream = current.streams.get(frame.stream);
72
+ if (stream === undefined)
73
+ continue;
74
+ const { buffer } = stream;
75
+ if (frame.kind === "end") {
76
+ buffer.end();
77
+ forget(current, frame.stream);
78
+ } else if (frame.kind === "error") {
79
+ buffer.fail(decodeError2(parseJson2(frame.error)));
80
+ forget(current, frame.stream);
81
+ } else {
82
+ let chunk;
83
+ try {
84
+ const bytes = Uint8Array.fromBase64(frame.data);
85
+ chunk = frame.kind === "deflated" ? inflateSync(bytes) : bytes;
86
+ } catch {
87
+ throw new SdkError("invalid", "The host sent invalid stream bytes.");
88
+ }
89
+ if (!buffer.push(chunk)) {
90
+ buffer.fail(new SdkError("unavailable", "The stream exceeded its buffer capacity."));
91
+ release(current, frame.stream);
92
+ }
93
+ }
94
+ }
95
+ if (!controller.signal.aborted)
96
+ throw new SdkError("unavailable", "The stream channel disconnected.");
97
+ } catch (cause) {
98
+ const error = cause instanceof Error ? cause : new SdkError("unavailable", cause instanceof Error ? cause.message : "The stream channel disconnected.");
99
+ ready.reject(error);
100
+ for (const stream of current.streams.values())
101
+ stream.buffer.fail(error);
102
+ } finally {
103
+ for (const stream of current.streams.values())
104
+ stream.dispose();
105
+ current.streams.clear();
106
+ controller.abort();
107
+ if (channel === current)
108
+ channel = undefined;
109
+ }
110
+ })();
111
+ return current;
112
+ };
113
+ return async (name, input, signal) => {
114
+ signal.throwIfAborted();
115
+ const current = open();
116
+ const id = crypto.randomUUID();
117
+ const buffer = streamBuffer2(() => release(current, id));
118
+ const canceled = Promise.withResolvers();
119
+ const abort = () => {
120
+ const error = signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError");
121
+ buffer.fail(error);
122
+ canceled.reject(error);
123
+ release(current, id);
124
+ };
125
+ current.streams.set(id, { buffer, dispose: () => signal.removeEventListener("abort", abort) });
126
+ signal.addEventListener("abort", abort, { once: true });
127
+ try {
128
+ const channelId = await Promise.race([current.ready, canceled.promise]);
129
+ signal.throwIfAborted();
130
+ await Promise.race([
131
+ post(name, {
132
+ ...json(input),
133
+ headers: {
134
+ "Content-Type": "application/json",
135
+ [CHANNEL_HEADER2]: channelId,
136
+ [STREAM_HEADER2]: id
137
+ },
138
+ signal
139
+ }),
140
+ canceled.promise
141
+ ]);
142
+ return buffer.body;
143
+ } catch (error) {
144
+ release(current, id);
145
+ throw error;
146
+ }
147
+ };
148
+ }
149
+ function networkBody(body) {
150
+ const reader = body.getReader();
151
+ return new ReadableStream({
152
+ async pull(controller) {
153
+ const next = await reader.read().catch((cause) => {
154
+ throw new SdkError("unavailable", cause instanceof Error ? cause.message : String(cause));
155
+ });
156
+ if (next.done)
157
+ controller.close();
158
+ else
159
+ controller.enqueue(next.value);
160
+ },
161
+ cancel: (reason) => reader.cancel(reason)
162
+ });
163
+ }
164
+
165
+ export { createStreamClient2 };
@@ -0,0 +1,22 @@
1
+ // src/stream-channel.ts
2
+ import { isJsonObject, SdkError } from "@nyte-ai/schema";
3
+ var CHANNEL_PATH2 = ".nyte/streams";
4
+ var CANCEL_PATH2 = ".nyte/streams/cancel";
5
+ var CHANNEL_HEADER2 = "X-Nyte-Channel";
6
+ var STREAM_HEADER2 = "X-Nyte-Stream";
7
+ var DEFLATE_REQUEST2 = { deflate: true };
8
+ function readStreamFrame2(value) {
9
+ if (isJsonObject(value) && typeof value.stream === "string") {
10
+ if (value.kind === "chunk" && typeof value.data === "string")
11
+ return { kind: "chunk", stream: value.stream, data: value.data };
12
+ if (value.kind === "deflated" && typeof value.data === "string")
13
+ return { kind: "deflated", stream: value.stream, data: value.data };
14
+ if (value.kind === "end")
15
+ return { kind: "end", stream: value.stream };
16
+ if (value.kind === "error" && typeof value.error === "string")
17
+ return { kind: "error", stream: value.stream, error: value.error };
18
+ }
19
+ throw new SdkError("invalid", "The host sent an invalid stream frame.");
20
+ }
21
+
22
+ export { CHANNEL_PATH2, CANCEL_PATH2, CHANNEL_HEADER2, STREAM_HEADER2, DEFLATE_REQUEST2, readStreamFrame2 };
@@ -0,0 +1,185 @@
1
+ import {
2
+ parseJson2
3
+ } from "./client-rk08pxm6.js";
4
+ import {
5
+ HOST_HEADER2,
6
+ OPERATIONS_HEADER2,
7
+ decodeError2,
8
+ parseSse2,
9
+ parseOutputFrames2,
10
+ withInputHeader2
11
+ } from "./client-kq4yq8n4.js";
12
+ import {
13
+ createStreamClient2
14
+ } from "./client-053qg1fq.js";
15
+
16
+ // src/client.ts
17
+ import { asId, OPERATIONS, SdkError } from "@nyte-ai/schema";
18
+ var DONE = { done: true, value: undefined };
19
+ function createTransport2(options) {
20
+ const base = options.url.replace(/\/+$/, "");
21
+ const send = options.fetch ?? fetch;
22
+ let credential = null;
23
+ let host = null;
24
+ let operations = null;
25
+ const post = async (name, init) => {
26
+ const headers = { ...await options.headers(), ...init.headers };
27
+ let response;
28
+ try {
29
+ response = await send(`${base}/${name}`, { ...init, method: "POST", headers });
30
+ } catch (error) {
31
+ if (!(error instanceof TypeError) || init.signal?.aborted === true)
32
+ throw error;
33
+ throw new SdkError("unavailable", error.message);
34
+ }
35
+ const answered = response.headers.get(HOST_HEADER2);
36
+ if (answered !== null && host !== null && answered !== host) {
37
+ await response.body?.cancel();
38
+ throw new SdkError("stale", `Host ${answered} answered instead of ${host}.`, {
39
+ hostId: asId(answered)
40
+ });
41
+ }
42
+ if (answered !== null)
43
+ host = asId(answered);
44
+ operations = response.headers.get(OPERATIONS_HEADER2) ?? operations;
45
+ credential = response.headers.get("X-Nyte-Credential") ?? credential;
46
+ if (response.ok)
47
+ return response;
48
+ throw decodeError2(jsonOrText(await response.text()), response.status);
49
+ };
50
+ const json = (input, headers) => ({
51
+ body: JSON.stringify(input),
52
+ headers: { "Content-Type": "application/json", ...headers }
53
+ });
54
+ const stream = createStreamClient2(post, crossesNetwork(base));
55
+ return {
56
+ async invoke(name, input, request) {
57
+ if ("wait" in OPERATIONS[name]) {
58
+ const controller = new AbortController;
59
+ const signal = request?.signal ?? controller.signal;
60
+ try {
61
+ return parseJson2(await new Response(await stream(name, input, signal)).text());
62
+ } finally {
63
+ controller.abort();
64
+ }
65
+ }
66
+ const response = await post(name, { ...json(input), signal: request?.signal });
67
+ return parseJson2(await response.text());
68
+ },
69
+ frames(name, input) {
70
+ return cancellable(async function* (signal) {
71
+ yield* parseSse2(await stream(name, input, signal));
72
+ });
73
+ },
74
+ output(input) {
75
+ return cancellable(async function* (signal) {
76
+ yield* parseOutputFrames2(await stream("job.output", input, signal));
77
+ });
78
+ },
79
+ async bytes(name, input, request) {
80
+ const response = await post(name, { ...json(input), signal: request?.signal });
81
+ const length = response.headers.get("Content-Length");
82
+ const version = response.headers.get("X-Nyte-Version");
83
+ const body = response.body;
84
+ const reader = body?.getReader() ?? null;
85
+ const close = async () => {
86
+ await reader?.cancel();
87
+ };
88
+ return {
89
+ size: length === null ? null : Number(length),
90
+ mime: response.headers.get("X-Nyte-Mime"),
91
+ ...version === null ? {} : { version: asId(version) },
92
+ async* chunks() {
93
+ if (reader === null)
94
+ return;
95
+ for (;; ) {
96
+ const read = await reader.read();
97
+ if (read.done)
98
+ return;
99
+ yield read.value;
100
+ }
101
+ },
102
+ close,
103
+ [Symbol.asyncDispose]: close
104
+ };
105
+ },
106
+ async upload(name, input, body, request) {
107
+ const response = await post(name, {
108
+ ...withInputHeader2(input, body),
109
+ signal: request?.signal
110
+ });
111
+ return parseJson2(await response.text());
112
+ },
113
+ credential: () => credential,
114
+ host: () => host,
115
+ operations: () => operations
116
+ };
117
+ }
118
+ function cancellable(open) {
119
+ return {
120
+ [Symbol.asyncIterator]() {
121
+ const controller = new AbortController;
122
+ const source = open(controller.signal)[Symbol.asyncIterator]();
123
+ let settle = null;
124
+ const release = () => {
125
+ Promise.resolve(source.return?.()).catch(() => {
126
+ return;
127
+ });
128
+ };
129
+ return {
130
+ next() {
131
+ if (controller.signal.aborted)
132
+ return Promise.resolve(DONE);
133
+ const pulled = (async () => {
134
+ try {
135
+ const next = await source.next();
136
+ if (!controller.signal.aborted) {
137
+ if (next.done === true)
138
+ controller.abort();
139
+ return next;
140
+ }
141
+ if (next.done !== true)
142
+ release();
143
+ return DONE;
144
+ } catch (error) {
145
+ if (controller.signal.aborted)
146
+ return DONE;
147
+ controller.abort();
148
+ throw error;
149
+ }
150
+ })();
151
+ return Promise.race([
152
+ pulled,
153
+ new Promise((resolve) => {
154
+ settle = resolve;
155
+ })
156
+ ]).finally(() => {
157
+ settle = null;
158
+ });
159
+ },
160
+ async return() {
161
+ const waiting = settle;
162
+ settle = null;
163
+ if (waiting === null && !controller.signal.aborted)
164
+ release();
165
+ controller.abort();
166
+ waiting?.(DONE);
167
+ return DONE;
168
+ }
169
+ };
170
+ }
171
+ };
172
+ }
173
+ function crossesNetwork(url) {
174
+ const { hostname } = new URL(url);
175
+ return hostname !== "localhost" && hostname !== "[::1]" && !hostname.startsWith("127.");
176
+ }
177
+ function jsonOrText(text) {
178
+ try {
179
+ return parseJson2(text);
180
+ } catch {
181
+ return text;
182
+ }
183
+ }
184
+
185
+ export { createTransport2 };
@@ -0,0 +1,113 @@
1
+ // src/stream-buffer.ts
2
+ var MAX_BYTES = 8 * 1024 * 1024;
3
+ var MAX_CHUNKS = 4096;
4
+ function streamBuffer2(cancel) {
5
+ let chunks = [];
6
+ let head = 0;
7
+ let bytes = 0;
8
+ let ending;
9
+ let wake;
10
+ const writers = new Set;
11
+ const writable = () => {
12
+ for (const resolve of writers)
13
+ resolve();
14
+ };
15
+ const notify = () => {
16
+ const resolve = wake;
17
+ wake = undefined;
18
+ resolve?.();
19
+ };
20
+ const clear = () => {
21
+ chunks = [];
22
+ head = 0;
23
+ bytes = 0;
24
+ writable();
25
+ };
26
+ const push = (chunk) => {
27
+ if (ending !== undefined)
28
+ return false;
29
+ if (bytes + chunk.byteLength > MAX_BYTES || chunks.length - head >= MAX_CHUNKS)
30
+ return false;
31
+ chunks.push(chunk);
32
+ bytes += chunk.byteLength;
33
+ notify();
34
+ return true;
35
+ };
36
+ return {
37
+ body: new ReadableStream({
38
+ async pull(controller) {
39
+ for (;; ) {
40
+ if (ending?.error !== undefined) {
41
+ controller.error(ending.error);
42
+ return;
43
+ }
44
+ const chunk = chunks[head];
45
+ if (chunk !== undefined) {
46
+ head += 1;
47
+ bytes -= chunk.byteLength;
48
+ writable();
49
+ if (head === chunks.length)
50
+ clear();
51
+ else if (head >= 256) {
52
+ chunks = chunks.slice(head);
53
+ head = 0;
54
+ }
55
+ controller.enqueue(chunk);
56
+ return;
57
+ }
58
+ if (ending !== undefined) {
59
+ controller.close();
60
+ return;
61
+ }
62
+ await new Promise((resolve) => {
63
+ wake = resolve;
64
+ });
65
+ }
66
+ },
67
+ cancel() {
68
+ ending ??= {};
69
+ clear();
70
+ notify();
71
+ cancel();
72
+ }
73
+ }, { highWaterMark: 0 }),
74
+ push,
75
+ async write(chunk, signal) {
76
+ for (let start = 0;start < chunk.byteLength; start += MAX_BYTES) {
77
+ const part = chunk.subarray(start, start + MAX_BYTES);
78
+ for (;; ) {
79
+ if (ending !== undefined || signal.aborted)
80
+ return;
81
+ if (push(part))
82
+ break;
83
+ await new Promise((resolve) => {
84
+ const ready = () => {
85
+ writers.delete(ready);
86
+ signal.removeEventListener("abort", ready);
87
+ resolve();
88
+ };
89
+ writers.add(ready);
90
+ signal.addEventListener("abort", ready, { once: true });
91
+ });
92
+ }
93
+ }
94
+ },
95
+ end(final) {
96
+ if (final !== undefined) {
97
+ clear();
98
+ chunks.push(final);
99
+ bytes = final.byteLength;
100
+ }
101
+ ending ??= {};
102
+ notify();
103
+ writable();
104
+ },
105
+ fail(error) {
106
+ ending = { error };
107
+ clear();
108
+ notify();
109
+ }
110
+ };
111
+ }
112
+
113
+ export { streamBuffer2 };
@@ -0,0 +1,36 @@
1
+ // src/raw-parts.ts
2
+ import { isJson, isJsonObject } from "@nyte-ai/schema";
3
+ var ROLES = new Set(["step", "answer", "note"]);
4
+ function rawPart2(item) {
5
+ if (!isJson(item) || !isJsonObject(item))
6
+ return null;
7
+ const { id, turn, at, kind, part, partKind, role, state, version, placement, owner } = item;
8
+ if (typeof id !== "string")
9
+ return null;
10
+ const carriesPart = typeof partKind === "string" && state !== undefined;
11
+ const raw = {
12
+ partKind: carriesPart ? partKind : typeof kind === "string" ? kind : "unknown",
13
+ state: carriesPart ? state : item,
14
+ version: typeof version === "number" ? version : 0
15
+ };
16
+ if (typeof turn === "string" && typeof at === "number")
17
+ return {
18
+ ...raw,
19
+ id,
20
+ turn,
21
+ at,
22
+ kind: "part",
23
+ part: typeof part === "string" ? part : id,
24
+ role: typeof role === "string" && ROLES.has(role) ? role : "note",
25
+ status: { kind: "settled", commit: "", endedAt: at }
26
+ };
27
+ return {
28
+ ...raw,
29
+ id,
30
+ placement: isJsonObject(placement) && typeof placement["kind"] === "string" ? placement : { kind: "transcript", role: "note" },
31
+ status: { kind: "settled", commit: "", endedAt: 0 },
32
+ owner: typeof owner === "string" ? owner : null
33
+ };
34
+ }
35
+
36
+ export { rawPart2 };
@@ -0,0 +1,21 @@
1
+ // src/digest.ts
2
+ import { OPERATIONS } from "@nyte-ai/schema";
3
+ var rows = OPERATIONS;
4
+ var encoder = new TextEncoder;
5
+ async function operationsDigest2() {
6
+ const table = Object.entries(rows).map(([name, row]) => [
7
+ name,
8
+ row.kind,
9
+ row.authority,
10
+ row.scope,
11
+ row.capability ?? null,
12
+ row.recovery ?? null,
13
+ row.wait ?? null,
14
+ row.input["~standard"].jsonSchema.input({ target: "draft-2020-12" }),
15
+ row.output["~standard"].jsonSchema.input({ target: "draft-2020-12" })
16
+ ]);
17
+ const hash = await crypto.subtle.digest("SHA-256", encoder.encode(JSON.stringify(table)));
18
+ return new Uint8Array(hash).toHex().slice(0, 16);
19
+ }
20
+
21
+ export { operationsDigest2 };