@skein-js/express 0.1.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 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,75 @@
1
+ # @skein-js/express
2
+
3
+ > Express adapter for skein-js — mount the Agent Protocol on an Express Router.
4
+
5
+ Part of **[skein-js](https://github.com/mainawycliffe/skein)** — 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
+ **Status:** 🚧 Pre-alpha — implemented; the v1 framework adapter.
8
+
9
+ ## What it does
10
+
11
+ Converts Express `req`/`res` into [`@skein-js/agent-protocol`](../agent-protocol)'s normalized request, dispatches to its handler table, and pipes JSON / `204` / `text/event-stream` responses back out. Ships a `createExpressServer` convenience, a `skeinRouter` that returns a mountable `Router`, and the pure `createHandlerRouter` shim for callers wiring their own drivers.
12
+
13
+ ## Reuse
14
+
15
+ Thin transport shim over [`@skein-js/agent-protocol`](../agent-protocol); adds no protocol logic of its own.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pnpm add @skein-js/express
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ The zero-setup server — reads a `langgraph.json`, wires in-memory drivers, and serves the Agent Protocol:
26
+
27
+ ```ts
28
+ import { createExpressServer } from "@skein-js/express";
29
+
30
+ const server = await createExpressServer({ config: "./langgraph.json" });
31
+ await server.listen(2024);
32
+ // ...later: await server.close();
33
+ ```
34
+
35
+ Or mount the router on an existing Express app:
36
+
37
+ ```ts
38
+ import express from "express";
39
+ import { skeinRouter } from "@skein-js/express";
40
+
41
+ const app = express();
42
+ const { router, runtime } = await skeinRouter({ config: "./langgraph.json" });
43
+ app.use(router);
44
+ app.listen(2024);
45
+ // runtime.worker.stop() to drain background runs on shutdown.
46
+ ```
47
+
48
+ Bring your own persistent drivers (e.g. Postgres + Redis for `skein up`) through the same seam:
49
+
50
+ ```ts
51
+ const { router } = await skeinRouter({ deps: myProtocolDeps });
52
+ ```
53
+
54
+ ### CORS
55
+
56
+ Browser clients (Agent Chat UI, React `useStream`) run on a different origin. CORS is **off by default** (non-permissive) and driven by the `http.cors` block of `langgraph.json`, matching the LangGraph CLI:
57
+
58
+ ```jsonc
59
+ {
60
+ "graphs": { "agent": "./agent.ts:graph" },
61
+ "http": { "cors": { "allow_origins": ["http://localhost:3000"] } },
62
+ }
63
+ ```
64
+
65
+ Override in code with the `cors` option: pass [`CorsOptions`](https://github.com/expressjs/cors#configuration-options) to restrict origins, `true` for permissive dev, or `false` to force it off.
66
+
67
+ ## Learn more
68
+
69
+ - [skein-js overview](../../docs/index.md)
70
+ - [Reuse-first architecture](../../docs/reuse.md)
71
+ - [Roadmap](../../docs/roadmap.md)
72
+
73
+ ## License
74
+
75
+ [Apache-2.0](../../LICENSE)
@@ -0,0 +1,168 @@
1
+ import { ProtocolRuntime, Logger, ProtocolDeps, ProtocolHandlers, ProtocolRequest, ProtocolResponse } from '@skein-js/agent-protocol';
2
+ import { ModuleImporter } from '@skein-js/config';
3
+ import { CorsOptions } from 'cors';
4
+ import { Router, Express, Request, Response } from 'express';
5
+ import { Server } from 'node:http';
6
+ import { MemoryStoreSnapshot } from '@skein-js/storage-memory';
7
+
8
+ interface SkeinRouterCommonOptions {
9
+ logger?: Logger;
10
+ /**
11
+ * Cross-origin access for browser clients (Agent Chat UI, React `useStream`). When omitted, CORS
12
+ * is driven by the config's `http.cors` block (LangGraph-compatible) and is otherwise **off** — we
13
+ * do not default to LangGraph's permissive `origin: "*"`. Set this to override: `CorsOptions` to
14
+ * restrict origins for `skein up`, `true` for permissive dev (reflect the request origin), or
15
+ * `false` to force it off. An explicit value wins over `http.cors`.
16
+ */
17
+ cors?: boolean | CorsOptions;
18
+ /**
19
+ * Eager-load every declared graph at boot instead of lazily on first request. `skein dev` sets
20
+ * this so (a) graph import errors surface at startup and (b) the graph source files enter the
21
+ * running process's module graph — which is what arms `tsx watch`'s hot reload (it only watches
22
+ * files that have actually been imported). Load failures are logged, not thrown, so one bad
23
+ * graph never takes the server down or breaks the watch loop.
24
+ */
25
+ warm?: boolean;
26
+ }
27
+ /** Either point at a `langgraph.json` (in-memory runtime) or inject a ready `ProtocolDeps`. */
28
+ type SkeinRouterOptions = SkeinRouterCommonOptions & ({
29
+ config: string;
30
+ /**
31
+ * How graph modules are imported for the in-memory runtime. Defaults to a native
32
+ * dynamic `import()`; `skein dev` injects a vite-backed importer for TypeScript graphs.
33
+ */
34
+ importModule?: ModuleImporter;
35
+ deps?: never;
36
+ } | {
37
+ deps: ProtocolDeps;
38
+ config?: never;
39
+ importModule?: never;
40
+ });
41
+ interface SkeinRouter {
42
+ /** Mount on an Express app: `app.use(router)`. */
43
+ router: Router;
44
+ /** The wired runtime — call `runtime.worker.stop()` on shutdown to drain background runs. */
45
+ runtime: ProtocolRuntime;
46
+ }
47
+ /**
48
+ * Wire a protocol runtime and return its mountable router. Seeds one assistant per declared graph
49
+ * and starts the background run worker before returning, so the router is ready to serve.
50
+ */
51
+ declare function skeinRouter(options: SkeinRouterOptions): Promise<SkeinRouter>;
52
+
53
+ interface SkeinExpressServer {
54
+ /** The Express app, protocol mounted at `/`. Mount extra middleware or routes before `listen`. */
55
+ app: Express;
56
+ /** The wired runtime (assistants, handlers, worker). */
57
+ runtime: ProtocolRuntime;
58
+ /** Start listening; resolves with the Node `Server` once bound. Defaults to port 2024. */
59
+ listen(port?: number, host?: string): Promise<Server>;
60
+ /** Stop the run worker and close the HTTP server (if listening). */
61
+ close(): Promise<void>;
62
+ }
63
+ /** Build an Express server hosting the Agent Protocol, ready to `listen`. */
64
+ declare function createExpressServer(options: SkeinRouterOptions): Promise<SkeinExpressServer>;
65
+
66
+ type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
67
+ interface RouteBinding {
68
+ method: HttpMethod;
69
+ path: string;
70
+ handler: keyof ProtocolHandlers;
71
+ /**
72
+ * Fold the path `thread_id` into the request body before dispatch. The SDK addresses a
73
+ * thread-scoped run by its path (`POST /threads/{id}/runs/stream`) while carrying only
74
+ * `assistant_id` in the body, but the stateless run handlers read `thread_id` from the body — so a
75
+ * thread-scoped mount must copy it across, or the run would target a stray new thread.
76
+ */
77
+ foldThreadIdIntoBody?: boolean;
78
+ }
79
+ /** The route table, ordered most-specific-first within each method so literals win over params. */
80
+ declare const skeinRoutes: readonly RouteBinding[];
81
+ interface HandlerRouterOptions {
82
+ /** Structured logger for unexpected (non-`SkeinHttpError`) faults. */
83
+ logger?: Logger;
84
+ /**
85
+ * Cross-origin access, needed by browser clients (Agent Chat UI, React `useStream`) that run on a
86
+ * different origin than the server. `true` reflects the request origin (permissive — good for
87
+ * `skein dev`); pass `CorsOptions` to restrict origins for `skein up`; omit/`false` to disable.
88
+ */
89
+ cors?: boolean | CorsOptions;
90
+ }
91
+ /**
92
+ * Build an Express `Router` that binds the route table to a handler table. This is the pure shim —
93
+ * it assembles no runtime and knows no storage driver, so callers can mount it over any
94
+ * `ProtocolHandlers` (in-memory for `skein dev`, Postgres + Redis for `skein up`).
95
+ */
96
+ declare function createHandlerRouter(handlers: ProtocolHandlers, options?: HandlerRouterOptions): Router;
97
+
98
+ /** Translate an Express `Request` into the normalized `ProtocolRequest` the handler table consumes. */
99
+ declare function toProtocolRequest(req: Request): ProtocolRequest;
100
+
101
+ /** Write a `ProtocolResponse` back onto the Express `res`, streaming when it is an SSE response. */
102
+ declare function sendProtocolResponse(response: ProtocolResponse, res: Response): Promise<void>;
103
+
104
+ /** Serialize a caught error onto `res`, using the protocol status when the error carries one. */
105
+ declare function sendErrorResponse(error: unknown, res: Response, logger?: Logger): void;
106
+
107
+ /** The checkpoint tuple `[checkpoint, metadata, parentId?]` with the blobs base64-encoded. */
108
+ type SerializedCheckpointTuple = [string, string, string | undefined];
109
+ /** `MemorySaver.storage` (thread → namespace → checkpointId → tuple) with blobs base64-encoded. */
110
+ type SerializedCheckpointStorage = Record<string, Record<string, Record<string, SerializedCheckpointTuple>>>;
111
+ /** `MemorySaver.writes` (key → taskId+idx → `[taskId, channel, blob]`) with the blob base64-encoded. */
112
+ type SerializedCheckpointWrites = Record<string, Record<string, [string, string, string]>>;
113
+ interface CheckpointerSnapshot {
114
+ storage: SerializedCheckpointStorage;
115
+ writes: SerializedCheckpointWrites;
116
+ }
117
+ /** A JSON-serializable snapshot of the whole in-memory dev runtime. */
118
+ interface DevStateSnapshot {
119
+ version: 1;
120
+ store: MemoryStoreSnapshot;
121
+ checkpoints: CheckpointerSnapshot;
122
+ }
123
+
124
+ interface InMemoryRuntimeConfig {
125
+ /** In-memory `ProtocolDeps` (store, queue, bus, checkpointer) around the config's graphs. */
126
+ deps: ProtocolDeps;
127
+ /** CORS mapped from the config's `http.cors`, or `undefined` when none is declared. */
128
+ cors?: CorsOptions;
129
+ }
130
+ /** Load `langgraph.json`, wiring fresh in-memory drivers and reading its `http.cors` for the adapter. */
131
+ declare function loadInMemoryRuntime(configPath: string, importModule?: ModuleImporter): Promise<InMemoryRuntimeConfig>;
132
+ interface ReloadableInMemoryRuntime extends InMemoryRuntimeConfig {
133
+ /**
134
+ * Re-read the config and swap in freshly imported graphs, keeping the same drivers. Because the
135
+ * run engine calls `graphs.load()` per run (it never caches the compiled graph itself), the next
136
+ * run picks up the new code while every thread, run, checkpoint, and store item survives. This is
137
+ * what lets `skein dev` hot-reload graph source without dropping in-memory state.
138
+ */
139
+ reloadGraphs(): Promise<void>;
140
+ /** A JSON-serializable snapshot of all dev state (protocol store + checkpoints). */
141
+ snapshotState(): DevStateSnapshot;
142
+ /** Restore dev state from a {@link snapshotState} — call before the server starts serving. */
143
+ hydrateState(snapshot: DevStateSnapshot): void;
144
+ }
145
+ /**
146
+ * Like {@link loadInMemoryRuntime}, but the returned `deps.graphs` delegates to a swappable config
147
+ * registry so graphs can be reloaded in place, and it can snapshot/restore its dev state. `skein
148
+ * dev` pairs this with vite's watcher (clear vite's cache, then `reloadGraphs()` — no server
149
+ * restart, no lost state) and with on-disk JSON persistence across restarts.
150
+ */
151
+ declare function loadReloadableInMemoryRuntime(configPath: string, importModule?: ModuleImporter): Promise<ReloadableInMemoryRuntime>;
152
+
153
+ /** The `http.cors` block of a langgraph.json — LangGraph's field names (snake_case). */
154
+ interface LanggraphCorsConfig {
155
+ allow_origins?: string[];
156
+ allow_origin_regex?: string;
157
+ allow_methods?: string[];
158
+ allow_headers?: string[];
159
+ allow_credentials?: boolean;
160
+ expose_headers?: string[];
161
+ max_age?: number;
162
+ }
163
+ /** Translate a LangGraph `http.cors` config into `cors` middleware options. */
164
+ declare function toCorsOptions(config: LanggraphCorsConfig): CorsOptions;
165
+ /** Read `http.cors` from a langgraph.json `http` block, mapped to `CorsOptions`, or `undefined`. */
166
+ declare function corsFromHttpConfig(http: unknown): CorsOptions | undefined;
167
+
168
+ export { type DevStateSnapshot, type HandlerRouterOptions, type InMemoryRuntimeConfig, type LanggraphCorsConfig, type ReloadableInMemoryRuntime, type SkeinExpressServer, type SkeinRouter, type SkeinRouterOptions, corsFromHttpConfig, createExpressServer, createHandlerRouter, loadInMemoryRuntime, loadReloadableInMemoryRuntime, sendErrorResponse, sendProtocolResponse, skeinRouter, skeinRoutes, toCorsOptions, toProtocolRequest };
package/dist/index.js ADDED
@@ -0,0 +1,404 @@
1
+ // src/skein-router.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 { loadAuthEngine, loadConfig } from "@skein-js/config";
9
+ import { MemoryRunEventBus, MemoryRunQueue, MemorySkeinStore } from "@skein-js/storage-memory";
10
+
11
+ // src/cors-config.ts
12
+ var ALWAYS_EXPOSED_HEADERS = ["content-location", "x-pagination-total"];
13
+ function toCorsOptions(config) {
14
+ const options = {};
15
+ const allowAll = config.allow_origins?.includes("*") ?? false;
16
+ if (config.allow_origin_regex !== void 0) {
17
+ const pattern = new RegExp(`^(?:${config.allow_origin_regex})$`);
18
+ const listed = allowAll ? void 0 : new Set(config.allow_origins);
19
+ options.origin = (origin, callback) => callback(
20
+ null,
21
+ origin !== void 0 && (allowAll || pattern.test(origin) || (listed?.has(origin) ?? false))
22
+ );
23
+ } else if (config.allow_origins !== void 0) {
24
+ options.origin = allowAll ? "*" : config.allow_origins;
25
+ }
26
+ if (config.allow_methods !== void 0) options.methods = config.allow_methods;
27
+ if (config.allow_headers !== void 0) options.allowedHeaders = config.allow_headers;
28
+ if (config.allow_credentials !== void 0) options.credentials = config.allow_credentials;
29
+ if (config.max_age !== void 0) options.maxAge = config.max_age;
30
+ const exposed = /* @__PURE__ */ new Set([...ALWAYS_EXPOSED_HEADERS, ...config.expose_headers ?? []]);
31
+ options.exposedHeaders = [...exposed];
32
+ return options;
33
+ }
34
+ function corsFromHttpConfig(http) {
35
+ if (typeof http !== "object" || http === null) return void 0;
36
+ const cors2 = http.cors;
37
+ if (typeof cors2 !== "object" || cors2 === null) return void 0;
38
+ return toCorsOptions(cors2);
39
+ }
40
+
41
+ // src/dev-persistence.ts
42
+ var toBase64 = (bytes) => Buffer.from(bytes).toString("base64");
43
+ var fromBase64 = (text) => new Uint8Array(Buffer.from(text, "base64"));
44
+ var mapValues = (record, fn) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, fn(value)]));
45
+ function snapshotCheckpointer(saver) {
46
+ return {
47
+ storage: mapValues(
48
+ saver.storage,
49
+ (namespaces) => mapValues(
50
+ namespaces,
51
+ (checkpoints) => mapValues(checkpoints, ([checkpoint, metadata, parentId]) => [
52
+ toBase64(checkpoint),
53
+ toBase64(metadata),
54
+ parentId
55
+ ])
56
+ )
57
+ ),
58
+ writes: mapValues(
59
+ saver.writes,
60
+ (taskWrites) => mapValues(taskWrites, ([taskId, channel, blob]) => [
61
+ taskId,
62
+ channel,
63
+ toBase64(blob)
64
+ ])
65
+ )
66
+ };
67
+ }
68
+ function hydrateCheckpointer(saver, snapshot) {
69
+ saver.storage = mapValues(
70
+ snapshot.storage,
71
+ (namespaces) => mapValues(
72
+ namespaces,
73
+ (checkpoints) => mapValues(
74
+ checkpoints,
75
+ ([checkpoint, metadata, parentId]) => [
76
+ fromBase64(checkpoint),
77
+ fromBase64(metadata),
78
+ parentId
79
+ ]
80
+ )
81
+ )
82
+ );
83
+ saver.writes = mapValues(
84
+ snapshot.writes,
85
+ (taskWrites) => mapValues(taskWrites, ([taskId, channel, blob]) => [
86
+ taskId,
87
+ channel,
88
+ fromBase64(blob)
89
+ ])
90
+ );
91
+ }
92
+
93
+ // src/in-memory-runtime.ts
94
+ function toGraphResolver(graphs) {
95
+ return {
96
+ ids: graphs.ids,
97
+ load: (graphId) => graphs.load(graphId),
98
+ schemas: async (graphId) => await graphs.schemas(graphId)
99
+ };
100
+ }
101
+ function buildInMemoryDeps(graphs) {
102
+ return {
103
+ store: new MemorySkeinStore(),
104
+ graphs,
105
+ queue: new MemoryRunQueue(),
106
+ bus: new MemoryRunEventBus(),
107
+ checkpointer: new MemorySaver()
108
+ };
109
+ }
110
+ async function loadInMemoryRuntime(configPath, importModule) {
111
+ const { graphs, config, configDir } = await loadConfig({ configPath, importModule });
112
+ const deps = buildInMemoryDeps(toGraphResolver(graphs));
113
+ deps.auth = await loadAuthEngine(config.auth, { configDir, importModule });
114
+ return {
115
+ deps,
116
+ cors: corsFromHttpConfig(config.http)
117
+ };
118
+ }
119
+ async function loadReloadableInMemoryRuntime(configPath, importModule) {
120
+ const first = await loadConfig({ configPath, importModule });
121
+ let current = first.graphs;
122
+ const graphs = {
123
+ ids: first.graphs.ids,
124
+ load: (graphId) => current.load(graphId),
125
+ schemas: async (graphId) => await current.schemas(graphId)
126
+ };
127
+ const store = new MemorySkeinStore();
128
+ const checkpointer = new MemorySaver();
129
+ const deps = {
130
+ store,
131
+ graphs,
132
+ queue: new MemoryRunQueue(),
133
+ bus: new MemoryRunEventBus(),
134
+ checkpointer,
135
+ auth: await loadAuthEngine(first.config.auth, { configDir: first.configDir, importModule })
136
+ };
137
+ return {
138
+ deps,
139
+ cors: corsFromHttpConfig(first.config.http),
140
+ reloadGraphs: async () => {
141
+ current = (await loadConfig({ configPath, importModule })).graphs;
142
+ },
143
+ snapshotState: () => ({
144
+ version: 1,
145
+ store: store.snapshot(),
146
+ checkpoints: snapshotCheckpointer(checkpointer)
147
+ }),
148
+ hydrateState: (snapshot) => {
149
+ store.hydrate(snapshot.store);
150
+ hydrateCheckpointer(checkpointer, snapshot.checkpoints);
151
+ }
152
+ };
153
+ }
154
+
155
+ // src/routes.ts
156
+ import cors from "cors";
157
+ import express from "express";
158
+
159
+ // src/error-response.ts
160
+ import { isSkeinHttpError } from "@skein-js/core";
161
+ function sendErrorResponse(error, res, logger) {
162
+ if (res.headersSent) {
163
+ if (!isSkeinHttpError(error)) logger?.error("Unhandled error after headers were sent.", error);
164
+ if (!res.writableEnded) res.end();
165
+ return;
166
+ }
167
+ if (isSkeinHttpError(error)) {
168
+ res.status(error.status).json({
169
+ status: error.status,
170
+ message: error.message,
171
+ ...error.code !== void 0 ? { code: error.code } : {},
172
+ ...error.details !== void 0 ? { details: error.details } : {}
173
+ });
174
+ return;
175
+ }
176
+ logger?.error("Unhandled error in the skein Express adapter.", error);
177
+ res.status(500).json({ status: 500, message: "Internal Server Error" });
178
+ }
179
+
180
+ // src/send-protocol-response.ts
181
+ import { SSE_HEADERS } from "@skein-js/agent-protocol";
182
+ import { serializeWireJson } from "@skein-js/core";
183
+ var ignoreStreamError = () => {
184
+ };
185
+ async function pipeServerSentEvents(status, events, res) {
186
+ res.status(status);
187
+ for (const [name, value] of Object.entries(SSE_HEADERS)) res.setHeader(name, value);
188
+ res.flushHeaders();
189
+ const iterator = events[Symbol.asyncIterator]();
190
+ let clientDisconnected = false;
191
+ const releaseOnClientClose = () => {
192
+ clientDisconnected = true;
193
+ void Promise.resolve(iterator.return?.(void 0)).catch(ignoreStreamError);
194
+ };
195
+ res.once("close", releaseOnClientClose);
196
+ res.on("error", ignoreStreamError);
197
+ try {
198
+ for (; ; ) {
199
+ const next = await iterator.next();
200
+ if (next.done || clientDisconnected) break;
201
+ res.write(next.value);
202
+ }
203
+ } finally {
204
+ res.removeListener("close", releaseOnClientClose);
205
+ if (!res.writableEnded) res.end();
206
+ }
207
+ }
208
+ async function sendProtocolResponse(response, res) {
209
+ switch (response.kind) {
210
+ case "json":
211
+ res.status(response.status).type("application/json").send(serializeWireJson(response.body));
212
+ return;
213
+ case "empty":
214
+ res.status(response.status).end();
215
+ return;
216
+ case "sse":
217
+ await pipeServerSentEvents(response.status, response.events, res);
218
+ return;
219
+ }
220
+ }
221
+
222
+ // src/to-protocol-request.ts
223
+ function toSingleValueHeaders(headers) {
224
+ const flattened = {};
225
+ for (const [name, value] of Object.entries(headers)) {
226
+ flattened[name] = Array.isArray(value) ? value[0] : value;
227
+ }
228
+ return flattened;
229
+ }
230
+ function toProtocolRequest(req) {
231
+ return {
232
+ method: req.method,
233
+ // Absolute URL so a synthesized WHATWG `Request` carries the path + query string; an auth
234
+ // handler may read either. `req.originalUrl` includes the query, unlike `req.path`.
235
+ url: `${req.protocol}://${req.get("host") ?? "localhost"}${req.originalUrl}`,
236
+ // Express 5 types params as `string | string[]`, but the protocol's routes use single named
237
+ // params only, so the narrower `Record<string, string>` holds.
238
+ params: req.params,
239
+ // Express parses the query string with `qs`; the handlers only read flat string / string[]
240
+ // values, so the parsed shape is compatible.
241
+ query: req.query,
242
+ body: req.body,
243
+ headers: toSingleValueHeaders(req.headers)
244
+ };
245
+ }
246
+
247
+ // src/routes.ts
248
+ var skeinRoutes = [
249
+ // assistants
250
+ { method: "get", path: "/assistants/:assistant_id/schemas", handler: "getAssistantSchemas" },
251
+ { method: "get", path: "/assistants/:assistant_id", handler: "getAssistant" },
252
+ { method: "post", path: "/assistants/search", handler: "searchAssistants" },
253
+ // threads
254
+ { method: "post", path: "/threads/search", handler: "listThreads" },
255
+ { method: "post", path: "/threads", handler: "createThread" },
256
+ { method: "get", path: "/threads/:thread_id", handler: "getThread" },
257
+ { method: "patch", path: "/threads/:thread_id", handler: "patchThread" },
258
+ { method: "delete", path: "/threads/:thread_id", handler: "deleteThread" },
259
+ { method: "get", path: "/threads/:thread_id/state", handler: "getThreadState" },
260
+ { method: "post", path: "/threads/:thread_id/history", handler: "getThreadHistory" },
261
+ // runs — the stateless handlers are reused on the thread-scoped path with the id folded in
262
+ { method: "post", path: "/runs/wait", handler: "createWaitRun" },
263
+ { method: "post", path: "/runs/stream", handler: "createStreamRun" },
264
+ {
265
+ method: "post",
266
+ path: "/threads/:thread_id/runs/wait",
267
+ handler: "createWaitRun",
268
+ foldThreadIdIntoBody: true
269
+ },
270
+ {
271
+ method: "post",
272
+ path: "/threads/:thread_id/runs/stream",
273
+ handler: "createStreamRun",
274
+ foldThreadIdIntoBody: true
275
+ },
276
+ { method: "post", path: "/threads/:thread_id/runs", handler: "createBackgroundRun" },
277
+ { method: "get", path: "/threads/:thread_id/runs", handler: "listThreadRuns" },
278
+ { method: "post", path: "/threads/:thread_id/runs/:run_id/cancel", handler: "cancelRun" },
279
+ { method: "get", path: "/threads/:thread_id/runs/:run_id/stream", handler: "joinRunStream" },
280
+ { method: "get", path: "/threads/:thread_id/runs/:run_id", handler: "getRun" },
281
+ { method: "delete", path: "/threads/:thread_id/runs/:run_id", handler: "deleteRun" },
282
+ { method: "get", path: "/runs/:run_id/stream", handler: "joinRunStream" },
283
+ // thread streaming / commands
284
+ { method: "post", path: "/threads/:thread_id/stream", handler: "postThreadStream" },
285
+ { method: "get", path: "/threads/:thread_id/stream", handler: "getThreadStream" },
286
+ { method: "post", path: "/threads/:thread_id/commands", handler: "postThreadCommands" },
287
+ // store
288
+ { method: "put", path: "/store/items", handler: "putStoreItem" },
289
+ { method: "get", path: "/store/items", handler: "getStoreItem" },
290
+ { method: "delete", path: "/store/items", handler: "deleteStoreItem" },
291
+ { method: "post", path: "/store/items/search", handler: "searchStoreItems" },
292
+ { method: "post", path: "/store/namespaces", handler: "listStoreNamespaces" }
293
+ ];
294
+ function foldThreadId(request) {
295
+ const threadId = request.params["thread_id"];
296
+ if (threadId === void 0) return request;
297
+ const base = typeof request.body === "object" && request.body !== null && !Array.isArray(request.body) ? request.body : {};
298
+ return { ...request, body: { ...base, thread_id: threadId } };
299
+ }
300
+ function createHandlerRouter(handlers, options = {}) {
301
+ const router = express.Router();
302
+ if (options.cors) router.use(cors(options.cors === true ? { origin: true } : options.cors));
303
+ router.use(express.json());
304
+ for (const binding of skeinRoutes) {
305
+ const invoke = handlers[binding.handler];
306
+ router[binding.method](binding.path, async (req, res) => {
307
+ try {
308
+ const request = toProtocolRequest(req);
309
+ const response = await invoke(binding.foldThreadIdIntoBody ? foldThreadId(request) : request);
310
+ await sendProtocolResponse(response, res);
311
+ } catch (error) {
312
+ sendErrorResponse(error, res, options.logger);
313
+ }
314
+ });
315
+ }
316
+ return router;
317
+ }
318
+
319
+ // src/skein-router.ts
320
+ async function skeinRouter(options) {
321
+ let deps;
322
+ let corsFromConfig;
323
+ if (options.deps) {
324
+ deps = options.deps;
325
+ } else {
326
+ const loaded = await loadInMemoryRuntime(options.config, options.importModule);
327
+ deps = loaded.deps;
328
+ corsFromConfig = loaded.cors;
329
+ }
330
+ const runtime = createProtocolRuntime(deps);
331
+ await runtime.service.assistants.registerGraphAssistants();
332
+ if (options.warm) {
333
+ await Promise.all(
334
+ deps.graphs.ids.map(
335
+ (graphId) => deps.graphs.load(graphId).catch((error) => {
336
+ options.logger?.warn(`Failed to warm graph "${graphId}".`, error);
337
+ })
338
+ )
339
+ );
340
+ }
341
+ runtime.worker.start();
342
+ const router = createHandlerRouter(runtime.handlers, {
343
+ logger: options.logger,
344
+ // Explicit option wins; otherwise fall back to the config's `http.cors`, else off.
345
+ cors: options.cors ?? corsFromConfig ?? false
346
+ });
347
+ return { router, runtime };
348
+ }
349
+
350
+ // src/create-express-server.ts
351
+ import express2 from "express";
352
+ function requestLogger(logger) {
353
+ return (req, res, next) => {
354
+ const startedAt = Date.now();
355
+ let logged = false;
356
+ const log = () => {
357
+ if (logged) return;
358
+ logged = true;
359
+ logger.info(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - startedAt}ms`);
360
+ };
361
+ res.once("finish", log);
362
+ res.once("close", log);
363
+ next();
364
+ };
365
+ }
366
+ async function createExpressServer(options) {
367
+ const { router, runtime } = await skeinRouter(options);
368
+ const app = express2();
369
+ if (options.logger) app.use(requestLogger(options.logger));
370
+ app.use(router);
371
+ let server;
372
+ return {
373
+ app,
374
+ runtime,
375
+ listen: (port = 2024, host = "localhost") => new Promise((resolve, reject) => {
376
+ const bound = app.listen(port, host, () => resolve(bound));
377
+ bound.once("error", reject);
378
+ server = bound;
379
+ }),
380
+ close: async () => {
381
+ await runtime.worker.stop();
382
+ const bound = server;
383
+ server = void 0;
384
+ if (bound) {
385
+ await new Promise((resolve, reject) => {
386
+ bound.close((error) => error ? reject(error) : resolve());
387
+ });
388
+ }
389
+ }
390
+ };
391
+ }
392
+ export {
393
+ corsFromHttpConfig,
394
+ createExpressServer,
395
+ createHandlerRouter,
396
+ loadInMemoryRuntime,
397
+ loadReloadableInMemoryRuntime,
398
+ sendErrorResponse,
399
+ sendProtocolResponse,
400
+ skeinRouter,
401
+ skeinRoutes,
402
+ toCorsOptions,
403
+ toProtocolRequest
404
+ };
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@skein-js/express",
3
+ "version": "0.1.0",
4
+ "description": "Express adapter for skein-js — mount the Agent Protocol on an Express Router.",
5
+ "license": "Apache-2.0",
6
+ "author": "Maina Wycliffe <wmmaina7@gmail.com>",
7
+ "homepage": "https://github.com/mainawycliffe/skein/tree/main/packages/server-express#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/mainawycliffe/skein.git",
11
+ "directory": "packages/server-express"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/mainawycliffe/skein/issues"
15
+ },
16
+ "keywords": [
17
+ "express",
18
+ "langgraph",
19
+ "agent-protocol",
20
+ "sse"
21
+ ],
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "module": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "LICENSE",
35
+ "README.md"
36
+ ],
37
+ "sideEffects": false,
38
+ "engines": {
39
+ "node": ">=20"
40
+ },
41
+ "dependencies": {
42
+ "cors": "^2.8.5",
43
+ "@skein-js/agent-protocol": "0.1.0",
44
+ "@skein-js/config": "0.1.0",
45
+ "@skein-js/core": "0.1.0",
46
+ "@skein-js/storage-memory": "0.1.0"
47
+ },
48
+ "peerDependencies": {
49
+ "@langchain/langgraph": "^1.4.0",
50
+ "express": ">=4.18.0"
51
+ },
52
+ "devDependencies": {
53
+ "@langchain/core": "^1.2.0",
54
+ "@langchain/langgraph": "^1.4.0",
55
+ "@types/cors": "^2.8.17",
56
+ "@types/express": "^5.0.0",
57
+ "express": "^5.2.1"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }