@skein-js/server-kit 0.6.1

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 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/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # @skein-js/server-kit
2
+
3
+ > Shared, framework-agnostic building blocks for skein-js HTTP adapters.
4
+
5
+ Part of **[skein-js](../../README.md)** — a TypeScript [Agent Protocol](https://github.com/langchain-ai/agent-protocol) server for [LangGraph.js](https://github.com/langchain-ai/langgraphjs), and a drop-in replacement for the LangGraph CLI.
6
+
7
+ This package is the common ground the framework adapters ([`@skein-js/express`](../server-express),
8
+ [`@skein-js/fastify`](../server-fastify), [`@skein-js/nestjs`](../server-nestjs),
9
+ [`@skein-js/nextjs`](../server-nextjs)) stand on — so no adapter has to depend on another (or on
10
+ Express) just to reuse it. It holds the framework-agnostic pieces (runtime assembly, dev-state import,
11
+ CORS, and the Node-`http` transport the Node-based adapters share); each adapter still writes only the
12
+ thin request/response shim its framework needs over the [`@skein-js/agent-protocol`](../agent-protocol)
13
+ handler table.
14
+
15
+ ## What's here
16
+
17
+ - **Runtime resolution** — `resolveProtocolRuntime`: turn a `{ config } | { deps }` bag into a live
18
+ runtime (assistants seeded, worker started) — the step every adapter runs before mounting routes.
19
+ - **In-memory dev runtime** — `loadInMemoryRuntime` / `loadReloadableInMemoryRuntime`: assemble a
20
+ `ProtocolDeps` backed by in-process drivers from a `langgraph.json`. This is what powers `skein dev`
21
+ and every adapter's `{ config }` convenience path (hot-reload + snapshot/restore included).
22
+ - **LangGraph dev-state import** — `readLanggraphDevState` / `loadSnapshotIntoStore` /
23
+ `describeSnapshot`: read an existing `.langgraph_api/` directory and reconstruct skein's own
24
+ `DevStateSnapshot`, so adopting skein carries all local state over losslessly.
25
+ - **CORS** — `corsFromHttpConfig` / `toCorsOptions` map a `langgraph.json` `http.cors` block to
26
+ `cors`-style `CorsOptions`; `allowedOrigin` / `corsResponseHeaders` / `applyNodeCors` /
27
+ `sendNodePreflight` derive CORS headers for the adapters without a CORS middleware of their own
28
+ (an unset origin resolves to `*`, never a reflected origin, so it can't pair with credentials).
29
+ - **Node transport** — `sendNodeResponse` / `sendNodeError`: serialize a `ProtocolResponse` (JSON / 204
30
+ / SSE) onto a Node `ServerResponse`, shared by the NestJS + Next.js Pages Router adapters.
31
+
32
+ > The route table itself (`skeinRoutes`) is **not** here — it lives with the engine in
33
+ > [`@skein-js/agent-protocol`](../agent-protocol), since it references the handler names. Adapters
34
+ > import it from there.
35
+
36
+ ## Learn more
37
+
38
+ - [Building your own adapter](../../docs/building-an-adapter.md)
39
+ - [skein-js overview](../../docs/index.md)
40
+
41
+ ## License
42
+
43
+ [Apache-2.0](../../LICENSE)
@@ -0,0 +1,169 @@
1
+ import { ProtocolRuntime, Logger, ProtocolDeps, ProtocolResponse } from '@skein-js/agent-protocol';
2
+ import { ModuleImporter, GraphSchemas } from '@skein-js/config';
3
+ import { CorsOptions } from 'cors';
4
+ export { CorsOptions } from 'cors';
5
+ import { MemoryStoreSnapshot } from '@skein-js/storage-memory';
6
+ import { BaseCheckpointSaver } from '@langchain/langgraph';
7
+ import { SkeinStore } from '@skein-js/core';
8
+ import { ServerResponse } from 'node:http';
9
+
10
+ interface SkeinRuntimeCommonOptions {
11
+ logger?: Logger;
12
+ /**
13
+ * Cross-origin access for browser clients (Agent Chat UI, React `useStream`). When omitted, CORS is
14
+ * driven by the config's `http.cors` block (LangGraph-compatible) and is otherwise **off** — we do
15
+ * not default to LangGraph's permissive `origin: "*"`. `true` reflects the request origin (dev),
16
+ * `CorsOptions` restricts origins for production, `false` forces it off. An explicit value wins.
17
+ */
18
+ cors?: boolean | CorsOptions;
19
+ /**
20
+ * Eager-load every declared graph at boot instead of lazily on first request, so graph import
21
+ * errors surface at startup. Load failures are logged, not thrown, so one bad graph never takes the
22
+ * server down.
23
+ */
24
+ warm?: boolean;
25
+ }
26
+ /** Either point at a `langgraph.json` (in-memory runtime) or inject a ready `ProtocolDeps`. */
27
+ type SkeinRuntimeOptions = SkeinRuntimeCommonOptions & ({
28
+ config: string;
29
+ /**
30
+ * How graph modules are imported for the in-memory runtime. Defaults to a native dynamic
31
+ * `import()`; `skein dev` injects a vite-backed importer for TypeScript graphs.
32
+ */
33
+ importModule?: ModuleImporter;
34
+ deps?: never;
35
+ } | {
36
+ deps: ProtocolDeps;
37
+ config?: never;
38
+ importModule?: never;
39
+ });
40
+ interface ResolvedProtocolRuntime {
41
+ /** The wired runtime — assistants seeded and the background worker already started. */
42
+ runtime: ProtocolRuntime;
43
+ /** CORS mapped from the config's `http.cors`, or `undefined` for the injected-`deps` path. */
44
+ cors?: CorsOptions;
45
+ }
46
+ /**
47
+ * Build a `ProtocolRuntime` from adapter options: resolve `deps` (injected, or fresh in-memory
48
+ * drivers from a `langgraph.json`), seed one assistant per declared graph, optionally warm the
49
+ * graphs, and start the background run worker. Returns the runtime plus any CORS derived from the
50
+ * config so the adapter can apply it. The caller owns shutdown (`runtime.worker.stop()`).
51
+ */
52
+ declare function resolveProtocolRuntime(options: SkeinRuntimeOptions): Promise<ResolvedProtocolRuntime>;
53
+
54
+ /** The checkpoint tuple `[checkpoint, metadata, parentId?]` with the blobs base64-encoded. */
55
+ type SerializedCheckpointTuple = [string, string, string | undefined];
56
+ /** `MemorySaver.storage` (thread → namespace → checkpointId → tuple) with blobs base64-encoded. */
57
+ type SerializedCheckpointStorage = Record<string, Record<string, Record<string, SerializedCheckpointTuple>>>;
58
+ /** `MemorySaver.writes` (key → taskId+idx → `[taskId, channel, blob]`) with the blob base64-encoded. */
59
+ type SerializedCheckpointWrites = Record<string, Record<string, [string, string, string]>>;
60
+ interface CheckpointerSnapshot {
61
+ storage: SerializedCheckpointStorage;
62
+ writes: SerializedCheckpointWrites;
63
+ }
64
+ /** A JSON-serializable snapshot of the whole in-memory dev runtime. */
65
+ interface DevStateSnapshot {
66
+ version: 1;
67
+ store: MemoryStoreSnapshot;
68
+ checkpoints: CheckpointerSnapshot;
69
+ }
70
+
71
+ interface InMemoryRuntimeConfig {
72
+ /** In-memory `ProtocolDeps` (store, queue, bus, checkpointer) around the config's graphs. */
73
+ deps: ProtocolDeps;
74
+ /** CORS mapped from the config's `http.cors`, or `undefined` when none is declared. */
75
+ cors?: CorsOptions;
76
+ }
77
+ /** Load `langgraph.json`, wiring fresh in-memory drivers and reading its `http.cors` for the adapter. */
78
+ declare function loadInMemoryRuntime(configPath: string, importModule?: ModuleImporter, staticSchemas?: Record<string, GraphSchemas>): Promise<InMemoryRuntimeConfig>;
79
+ interface ReloadableInMemoryRuntime extends InMemoryRuntimeConfig {
80
+ /**
81
+ * Re-read the config and swap in freshly imported graphs, keeping the same drivers. Because the
82
+ * run engine calls `graphs.load()` per run (it never caches the compiled graph itself), the next
83
+ * run picks up the new code while every thread, run, checkpoint, and store item survives. This is
84
+ * what lets `skein dev` hot-reload graph source without dropping in-memory state.
85
+ */
86
+ reloadGraphs(): Promise<void>;
87
+ /** A JSON-serializable snapshot of all dev state (protocol store + checkpoints). */
88
+ snapshotState(): DevStateSnapshot;
89
+ /** Restore dev state from a {@link snapshotState} — call before the server starts serving. */
90
+ hydrateState(snapshot: DevStateSnapshot): void;
91
+ }
92
+ /**
93
+ * Like {@link loadInMemoryRuntime}, but the returned `deps.graphs` delegates to a swappable config
94
+ * registry so graphs can be reloaded in place, and it can snapshot/restore its dev state. `skein
95
+ * dev` pairs this with vite's watcher (clear vite's cache, then `reloadGraphs()` — no server
96
+ * restart, no lost state) and with on-disk JSON persistence across restarts.
97
+ */
98
+ declare function loadReloadableInMemoryRuntime(configPath: string, importModule?: ModuleImporter, staticSchemas?: Record<string, GraphSchemas>): Promise<ReloadableInMemoryRuntime>;
99
+
100
+ /**
101
+ * Read a LangGraph `.langgraph_api/` directory and reconstruct skein's `DevStateSnapshot`.
102
+ * Returns `null` when the directory holds none of the expected files (nothing to import).
103
+ */
104
+ declare function readLanggraphDevState(langgraphApiDir: string): Promise<DevStateSnapshot | null>;
105
+ /** Row/checkpoint counts in a snapshot, for CLI + log summaries. */
106
+ interface DevStateCounts {
107
+ assistants: number;
108
+ threads: number;
109
+ runs: number;
110
+ items: number;
111
+ /** Threads that carry graph checkpoint history. */
112
+ checkpointedThreads: number;
113
+ }
114
+ declare function describeSnapshot(snapshot: DevStateSnapshot): DevStateCounts;
115
+ /**
116
+ * Load a `DevStateSnapshot` into a live store + checkpointer — the sink for importing into a real
117
+ * skein deployment (e.g. Postgres). Resource rows go through the driver's `restore` (ids +
118
+ * timestamps preserved, `ON CONFLICT DO NOTHING` so re-runs are safe); checkpoints — graph state +
119
+ * full history — are copied via the public checkpointer API. Throws if the store can't bulk-restore
120
+ * (both first-party drivers can); a custom driver must implement `restore` to be an import target.
121
+ */
122
+ declare function loadSnapshotIntoStore(snapshot: DevStateSnapshot, store: SkeinStore, checkpointer: BaseCheckpointSaver): Promise<void>;
123
+
124
+ /** The `http.cors` block of a langgraph.json — LangGraph's field names (snake_case). */
125
+ interface LanggraphCorsConfig {
126
+ allow_origins?: string[];
127
+ allow_origin_regex?: string;
128
+ allow_methods?: string[];
129
+ allow_headers?: string[];
130
+ allow_credentials?: boolean;
131
+ expose_headers?: string[];
132
+ max_age?: number;
133
+ }
134
+ /** Translate a LangGraph `http.cors` config into `cors` middleware options. */
135
+ declare function toCorsOptions(config: LanggraphCorsConfig): CorsOptions;
136
+ /** Read `http.cors` from a langgraph.json `http` block, mapped to `CorsOptions`, or `undefined`. */
137
+ declare function corsFromHttpConfig(http: unknown): CorsOptions | undefined;
138
+
139
+ type CorsSetting = true | CorsOptions;
140
+ /**
141
+ * Resolve the `Access-Control-Allow-Origin` value for a request origin, or `undefined` to deny.
142
+ * An unset `origin` resolves to `*` (matching the `cors`/`@fastify/cors` default) rather than
143
+ * reflecting the caller's origin, so it can never be paired with credentials into a wildcard bypass.
144
+ */
145
+ declare function allowedOrigin(requestOrigin: string | undefined, cors: CorsSetting): string | undefined;
146
+ /** Join a `string | string[]` option into a comma list, or `undefined` when absent. */
147
+ declare function joinList(value: string | string[] | undefined): string | undefined;
148
+ /** The CORS response headers to merge onto an actual (non-preflight) response. */
149
+ declare function corsResponseHeaders(requestOrigin: string | undefined, cors: CorsSetting): Record<string, string>;
150
+ /** The preflight response headers for an `OPTIONS` request. */
151
+ declare function corsPreflightHeaders(requestOrigin: string | undefined, requestedHeaders: string | undefined, cors: CorsSetting): Record<string, string>;
152
+ /** Set CORS headers on a Node response for an actual request (before the status line is written). */
153
+ declare function applyNodeCors(reqHeaders: {
154
+ origin?: string | string[];
155
+ [key: string]: string | string[] | undefined;
156
+ }, res: ServerResponse, cors: CorsSetting): void;
157
+ /** Answer an `OPTIONS` preflight on a Node response with a 204 + CORS headers. */
158
+ declare function sendNodePreflight(reqHeaders: {
159
+ origin?: string | string[];
160
+ "access-control-request-headers"?: string | string[];
161
+ [key: string]: string | string[] | undefined;
162
+ }, res: ServerResponse, cors: CorsSetting): void;
163
+
164
+ /** Write a `ProtocolResponse` back onto the Node `res`, streaming when it is an SSE response. */
165
+ declare function sendNodeResponse(response: ProtocolResponse, res: ServerResponse): Promise<void>;
166
+ /** Serialize a caught error onto the Node `res`, using the protocol status when the error carries one. */
167
+ declare function sendNodeError(error: unknown, res: ServerResponse, logger?: Logger, adapterName?: string): void;
168
+
169
+ export { type CorsSetting, type DevStateCounts, type DevStateSnapshot, type InMemoryRuntimeConfig, type LanggraphCorsConfig, type ReloadableInMemoryRuntime, type ResolvedProtocolRuntime, type SkeinRuntimeCommonOptions, type SkeinRuntimeOptions, allowedOrigin, applyNodeCors, corsFromHttpConfig, corsPreflightHeaders, corsResponseHeaders, describeSnapshot, joinList, loadInMemoryRuntime, loadReloadableInMemoryRuntime, loadSnapshotIntoStore, readLanggraphDevState, resolveProtocolRuntime, sendNodeError, sendNodePreflight, sendNodeResponse, toCorsOptions };
package/dist/index.js ADDED
@@ -0,0 +1,629 @@
1
+ // src/resolve-runtime.ts
2
+ import {
3
+ createProtocolRuntime
4
+ } from "@skein-js/agent-protocol";
5
+
6
+ // src/in-memory-runtime.ts
7
+ import { MemorySaver } from "@langchain/langgraph";
8
+ import {
9
+ loadAuthEngine,
10
+ loadConfig
11
+ } from "@skein-js/config";
12
+ import { MemoryRunEventBus, MemoryRunQueue, MemorySkeinStore } from "@skein-js/storage-memory";
13
+
14
+ // src/cors-config.ts
15
+ var ALWAYS_EXPOSED_HEADERS = ["content-location", "x-pagination-total"];
16
+ function toCorsOptions(config) {
17
+ const options = {};
18
+ const allowAll = config.allow_origins?.includes("*") ?? false;
19
+ if (config.allow_origin_regex !== void 0) {
20
+ const pattern = new RegExp(`^(?:${config.allow_origin_regex})$`);
21
+ const listed = allowAll ? void 0 : new Set(config.allow_origins);
22
+ options.origin = (origin, callback) => callback(
23
+ null,
24
+ origin !== void 0 && (allowAll || pattern.test(origin) || (listed?.has(origin) ?? false))
25
+ );
26
+ } else if (config.allow_origins !== void 0) {
27
+ options.origin = allowAll ? "*" : config.allow_origins;
28
+ }
29
+ if (config.allow_methods !== void 0) options.methods = config.allow_methods;
30
+ if (config.allow_headers !== void 0) options.allowedHeaders = config.allow_headers;
31
+ if (config.allow_credentials !== void 0) options.credentials = config.allow_credentials;
32
+ if (config.max_age !== void 0) options.maxAge = config.max_age;
33
+ const exposed = /* @__PURE__ */ new Set([...ALWAYS_EXPOSED_HEADERS, ...config.expose_headers ?? []]);
34
+ options.exposedHeaders = [...exposed];
35
+ return options;
36
+ }
37
+ function corsFromHttpConfig(http) {
38
+ if (typeof http !== "object" || http === null) return void 0;
39
+ const cors = http.cors;
40
+ if (typeof cors !== "object" || cors === null) return void 0;
41
+ return toCorsOptions(cors);
42
+ }
43
+
44
+ // src/dev-persistence.ts
45
+ var toBase64 = (bytes) => Buffer.from(bytes).toString("base64");
46
+ var fromBase64 = (text) => new Uint8Array(Buffer.from(text, "base64"));
47
+ var mapValues = (record, fn) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, fn(value)]));
48
+ function snapshotCheckpointer(saver) {
49
+ return {
50
+ storage: mapValues(
51
+ saver.storage,
52
+ (namespaces) => mapValues(
53
+ namespaces,
54
+ (checkpoints) => mapValues(checkpoints, ([checkpoint, metadata, parentId]) => [
55
+ toBase64(checkpoint),
56
+ toBase64(metadata),
57
+ parentId
58
+ ])
59
+ )
60
+ ),
61
+ writes: mapValues(
62
+ saver.writes,
63
+ (taskWrites) => mapValues(taskWrites, ([taskId, channel, blob]) => [
64
+ taskId,
65
+ channel,
66
+ toBase64(blob)
67
+ ])
68
+ )
69
+ };
70
+ }
71
+ function hydrateCheckpointer(saver, snapshot) {
72
+ saver.storage = mapValues(
73
+ snapshot.storage,
74
+ (namespaces) => mapValues(
75
+ namespaces,
76
+ (checkpoints) => mapValues(
77
+ checkpoints,
78
+ ([checkpoint, metadata, parentId]) => [
79
+ fromBase64(checkpoint),
80
+ fromBase64(metadata),
81
+ parentId
82
+ ]
83
+ )
84
+ )
85
+ );
86
+ saver.writes = mapValues(
87
+ snapshot.writes,
88
+ (taskWrites) => mapValues(taskWrites, ([taskId, channel, blob]) => [
89
+ taskId,
90
+ channel,
91
+ fromBase64(blob)
92
+ ])
93
+ );
94
+ }
95
+
96
+ // src/in-memory-runtime.ts
97
+ function toGraphResolver(graphs) {
98
+ return {
99
+ ids: graphs.ids,
100
+ load: (graphId) => graphs.load(graphId),
101
+ schemas: async (graphId) => await graphs.schemas(graphId)
102
+ };
103
+ }
104
+ function buildInMemoryDeps(graphs) {
105
+ return {
106
+ store: new MemorySkeinStore(),
107
+ graphs,
108
+ queue: new MemoryRunQueue(),
109
+ bus: new MemoryRunEventBus(),
110
+ checkpointer: new MemorySaver()
111
+ };
112
+ }
113
+ async function loadInMemoryRuntime(configPath, importModule, staticSchemas) {
114
+ const { graphs, config, configDir } = await loadConfig({
115
+ configPath,
116
+ importModule,
117
+ staticSchemas
118
+ });
119
+ const deps = buildInMemoryDeps(toGraphResolver(graphs));
120
+ deps.auth = await loadAuthEngine(config.auth, { configDir, importModule });
121
+ return {
122
+ deps,
123
+ cors: corsFromHttpConfig(config.http)
124
+ };
125
+ }
126
+ async function loadReloadableInMemoryRuntime(configPath, importModule, staticSchemas) {
127
+ const first = await loadConfig({ configPath, importModule, staticSchemas });
128
+ let current = first.graphs;
129
+ const graphs = {
130
+ ids: first.graphs.ids,
131
+ load: (graphId) => current.load(graphId),
132
+ schemas: async (graphId) => await current.schemas(graphId)
133
+ };
134
+ const store = new MemorySkeinStore();
135
+ const checkpointer = new MemorySaver();
136
+ const deps = {
137
+ store,
138
+ graphs,
139
+ queue: new MemoryRunQueue(),
140
+ bus: new MemoryRunEventBus(),
141
+ checkpointer,
142
+ auth: await loadAuthEngine(first.config.auth, { configDir: first.configDir, importModule })
143
+ };
144
+ return {
145
+ deps,
146
+ cors: corsFromHttpConfig(first.config.http),
147
+ reloadGraphs: async () => {
148
+ current = (await loadConfig({ configPath, importModule, staticSchemas })).graphs;
149
+ },
150
+ snapshotState: () => ({
151
+ version: 1,
152
+ store: store.snapshot(),
153
+ checkpoints: snapshotCheckpointer(checkpointer)
154
+ }),
155
+ hydrateState: (snapshot) => {
156
+ store.hydrate(snapshot.store);
157
+ hydrateCheckpointer(checkpointer, snapshot.checkpoints);
158
+ }
159
+ };
160
+ }
161
+
162
+ // src/resolve-runtime.ts
163
+ async function resolveProtocolRuntime(options) {
164
+ let deps;
165
+ let corsFromConfig;
166
+ if (options.deps) {
167
+ deps = options.deps;
168
+ } else {
169
+ const loaded = await loadInMemoryRuntime(options.config, options.importModule);
170
+ deps = loaded.deps;
171
+ corsFromConfig = loaded.cors;
172
+ }
173
+ const runtime = createProtocolRuntime(deps);
174
+ await runtime.service.assistants.registerGraphAssistants();
175
+ if (options.warm) {
176
+ await Promise.all(
177
+ deps.graphs.ids.map(
178
+ (graphId) => deps.graphs.load(graphId).catch((error) => {
179
+ options.logger?.warn(`Failed to warm graph "${graphId}".`, error);
180
+ })
181
+ )
182
+ );
183
+ }
184
+ runtime.worker.start();
185
+ return { runtime, cors: corsFromConfig };
186
+ }
187
+
188
+ // src/langgraph-import.ts
189
+ import { readFile } from "fs/promises";
190
+ import path from "path";
191
+ import {
192
+ MemorySaver as MemorySaver2
193
+ } from "@langchain/langgraph";
194
+ import {
195
+ isTerminalRunStatus
196
+ } from "@skein-js/core";
197
+ import { SuperJSON } from "superjson";
198
+ import { z } from "zod";
199
+ var OPS_FILE = ".langgraphjs_ops.json";
200
+ var STORE_FILE = ".langgraphjs_api.store.json";
201
+ var CHECKPOINTER_FILE = ".langgraphjs_api.checkpointer.json";
202
+ var langgraphSuperjson = new SuperJSON();
203
+ langgraphSuperjson.registerCustom(
204
+ {
205
+ isApplicable: (value) => value instanceof Uint8Array,
206
+ serialize: (value) => Buffer.from(value).toString("base64"),
207
+ deserialize: (value) => new Uint8Array(Buffer.from(value, "base64"))
208
+ },
209
+ "Uint8Array"
210
+ );
211
+ var timestamp = z.union([z.date(), z.string()]).optional();
212
+ var jsonObject = z.record(z.unknown());
213
+ var langgraphAssistantSchema = z.object({
214
+ assistant_id: z.string(),
215
+ graph_id: z.string(),
216
+ name: z.string().optional(),
217
+ description: z.string().nullish(),
218
+ config: jsonObject.optional(),
219
+ context: z.unknown().optional(),
220
+ metadata: jsonObject.optional(),
221
+ version: z.number().optional(),
222
+ created_at: timestamp,
223
+ updated_at: timestamp
224
+ }).passthrough();
225
+ var langgraphAssistantVersionSchema = z.object({
226
+ assistant_id: z.string(),
227
+ version: z.number(),
228
+ graph_id: z.string(),
229
+ name: z.string().optional(),
230
+ description: z.string().nullish(),
231
+ config: jsonObject.optional(),
232
+ context: z.unknown().optional(),
233
+ metadata: jsonObject.optional(),
234
+ created_at: timestamp
235
+ }).passthrough();
236
+ var langgraphThreadSchema = z.object({
237
+ thread_id: z.string(),
238
+ status: z.string().optional(),
239
+ metadata: jsonObject.optional(),
240
+ values: jsonObject.optional(),
241
+ interrupts: jsonObject.optional(),
242
+ created_at: timestamp,
243
+ updated_at: timestamp
244
+ }).passthrough();
245
+ var langgraphRunSchema = z.object({
246
+ run_id: z.string(),
247
+ thread_id: z.string(),
248
+ assistant_id: z.string(),
249
+ status: z.string().optional(),
250
+ metadata: jsonObject.optional(),
251
+ multitask_strategy: z.string().nullish(),
252
+ kwargs: jsonObject.optional(),
253
+ created_at: timestamp,
254
+ updated_at: timestamp
255
+ }).passthrough();
256
+ var langgraphOpsSchema = z.object({
257
+ assistants: z.record(langgraphAssistantSchema).optional(),
258
+ assistant_versions: z.array(langgraphAssistantVersionSchema).optional(),
259
+ threads: z.record(langgraphThreadSchema).optional(),
260
+ runs: z.record(langgraphRunSchema).optional()
261
+ }).passthrough();
262
+ var langgraphStoreItemSchema = z.object({
263
+ namespace: z.array(z.string()),
264
+ key: z.string(),
265
+ value: jsonObject,
266
+ createdAt: timestamp,
267
+ updatedAt: timestamp
268
+ }).passthrough();
269
+ var langgraphStoreFileSchema = z.object({ data: z.map(z.string(), z.map(z.string(), langgraphStoreItemSchema)).optional() }).passthrough();
270
+ var langgraphCheckpointerSchema = z.object({ storage: jsonObject, writes: jsonObject }).passthrough();
271
+ async function readSuperjsonFile(filepath) {
272
+ let text;
273
+ try {
274
+ text = await readFile(filepath, "utf8");
275
+ } catch {
276
+ return null;
277
+ }
278
+ try {
279
+ return langgraphSuperjson.parse(text) ?? null;
280
+ } catch (error) {
281
+ throw new Error(
282
+ `Could not parse LangGraph state file "${filepath}": ${error instanceof Error ? error.message : String(error)}`
283
+ );
284
+ }
285
+ }
286
+ function validateShape(schema, value, label) {
287
+ const result = schema.safeParse(value);
288
+ if (!result.success) {
289
+ const detail = result.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
290
+ throw new Error(`Invalid LangGraph ${label}: ${detail}`);
291
+ }
292
+ return result.data;
293
+ }
294
+ function toIso(value, fallback) {
295
+ if (value instanceof Date) return value.toISOString();
296
+ if (typeof value === "string") return value;
297
+ return fallback;
298
+ }
299
+ function toAssistant(row, now) {
300
+ return {
301
+ assistant_id: row.assistant_id,
302
+ graph_id: row.graph_id,
303
+ name: row.name ?? row.graph_id,
304
+ description: row.description ?? void 0,
305
+ config: row.config ?? {},
306
+ context: row.context ?? {},
307
+ metadata: row.metadata ?? {},
308
+ version: row.version ?? 1,
309
+ created_at: toIso(row.created_at, now),
310
+ updated_at: toIso(row.updated_at, now)
311
+ };
312
+ }
313
+ function toAssistantVersion(row, now) {
314
+ return {
315
+ assistant_id: row.assistant_id,
316
+ version: row.version,
317
+ graph_id: row.graph_id,
318
+ name: row.name ?? row.graph_id,
319
+ description: row.description ?? void 0,
320
+ config: row.config ?? {},
321
+ context: row.context ?? {},
322
+ metadata: row.metadata ?? {},
323
+ created_at: toIso(row.created_at, now)
324
+ };
325
+ }
326
+ function toThread(row, now) {
327
+ const createdAt = toIso(row.created_at, now);
328
+ const updatedAt = toIso(row.updated_at, createdAt);
329
+ return {
330
+ thread_id: row.thread_id,
331
+ status: row.status ?? "idle",
332
+ metadata: row.metadata ?? {},
333
+ values: row.values ?? {},
334
+ interrupts: row.interrupts ?? {},
335
+ created_at: createdAt,
336
+ updated_at: updatedAt,
337
+ state_updated_at: updatedAt
338
+ };
339
+ }
340
+ function toRun(row, now) {
341
+ const createdAt = toIso(row.created_at, now);
342
+ const status = row.status ?? "success";
343
+ return {
344
+ run_id: row.run_id,
345
+ thread_id: row.thread_id,
346
+ assistant_id: row.assistant_id,
347
+ status: isTerminalRunStatus(status) ? status : "error",
348
+ metadata: row.metadata ?? {},
349
+ multitask_strategy: row.multitask_strategy ?? null,
350
+ created_at: createdAt,
351
+ updated_at: toIso(row.updated_at, createdAt)
352
+ };
353
+ }
354
+ function toRunKwargs(kwargs) {
355
+ if (!kwargs) return {};
356
+ const {
357
+ input,
358
+ command,
359
+ config,
360
+ context,
361
+ stream_mode,
362
+ interrupt_before,
363
+ interrupt_after,
364
+ webhook
365
+ } = kwargs;
366
+ return {
367
+ input,
368
+ command,
369
+ config,
370
+ context,
371
+ stream_mode,
372
+ interrupt_before,
373
+ interrupt_after,
374
+ ...typeof webhook === "string" ? { webhook } : {}
375
+ };
376
+ }
377
+ async function readLanggraphDevState(langgraphApiDir) {
378
+ const now = (/* @__PURE__ */ new Date()).toISOString();
379
+ const [opsRaw, storeRaw, checkpointerRaw] = await Promise.all([
380
+ readSuperjsonFile(path.join(langgraphApiDir, OPS_FILE)),
381
+ readSuperjsonFile(path.join(langgraphApiDir, STORE_FILE)),
382
+ readSuperjsonFile(path.join(langgraphApiDir, CHECKPOINTER_FILE))
383
+ ]);
384
+ if (!opsRaw && !storeRaw && !checkpointerRaw) return null;
385
+ const ops = opsRaw ? validateShape(langgraphOpsSchema, opsRaw, OPS_FILE) : null;
386
+ const storeFile = storeRaw ? validateShape(langgraphStoreFileSchema, storeRaw, STORE_FILE) : null;
387
+ const checkpointerFile = checkpointerRaw ? validateShape(langgraphCheckpointerSchema, checkpointerRaw, CHECKPOINTER_FILE) : null;
388
+ const runEntries = Object.entries(ops?.runs ?? {});
389
+ const items = [];
390
+ if (storeFile?.data) {
391
+ for (const namespaceItems of storeFile.data.values()) {
392
+ for (const stored of namespaceItems.values()) {
393
+ const item = {
394
+ namespace: stored.namespace,
395
+ key: stored.key,
396
+ value: stored.value,
397
+ createdAt: toIso(stored.createdAt, now),
398
+ updatedAt: toIso(stored.updatedAt, now)
399
+ };
400
+ items.push([JSON.stringify([stored.namespace, stored.key]), item]);
401
+ }
402
+ }
403
+ }
404
+ const store = {
405
+ assistants: Object.entries(ops?.assistants ?? {}).map(([id, row]) => [
406
+ id,
407
+ toAssistant(row, now)
408
+ ]),
409
+ assistantVersions: (ops?.assistant_versions ?? []).map((row) => [
410
+ JSON.stringify([row.assistant_id, row.version]),
411
+ toAssistantVersion(row, now)
412
+ ]),
413
+ threads: Object.entries(ops?.threads ?? {}).map(([id, row]) => [id, toThread(row, now)]),
414
+ runs: runEntries.map(([id, row]) => [id, toRun(row, now)]),
415
+ runKwargs: runEntries.map(([id, row]) => [id, toRunKwargs(row.kwargs)]),
416
+ items
417
+ };
418
+ let checkpoints = { storage: {}, writes: {} };
419
+ if (checkpointerFile) {
420
+ const saver = new MemorySaver2();
421
+ saver.storage = checkpointerFile.storage;
422
+ saver.writes = checkpointerFile.writes;
423
+ checkpoints = snapshotCheckpointer(saver);
424
+ }
425
+ return { version: 1, store, checkpoints };
426
+ }
427
+ function describeSnapshot(snapshot) {
428
+ return {
429
+ assistants: snapshot.store.assistants.length,
430
+ threads: snapshot.store.threads.length,
431
+ runs: snapshot.store.runs.length,
432
+ items: snapshot.store.items.length,
433
+ checkpointedThreads: Object.keys(snapshot.checkpoints.storage).length
434
+ };
435
+ }
436
+ function supportsRestore(store) {
437
+ return typeof store.restore === "function";
438
+ }
439
+ async function copyCheckpoints(snapshot, target) {
440
+ const source = new MemorySaver2();
441
+ hydrateCheckpointer(source, snapshot);
442
+ const tuples = [];
443
+ for await (const tuple of source.list({})) tuples.push(tuple);
444
+ tuples.reverse();
445
+ for (const tuple of tuples) {
446
+ const configurable = tuple.config.configurable ?? {};
447
+ const putConfig = {
448
+ configurable: {
449
+ thread_id: configurable.thread_id,
450
+ checkpoint_ns: configurable.checkpoint_ns ?? "",
451
+ // `put` reads `checkpoint_id` as the PARENT pointer; the child's own id is `checkpoint.id`.
452
+ checkpoint_id: tuple.parentConfig?.configurable?.checkpoint_id
453
+ }
454
+ };
455
+ const stored = await target.put(
456
+ putConfig,
457
+ tuple.checkpoint,
458
+ tuple.metadata ?? {},
459
+ tuple.checkpoint.channel_versions ?? {}
460
+ );
461
+ const writesByTask = /* @__PURE__ */ new Map();
462
+ for (const [taskId, channel, value] of tuple.pendingWrites ?? []) {
463
+ const writes = writesByTask.get(taskId) ?? [];
464
+ writes.push([channel, value]);
465
+ writesByTask.set(taskId, writes);
466
+ }
467
+ for (const [taskId, writes] of writesByTask) {
468
+ await target.putWrites(stored, writes, taskId);
469
+ }
470
+ }
471
+ }
472
+ async function loadSnapshotIntoStore(snapshot, store, checkpointer) {
473
+ if (!supportsRestore(store)) {
474
+ throw new Error(
475
+ "Target store does not support bulk import (no restore() method). Use the in-memory or Postgres driver, or implement restore() on your SkeinStore."
476
+ );
477
+ }
478
+ await store.restore(snapshot.store);
479
+ await copyCheckpoints(snapshot.checkpoints, checkpointer);
480
+ }
481
+
482
+ // src/cors-runtime.ts
483
+ function allowedOrigin(requestOrigin, cors) {
484
+ const origin = cors === true ? true : cors.origin;
485
+ if (origin === true) return requestOrigin ?? "*";
486
+ if (origin === void 0 || origin === "*") return "*";
487
+ if (typeof origin === "string") return origin;
488
+ if (Array.isArray(origin)) {
489
+ return requestOrigin && origin.includes(requestOrigin) ? requestOrigin : void 0;
490
+ }
491
+ if (origin instanceof RegExp) {
492
+ const anchored = new RegExp(`^(?:${origin.source})$`, origin.flags.replace("g", ""));
493
+ return requestOrigin && anchored.test(requestOrigin) ? requestOrigin : void 0;
494
+ }
495
+ if (typeof origin === "function") {
496
+ let verdict;
497
+ origin(
498
+ requestOrigin,
499
+ (_err, allow) => {
500
+ verdict = allow;
501
+ }
502
+ );
503
+ if (verdict === true) return requestOrigin ?? "*";
504
+ if (typeof verdict === "string") return verdict;
505
+ return void 0;
506
+ }
507
+ return void 0;
508
+ }
509
+ function joinList(value) {
510
+ if (value === void 0) return void 0;
511
+ return [].concat(value).join(",");
512
+ }
513
+ function corsResponseHeaders(requestOrigin, cors) {
514
+ const allow = allowedOrigin(requestOrigin, cors);
515
+ if (allow === void 0) return {};
516
+ const headers = { "access-control-allow-origin": allow };
517
+ if (allow !== "*") headers["vary"] = "origin";
518
+ if (cors !== true && cors.credentials) headers["access-control-allow-credentials"] = "true";
519
+ const exposed = cors !== true ? joinList(cors.exposedHeaders) : void 0;
520
+ if (exposed) headers["access-control-expose-headers"] = exposed;
521
+ return headers;
522
+ }
523
+ function corsPreflightHeaders(requestOrigin, requestedHeaders, cors) {
524
+ const headers = corsResponseHeaders(requestOrigin, cors);
525
+ headers["access-control-allow-methods"] = (cors !== true ? joinList(cors.methods) : void 0) ?? "GET,POST,PUT,PATCH,DELETE,OPTIONS";
526
+ const allowedHeaders = (cors !== true ? joinList(cors.allowedHeaders) : void 0) ?? requestedHeaders;
527
+ if (allowedHeaders) headers["access-control-allow-headers"] = allowedHeaders;
528
+ if (cors !== true && typeof cors.maxAge === "number") {
529
+ headers["access-control-max-age"] = String(cors.maxAge);
530
+ }
531
+ return headers;
532
+ }
533
+ function firstHeader(value) {
534
+ return Array.isArray(value) ? value[0] : value;
535
+ }
536
+ function applyNodeCors(reqHeaders, res, cors) {
537
+ const headers = corsResponseHeaders(firstHeader(reqHeaders.origin), cors);
538
+ for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
539
+ }
540
+ function sendNodePreflight(reqHeaders, res, cors) {
541
+ const headers = corsPreflightHeaders(
542
+ firstHeader(reqHeaders.origin),
543
+ firstHeader(reqHeaders["access-control-request-headers"]),
544
+ cors
545
+ );
546
+ res.writeHead(204, headers).end();
547
+ }
548
+
549
+ // src/node-transport.ts
550
+ import { SSE_HEADERS } from "@skein-js/agent-protocol";
551
+ import { isSkeinHttpError, serializeWireJson } from "@skein-js/core";
552
+ var ignoreStreamError = () => {
553
+ };
554
+ async function pipeServerSentEvents(status, events, res) {
555
+ res.writeHead(status, SSE_HEADERS);
556
+ res.flushHeaders();
557
+ const iterator = events[Symbol.asyncIterator]();
558
+ let clientDisconnected = false;
559
+ const releaseOnClientClose = () => {
560
+ clientDisconnected = true;
561
+ void Promise.resolve(iterator.return?.(void 0)).catch(ignoreStreamError);
562
+ };
563
+ res.once("close", releaseOnClientClose);
564
+ res.on("error", ignoreStreamError);
565
+ try {
566
+ for (; ; ) {
567
+ const next = await iterator.next();
568
+ if (next.done || clientDisconnected) break;
569
+ res.write(next.value);
570
+ }
571
+ } finally {
572
+ res.removeListener("close", releaseOnClientClose);
573
+ if (!res.writableEnded) res.end();
574
+ }
575
+ }
576
+ async function sendNodeResponse(response, res) {
577
+ switch (response.kind) {
578
+ case "json":
579
+ res.writeHead(response.status, { "content-type": "application/json" });
580
+ res.end(serializeWireJson(response.body));
581
+ return;
582
+ case "empty":
583
+ res.writeHead(response.status).end();
584
+ return;
585
+ case "sse":
586
+ await pipeServerSentEvents(response.status, response.events, res);
587
+ return;
588
+ }
589
+ }
590
+ function sendNodeError(error, res, logger, adapterName = "skein") {
591
+ if (res.headersSent) {
592
+ if (!isSkeinHttpError(error)) logger?.error("Unhandled error after headers were sent.", error);
593
+ if (!res.writableEnded) res.end();
594
+ return;
595
+ }
596
+ if (isSkeinHttpError(error)) {
597
+ res.writeHead(error.status, { "content-type": "application/json" });
598
+ res.end(
599
+ JSON.stringify({
600
+ status: error.status,
601
+ message: error.message,
602
+ ...error.code !== void 0 ? { code: error.code } : {},
603
+ ...error.details !== void 0 ? { details: error.details } : {}
604
+ })
605
+ );
606
+ return;
607
+ }
608
+ logger?.error(`Unhandled error in the ${adapterName} adapter.`, error);
609
+ res.writeHead(500, { "content-type": "application/json" });
610
+ res.end(JSON.stringify({ status: 500, message: "Internal Server Error" }));
611
+ }
612
+ export {
613
+ allowedOrigin,
614
+ applyNodeCors,
615
+ corsFromHttpConfig,
616
+ corsPreflightHeaders,
617
+ corsResponseHeaders,
618
+ describeSnapshot,
619
+ joinList,
620
+ loadInMemoryRuntime,
621
+ loadReloadableInMemoryRuntime,
622
+ loadSnapshotIntoStore,
623
+ readLanggraphDevState,
624
+ resolveProtocolRuntime,
625
+ sendNodeError,
626
+ sendNodePreflight,
627
+ sendNodeResponse,
628
+ toCorsOptions
629
+ };
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@skein-js/server-kit",
3
+ "version": "0.6.1",
4
+ "description": "Shared, framework-agnostic building blocks for skein-js HTTP adapters — in-memory dev runtime, LangGraph dev-state import, and langgraph.json CORS mapping.",
5
+ "license": "Apache-2.0",
6
+ "author": "Maina Wycliffe <wmmaina7@gmail.com>",
7
+ "homepage": "https://github.com/mainawycliffe/skein-js/tree/main/packages/server-kit#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/mainawycliffe/skein-js.git",
11
+ "directory": "packages/server-kit"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/mainawycliffe/skein-js/issues"
15
+ },
16
+ "keywords": [
17
+ "typescript",
18
+ "langgraph",
19
+ "agent-protocol",
20
+ "adapter",
21
+ "cors"
22
+ ],
23
+ "type": "module",
24
+ "main": "./dist/index.js",
25
+ "module": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "LICENSE",
36
+ "README.md"
37
+ ],
38
+ "sideEffects": false,
39
+ "engines": {
40
+ "node": ">=20"
41
+ },
42
+ "dependencies": {
43
+ "cors": "^2.8.5",
44
+ "superjson": "^2.2.6",
45
+ "zod": "^3.25.76",
46
+ "@skein-js/config": "0.6.1",
47
+ "@skein-js/core": "0.6.1",
48
+ "@skein-js/storage-memory": "0.6.1",
49
+ "@skein-js/agent-protocol": "0.6.1"
50
+ },
51
+ "peerDependencies": {
52
+ "@langchain/langgraph": "^1.4.0"
53
+ },
54
+ "devDependencies": {
55
+ "@langchain/core": "^1.2.0",
56
+ "@langchain/langgraph": "^1.4.0",
57
+ "@types/cors": "^2.8.17"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }