@skein-js/fetch 0.12.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/LICENSE +13 -0
- package/README.md +23 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.js +224 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2025-2026 skein-js contributors
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# @skein-js/fetch
|
|
2
|
+
|
|
3
|
+
Native Web `Request`/`Response` transport for Skein. It is the production HTTP boundary for Bun and
|
|
4
|
+
Deno; Node framework adapters remain in `@skein-js/express`, `@skein-js/fastify`,
|
|
5
|
+
`@skein-js/nestjs`, and `@skein-js/nextjs`.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createSkeinFetchServer, startBunServer } from "@skein-js/fetch";
|
|
9
|
+
|
|
10
|
+
const skein = await createSkeinFetchServer({ config: "./langgraph.json", warm: true });
|
|
11
|
+
const listener = startBunServer(skein.fetch, { hostname: "0.0.0.0", port: 8000 });
|
|
12
|
+
|
|
13
|
+
// During shutdown: stop accepting traffic first, then drain the Skein worker.
|
|
14
|
+
listener.stop();
|
|
15
|
+
await skein.close();
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`startDenoServer` provides the corresponding `Deno.serve()` launcher. The host must grant the
|
|
19
|
+
network, environment, filesystem, and npm-package permissions required by its graph.
|
|
20
|
+
|
|
21
|
+
## Building
|
|
22
|
+
|
|
23
|
+
Run `nx build server-fetch` to build the library.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { ProtocolResponse } from '@skein-js/agent-protocol';
|
|
2
|
+
import { ResolvedProtocolRuntime, SkeinRuntimeOptions } from '@skein-js/server-kit';
|
|
3
|
+
export { Logger, RunWorkerOptions, SkeinRuntimeOptions, createConsoleLogger } from '@skein-js/server-kit';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Largest JSON body accepted, matching `express.json()`'s 100kb so the same request is accepted or
|
|
7
|
+
* rejected identically whichever adapter serves it.
|
|
8
|
+
*
|
|
9
|
+
* A bound is not optional here. The Node adapters inherit one from their body parser, but a native
|
|
10
|
+
* Fetch server has none worth relying on: `Bun.serve` defaults to 128MB and `Deno.serve` has no limit
|
|
11
|
+
* at all. Reading an unbounded body into a JS string happens *before* validation or auth, so without
|
|
12
|
+
* this a handful of concurrent large-body requests is an unauthenticated OOM on the 512Mi shape
|
|
13
|
+
* docs/performance.md sizes for.
|
|
14
|
+
*/
|
|
15
|
+
declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
16
|
+
/** Options for a native Fetch server. The protocol is mounted at the root unless `basePath` is set. */
|
|
17
|
+
type SkeinFetchServerOptions = SkeinRuntimeOptions & {
|
|
18
|
+
basePath?: string;
|
|
19
|
+
/** Largest accepted JSON body, in bytes. Defaults to {@link DEFAULT_MAX_BODY_BYTES}. */
|
|
20
|
+
maxBodyBytes?: number;
|
|
21
|
+
};
|
|
22
|
+
type SkeinFetchHandler = (request: Request) => Promise<Response>;
|
|
23
|
+
/** A resolved Fetch handler and the lifecycle it owns. `close` drains the run worker once. */
|
|
24
|
+
interface SkeinFetchServer {
|
|
25
|
+
fetch: SkeinFetchHandler;
|
|
26
|
+
runtime: ResolvedProtocolRuntime["runtime"];
|
|
27
|
+
close: () => Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
/** Serialize a transport-neutral protocol response into a Web `Response`. */
|
|
30
|
+
declare function toFetchResponse(response: ProtocolResponse, extraHeaders?: Record<string, string>): Response;
|
|
31
|
+
/** Resolve and start a Skein runtime, returning the Fetch handler plus an ordered drain lifecycle. */
|
|
32
|
+
declare function createSkeinFetchServer(options: SkeinFetchServerOptions): Promise<SkeinFetchServer>;
|
|
33
|
+
|
|
34
|
+
interface NativeServerOptions {
|
|
35
|
+
port: number;
|
|
36
|
+
hostname?: string;
|
|
37
|
+
}
|
|
38
|
+
interface BunServerHandle {
|
|
39
|
+
hostname: string;
|
|
40
|
+
port: number;
|
|
41
|
+
stop: (closeActiveConnections?: boolean) => void;
|
|
42
|
+
}
|
|
43
|
+
interface DenoServerHandle {
|
|
44
|
+
addr: {
|
|
45
|
+
hostname: string;
|
|
46
|
+
port: number;
|
|
47
|
+
};
|
|
48
|
+
finished: Promise<void>;
|
|
49
|
+
shutdown: () => Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/** Start a native `Bun.serve` listener without importing a Node HTTP compatibility layer. */
|
|
52
|
+
declare function startBunServer(fetch: (request: Request) => Response | Promise<Response>, options: NativeServerOptions): BunServerHandle;
|
|
53
|
+
/** Start a native `Deno.serve` listener without importing a Node HTTP compatibility layer. */
|
|
54
|
+
declare function startDenoServer(fetch: (request: Request) => Response | Promise<Response>, options: NativeServerOptions): DenoServerHandle;
|
|
55
|
+
|
|
56
|
+
export { type BunServerHandle, DEFAULT_MAX_BODY_BYTES, type DenoServerHandle, type NativeServerOptions, type SkeinFetchHandler, type SkeinFetchServer, type SkeinFetchServerOptions, createSkeinFetchServer, startBunServer, startDenoServer, toFetchResponse };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// src/skein-fetch-server.ts
|
|
2
|
+
import {
|
|
3
|
+
copyThreadIdIntoBody,
|
|
4
|
+
createRouteMatcher,
|
|
5
|
+
SSE_HEADERS
|
|
6
|
+
} from "@skein-js/agent-protocol";
|
|
7
|
+
import { isSkeinHttpError, serializeWireJson, SkeinHttpError } from "@skein-js/core";
|
|
8
|
+
import {
|
|
9
|
+
corsPreflightHeaders,
|
|
10
|
+
corsResponseHeaders,
|
|
11
|
+
resolveProtocolRuntime,
|
|
12
|
+
stripBasePath
|
|
13
|
+
} from "@skein-js/server-kit";
|
|
14
|
+
var DEFAULT_MAX_BODY_BYTES = 100 * 1024;
|
|
15
|
+
function toQuery(url) {
|
|
16
|
+
const query = {};
|
|
17
|
+
for (const key of new Set(url.searchParams.keys())) {
|
|
18
|
+
const values = url.searchParams.getAll(key);
|
|
19
|
+
query[key] = values.length > 1 ? values : values[0];
|
|
20
|
+
}
|
|
21
|
+
return query;
|
|
22
|
+
}
|
|
23
|
+
async function readBoundedText(request, maxBodyBytes) {
|
|
24
|
+
const declared = Number(request.headers.get("content-length"));
|
|
25
|
+
if (Number.isFinite(declared) && declared > maxBodyBytes) {
|
|
26
|
+
throw SkeinHttpError.payloadTooLarge(`Request body exceeds ${maxBodyBytes} bytes.`);
|
|
27
|
+
}
|
|
28
|
+
if (!request.body) return request.text();
|
|
29
|
+
const decoder = new TextDecoder();
|
|
30
|
+
const reader = request.body.getReader();
|
|
31
|
+
let received = 0;
|
|
32
|
+
let text = "";
|
|
33
|
+
try {
|
|
34
|
+
for (; ; ) {
|
|
35
|
+
const { done, value } = await reader.read();
|
|
36
|
+
if (done) break;
|
|
37
|
+
received += value.byteLength;
|
|
38
|
+
if (received > maxBodyBytes) {
|
|
39
|
+
throw SkeinHttpError.payloadTooLarge(`Request body exceeds ${maxBodyBytes} bytes.`);
|
|
40
|
+
}
|
|
41
|
+
text += decoder.decode(value, { stream: true });
|
|
42
|
+
}
|
|
43
|
+
} finally {
|
|
44
|
+
await reader.cancel().catch(() => {
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return text + decoder.decode();
|
|
48
|
+
}
|
|
49
|
+
async function toProtocolRequest(request, url, skeinPathname, params, maxBodyBytes) {
|
|
50
|
+
let body;
|
|
51
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
52
|
+
const text = await readBoundedText(request, maxBodyBytes);
|
|
53
|
+
try {
|
|
54
|
+
body = text ? JSON.parse(text) : {};
|
|
55
|
+
} catch {
|
|
56
|
+
throw SkeinHttpError.badRequest("Request body is not valid JSON.");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
method: request.method,
|
|
61
|
+
url: `${url.origin}${skeinPathname}${url.search}`,
|
|
62
|
+
params,
|
|
63
|
+
query: toQuery(url),
|
|
64
|
+
body,
|
|
65
|
+
headers: Object.fromEntries(request.headers),
|
|
66
|
+
signal: request.signal
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function createSseStream(events) {
|
|
70
|
+
const iterator = events[Symbol.asyncIterator]();
|
|
71
|
+
const encoder = new TextEncoder();
|
|
72
|
+
let finished = false;
|
|
73
|
+
return new ReadableStream(
|
|
74
|
+
{
|
|
75
|
+
async pull(controller) {
|
|
76
|
+
if (finished) return;
|
|
77
|
+
try {
|
|
78
|
+
const next = await iterator.next();
|
|
79
|
+
if (next.done) {
|
|
80
|
+
finished = true;
|
|
81
|
+
controller.close();
|
|
82
|
+
} else {
|
|
83
|
+
controller.enqueue(encoder.encode(next.value));
|
|
84
|
+
}
|
|
85
|
+
} catch (error) {
|
|
86
|
+
finished = true;
|
|
87
|
+
controller.error(error);
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
async cancel() {
|
|
91
|
+
if (finished) return;
|
|
92
|
+
finished = true;
|
|
93
|
+
await iterator.return?.(void 0);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
// The adapter itself retains no more than one encoded frame for a slow consumer.
|
|
97
|
+
{ highWaterMark: 1 }
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
function toFetchResponse(response, extraHeaders = {}) {
|
|
101
|
+
switch (response.kind) {
|
|
102
|
+
case "json":
|
|
103
|
+
return new Response(serializeWireJson(response.body), {
|
|
104
|
+
status: response.status,
|
|
105
|
+
headers: { "content-type": "application/json", ...response.headers, ...extraHeaders }
|
|
106
|
+
});
|
|
107
|
+
case "empty":
|
|
108
|
+
return new Response(null, {
|
|
109
|
+
status: response.status,
|
|
110
|
+
headers: { ...response.headers, ...extraHeaders }
|
|
111
|
+
});
|
|
112
|
+
case "sse":
|
|
113
|
+
return new Response(createSseStream(response.events), {
|
|
114
|
+
status: response.status,
|
|
115
|
+
headers: { ...SSE_HEADERS, ...response.headers, ...extraHeaders }
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function errorResponse(error, extraHeaders, logger) {
|
|
120
|
+
const headers = { "content-type": "application/json", ...extraHeaders };
|
|
121
|
+
if (isSkeinHttpError(error)) {
|
|
122
|
+
return new Response(
|
|
123
|
+
JSON.stringify({
|
|
124
|
+
status: error.status,
|
|
125
|
+
message: error.message,
|
|
126
|
+
...error.code !== void 0 ? { code: error.code } : {},
|
|
127
|
+
...error.details !== void 0 ? { details: error.details } : {}
|
|
128
|
+
}),
|
|
129
|
+
{ status: error.status, headers }
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
logger?.error("Unhandled error in the skein Fetch adapter.", error);
|
|
133
|
+
return new Response(JSON.stringify({ status: 500, message: "Internal Server Error" }), {
|
|
134
|
+
status: 500,
|
|
135
|
+
headers
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
function createFetchHandler(resolved, options) {
|
|
139
|
+
const basePath = options.basePath ?? "";
|
|
140
|
+
const cors = options.cors ?? resolved.cors;
|
|
141
|
+
const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
142
|
+
const matchRoute = createRouteMatcher(resolved.routes);
|
|
143
|
+
return async (request) => {
|
|
144
|
+
const url = new URL(request.url);
|
|
145
|
+
const skeinPathname = stripBasePath(url.pathname, basePath);
|
|
146
|
+
if (skeinPathname === null) return new Response(null, { status: 404 });
|
|
147
|
+
if (skeinPathname === "/ok" && request.method === "GET") {
|
|
148
|
+
return new Response(JSON.stringify({ ok: true }), {
|
|
149
|
+
status: 200,
|
|
150
|
+
headers: { "content-type": "application/json" }
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
if (request.method === "OPTIONS") {
|
|
154
|
+
if (!cors) return new Response(null, { status: 404 });
|
|
155
|
+
return new Response(null, {
|
|
156
|
+
status: 204,
|
|
157
|
+
headers: corsPreflightHeaders(
|
|
158
|
+
request.headers.get("origin") ?? void 0,
|
|
159
|
+
request.headers.get("access-control-request-headers") ?? void 0,
|
|
160
|
+
cors
|
|
161
|
+
)
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
const extraHeaders = cors ? corsResponseHeaders(request.headers.get("origin") ?? void 0, cors) : {};
|
|
165
|
+
const match = matchRoute(request.method, skeinPathname);
|
|
166
|
+
if (!match) {
|
|
167
|
+
return new Response(JSON.stringify({ status: 404, message: "Not Found" }), {
|
|
168
|
+
status: 404,
|
|
169
|
+
headers: { "content-type": "application/json", ...extraHeaders }
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
const protocolRequest = await toProtocolRequest(
|
|
174
|
+
request,
|
|
175
|
+
url,
|
|
176
|
+
skeinPathname,
|
|
177
|
+
match.params,
|
|
178
|
+
maxBodyBytes
|
|
179
|
+
);
|
|
180
|
+
const invoke = resolved.runtime.handlers[match.binding.handler];
|
|
181
|
+
const response = await invoke(
|
|
182
|
+
match.binding.foldThreadIdIntoBody ? copyThreadIdIntoBody(protocolRequest) : protocolRequest
|
|
183
|
+
);
|
|
184
|
+
return toFetchResponse(response, extraHeaders);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
return errorResponse(error, extraHeaders, resolved.logger);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
async function createSkeinFetchServer(options) {
|
|
191
|
+
const resolved = await resolveProtocolRuntime(options);
|
|
192
|
+
let closePromise;
|
|
193
|
+
return {
|
|
194
|
+
fetch: createFetchHandler(resolved, options),
|
|
195
|
+
runtime: resolved.runtime,
|
|
196
|
+
close() {
|
|
197
|
+
closePromise ??= resolved.runtime.worker.stop();
|
|
198
|
+
return closePromise;
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// src/native-servers.ts
|
|
204
|
+
function startBunServer(fetch, options) {
|
|
205
|
+
const bun = globalThis.Bun;
|
|
206
|
+
if (!bun) throw new Error("Bun.serve is unavailable. Run this launcher with Bun.");
|
|
207
|
+
return bun.serve({ ...options, fetch });
|
|
208
|
+
}
|
|
209
|
+
function startDenoServer(fetch, options) {
|
|
210
|
+
const deno = globalThis.Deno;
|
|
211
|
+
if (!deno) throw new Error("Deno.serve is unavailable. Run this launcher with Deno.");
|
|
212
|
+
return deno.serve(options, fetch);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/index.ts
|
|
216
|
+
import { createConsoleLogger } from "@skein-js/server-kit";
|
|
217
|
+
export {
|
|
218
|
+
DEFAULT_MAX_BODY_BYTES,
|
|
219
|
+
createConsoleLogger,
|
|
220
|
+
createSkeinFetchServer,
|
|
221
|
+
startBunServer,
|
|
222
|
+
startDenoServer,
|
|
223
|
+
toFetchResponse
|
|
224
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@skein-js/fetch",
|
|
3
|
+
"version": "0.12.0",
|
|
4
|
+
"description": "Runtime-neutral Fetch adapter for serving the Skein Agent Protocol on Bun and Deno.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Maina Wycliffe <wmmaina7@gmail.com>",
|
|
7
|
+
"homepage": "https://github.com/skein-js/skein-js/tree/main/packages/server-fetch#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/skein-js/skein-js.git",
|
|
11
|
+
"directory": "packages/server-fetch"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/skein-js/skein-js/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"typescript",
|
|
18
|
+
"fetch",
|
|
19
|
+
"bun",
|
|
20
|
+
"deno",
|
|
21
|
+
"langgraph",
|
|
22
|
+
"agent-protocol",
|
|
23
|
+
"sse"
|
|
24
|
+
],
|
|
25
|
+
"type": "module",
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"module": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist",
|
|
38
|
+
"LICENSE",
|
|
39
|
+
"README.md"
|
|
40
|
+
],
|
|
41
|
+
"sideEffects": false,
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@skein-js/server-kit": "0.12.0",
|
|
44
|
+
"@skein-js/core": "0.12.0",
|
|
45
|
+
"@skein-js/agent-protocol": "0.12.0"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@langchain/langgraph": "^1.4.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@langchain/langgraph": "^1.4.0"
|
|
52
|
+
},
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"access": "public"
|
|
55
|
+
}
|
|
56
|
+
}
|