@skein-js/core 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,45 @@
1
+ # @skein-js/core
2
+
3
+ > Framework-agnostic Agent Protocol engine for LangGraph.js — the heart of skein-js.
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 run engine, handler table, and SSE mapping that build on this contract live in [`@skein-js/agent-protocol`](../agent-protocol).
8
+
9
+ ## What it does
10
+
11
+ Holds the Agent Protocol _contract_ once, against _normalized_ types, so behavior is identical across every framework adapter and storage driver. Everything downstream imports it:
12
+
13
+ - **Wire types** re-exported from `@langchain/langgraph-sdk` (`Assistant`, `Thread`, `Run`, `RunStatus`, `Config`, `Metadata`, `Item`, `StreamMode`, …) — the single seam that pins the protocol version.
14
+ - **`SkeinStore`** — the persistence interface for protocol resources (`assistants` / `threads` / `runs` / `store`), including the `hasActiveRun` concurrency guard and `isTerminalRunStatus`.
15
+ - **`RunQueue` / `RunEventBus`** — the run queue + streaming pub/sub seams.
16
+ - **`SkeinHttpError`** — the typed edge error carrying an HTTP status.
17
+
18
+ ## Usage
19
+
20
+ ```ts
21
+ import { type SkeinStore, SkeinHttpError, isTerminalRunStatus } from "@skein-js/core";
22
+
23
+ // Storage drivers implement SkeinStore; adapters catch SkeinHttpError at the HTTP edge.
24
+ throw SkeinHttpError.notFound(`Thread "${id}" not found.`);
25
+ ```
26
+
27
+ ## Reuse
28
+
29
+ Reuses `@langchain/langgraph-sdk` TypeScript types as the wire contract rather than redefining them. Graphs run through `@langchain/langgraph` (`CompiledStateGraph.invoke`/`.stream`, interrupts/resume) in [`@skein-js/agent-protocol`](../agent-protocol) — never a reimplemented runtime.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pnpm add @skein-js/core
35
+ ```
36
+
37
+ ## Learn more
38
+
39
+ - [skein-js overview](../../docs/index.md)
40
+ - [Reuse-first architecture](../../docs/reuse.md)
41
+ - [Roadmap](../../docs/roadmap.md)
42
+
43
+ ## License
44
+
45
+ [Apache-2.0](../../LICENSE)
@@ -0,0 +1,284 @@
1
+ import { Run, Config, Metadata, Assistant, StreamMode, Thread, ThreadStatus, DefaultValues, Interrupt, Item, SearchItem } from '@langchain/langgraph-sdk';
2
+ export { Assistant, AssistantBase, AssistantGraph, Checkpoint, Config, DefaultValues, GraphSchema, Interrupt, Item, Metadata, Run, SearchItem, StreamMode, Thread, ThreadState, ThreadStatus, ThreadTask } from '@langchain/langgraph-sdk';
3
+
4
+ type RunStatus = Run["status"];
5
+ type MultitaskStrategy = NonNullable<Run["multitask_strategy"]>;
6
+
7
+ /** Fields accepted when registering an assistant (from a langgraph.json graph or the API). */
8
+ interface AssistantCreate {
9
+ graph_id: string;
10
+ /** Server-assigned when omitted. */
11
+ assistant_id?: string;
12
+ name?: string;
13
+ description?: string;
14
+ config?: Config;
15
+ context?: unknown;
16
+ metadata?: Metadata;
17
+ }
18
+ interface AssistantRepo {
19
+ list(): Promise<Assistant[]>;
20
+ get(assistantId: string): Promise<Assistant | null>;
21
+ /** Create (or, for a graph-derived assistant, register) an assistant. */
22
+ create(input: AssistantCreate): Promise<Assistant>;
23
+ delete(assistantId: string): Promise<void>;
24
+ }
25
+ interface ThreadCreate {
26
+ /** Server-assigned when omitted. */
27
+ thread_id?: string;
28
+ metadata?: Metadata;
29
+ status?: ThreadStatus;
30
+ }
31
+ /** Partial update; omitted fields are left unchanged. */
32
+ interface ThreadUpdate {
33
+ metadata?: Metadata;
34
+ status?: ThreadStatus;
35
+ /** Latest graph state values mirrored onto the thread row. */
36
+ values?: DefaultValues;
37
+ /** Pending human-in-the-loop interrupts, mirrored from the graph state onto the thread row. */
38
+ interrupts?: Record<string, Interrupt[]>;
39
+ }
40
+ interface ThreadRepo {
41
+ list(): Promise<Thread[]>;
42
+ get(threadId: string): Promise<Thread | null>;
43
+ create(input?: ThreadCreate): Promise<Thread>;
44
+ update(threadId: string, patch: ThreadUpdate): Promise<Thread>;
45
+ delete(threadId: string): Promise<void>;
46
+ }
47
+ /**
48
+ * The execution payload of a run — everything the run engine needs to (re)start a graph. Stored
49
+ * *opaquely* alongside the run (it is NOT part of the wire {@link Run}), so a background run picked
50
+ * up later, or a run reclaimed after a crash, can be reconstructed from just its `run_id`.
51
+ */
52
+ interface RunKwargs {
53
+ /** Graph input for a fresh turn. Absent when the run is a resume (see {@link command}). */
54
+ input?: unknown;
55
+ /** A LangGraph command (e.g. `{ resume }`) — present when resuming an interrupted thread. */
56
+ command?: {
57
+ resume?: unknown;
58
+ update?: unknown;
59
+ goto?: unknown;
60
+ };
61
+ config?: Config;
62
+ context?: unknown;
63
+ /** Requested stream modes; the engine normalizes these to graph modes. */
64
+ stream_mode?: StreamMode | StreamMode[];
65
+ interrupt_before?: string[] | "*";
66
+ interrupt_after?: string[] | "*";
67
+ }
68
+ interface RunCreate {
69
+ thread_id: string;
70
+ assistant_id: string;
71
+ /** Server-assigned when omitted. */
72
+ run_id?: string;
73
+ /** Defaults to `"pending"`. */
74
+ status?: RunStatus;
75
+ metadata?: Metadata;
76
+ multitask_strategy?: MultitaskStrategy | null;
77
+ /** Execution payload, stored opaquely for the run engine (see {@link RunKwargs}). */
78
+ kwargs?: RunKwargs;
79
+ }
80
+ interface RunRepo {
81
+ get(runId: string): Promise<Run | null>;
82
+ listByThread(threadId: string): Promise<Run[]>;
83
+ create(input: RunCreate): Promise<Run>;
84
+ setStatus(runId: string, status: RunStatus): Promise<Run>;
85
+ delete(runId: string): Promise<void>;
86
+ /** The opaque execution payload stored with a run, or null if the run is unknown. */
87
+ getKwargs(runId: string): Promise<RunKwargs | null>;
88
+ /**
89
+ * The protocol concurrency guard: true while the thread has an *inflight* run — one still
90
+ * `pending` or `running` (i.e. non-terminal per {@link isTerminalRunStatus}). An `interrupted`
91
+ * run is terminal and does NOT count: it has yielded the thread to a human, and a resume arrives
92
+ * as a fresh run. The run engine uses this to reject/queue concurrent runs.
93
+ */
94
+ hasActiveRun(threadId: string): Promise<boolean>;
95
+ }
96
+ /**
97
+ * Run statuses from which a run never transitions again. `"interrupted"` is terminal: resuming an
98
+ * interrupt starts a *new* run on the same thread (this matches `@langchain/langgraph-api`, whose
99
+ * inflight check is `pending | running` only — so an interrupted run never blocks the resume).
100
+ */
101
+ declare const TERMINAL_RUN_STATUSES: readonly RunStatus[];
102
+ /** True if `status` is terminal (the run is finished and no longer holds its thread). */
103
+ declare function isTerminalRunStatus(status: RunStatus): boolean;
104
+ interface StoreSearchQuery {
105
+ /** Restrict to items under this namespace prefix. */
106
+ prefix?: string[];
107
+ /** Natural-language query for semantic search (naive scan in the memory driver). */
108
+ query?: string;
109
+ limit?: number;
110
+ offset?: number;
111
+ }
112
+ interface StoreRepo {
113
+ get(namespace: string[], key: string): Promise<Item | null>;
114
+ put(namespace: string[], key: string, value: Record<string, unknown>): Promise<Item>;
115
+ delete(namespace: string[], key: string): Promise<void>;
116
+ search(query: StoreSearchQuery): Promise<SearchItem[]>;
117
+ listNamespaces(prefix?: string[]): Promise<string[][]>;
118
+ }
119
+ /** The single persistence seam for Agent Protocol resources. One implementation per driver. */
120
+ interface SkeinStore {
121
+ assistants: AssistantRepo;
122
+ threads: ThreadRepo;
123
+ runs: RunRepo;
124
+ store: StoreRepo;
125
+ }
126
+
127
+ /**
128
+ * A normalized stream frame produced during a run. Adapters map these onto SSE
129
+ * (`id:`/`event:`/`data:`); `seq` is monotonic per run so a reconnecting client can replay
130
+ * from a `Last-Event-ID` (see docs/streaming.md).
131
+ */
132
+ interface RunFrame {
133
+ /** Monotonic sequence within the run, starting at 1. */
134
+ seq: number;
135
+ /** Frame kind: a LangGraph stream mode, or `"error"` for a failed run. */
136
+ event: StreamMode | "error";
137
+ /** Serializable payload for this frame. */
138
+ data: unknown;
139
+ }
140
+ /** Identifies a run to execute; the processor resolves the rest through the {@link SkeinStore}. */
141
+ interface QueuedRun {
142
+ run_id: string;
143
+ thread_id: string;
144
+ }
145
+ /**
146
+ * Executes one queued run. Resolving marks the job done; throwing leaves it for the queue to retry
147
+ * or recover (a crashed processor's job is redelivered). The processor loads the run from the
148
+ * {@link SkeinStore} by id and drives it to a terminal status.
149
+ */
150
+ type RunProcessor = (run: QueuedRun) => Promise<void>;
151
+ interface RunConsumerOptions {
152
+ /** Max runs a single consumer executes at once. Default 1 (per-thread serialization). */
153
+ concurrency?: number;
154
+ }
155
+ /** A live consumer draining the queue; close it to stop pulling. */
156
+ interface RunConsumer {
157
+ /**
158
+ * Stop consuming. Without `force`, waits for in-flight runs to finish; with `force`, returns
159
+ * without waiting (the caller has already aborted them).
160
+ */
161
+ close(force?: boolean): Promise<void>;
162
+ }
163
+ /**
164
+ * A durable queue of background runs. One producer enqueues; a consumer's processor drains it.
165
+ * The in-memory driver implements this for `skein dev`; `@skein-js/redis` backs it with BullMQ
166
+ * (retries, backoff, stalled-job crash recovery, cross-instance workers).
167
+ */
168
+ interface RunQueue {
169
+ enqueue(run: QueuedRun): Promise<void>;
170
+ /** Start draining the queue, running each job through `process`. Returns a handle to stop. */
171
+ consume(process: RunProcessor, options?: RunConsumerOptions): RunConsumer;
172
+ }
173
+ /** Fan-out of {@link RunFrame}s from the executing worker to subscribed clients. */
174
+ interface RunEventBus {
175
+ /** Publish the next frame for a run. */
176
+ publish(runId: string, frame: RunFrame): Promise<void>;
177
+ /** Signal that a run produced its last frame; subscribers' iterators complete. */
178
+ close(runId: string): Promise<void>;
179
+ /**
180
+ * Subscribe to a run's frames. Frames with `seq > afterSeq` are delivered (past ones
181
+ * replayed, future ones live-tailed); the iterator completes once the run is closed.
182
+ */
183
+ subscribe(runId: string, afterSeq?: number): AsyncIterable<RunFrame>;
184
+ }
185
+
186
+ /**
187
+ * `JSON.stringify` for outbound protocol payloads. Any value exposing `toDict()` (i.e. a LangChain
188
+ * message) is flattened to `{ ...data, type }` — the shape LangGraph clients expect.
189
+ *
190
+ * The replacer reads `this[key]` rather than its `value` argument on purpose: `JSON.stringify`
191
+ * applies an object's own `toJSON()` *before* calling the replacer, and `BaseMessage.toJSON()`
192
+ * already produces the unwanted constructor form. `this[key]` is the original message, so we can
193
+ * intercept it and call `toDict()` instead.
194
+ */
195
+ declare function serializeWireJson(value: unknown): string;
196
+
197
+ /** Options for a {@link SkeinHttpError}. */
198
+ interface SkeinHttpErrorOptions {
199
+ /** Stable machine-readable code (e.g. `"thread_not_found"`), distinct from the message. */
200
+ code?: string;
201
+ /** Structured detail carried to the client (validation issues, conflicting ids, …). */
202
+ details?: unknown;
203
+ /** Underlying error, preserved for logs. */
204
+ cause?: unknown;
205
+ }
206
+ /** An error carrying the HTTP status the Agent Protocol response should use. */
207
+ declare class SkeinHttpError extends Error {
208
+ readonly status: number;
209
+ readonly code?: string;
210
+ readonly details?: unknown;
211
+ constructor(status: number, message: string, options?: SkeinHttpErrorOptions);
212
+ /** 400 — the request was malformed (failed boundary validation). */
213
+ static badRequest(message: string, options?: SkeinHttpErrorOptions): SkeinHttpError;
214
+ /** 401 — the caller is not authenticated (no/invalid credentials for the configured auth). */
215
+ static unauthorized(message: string, options?: SkeinHttpErrorOptions): SkeinHttpError;
216
+ /** 403 — the caller is authenticated but not permitted to perform this action. */
217
+ static forbidden(message: string, options?: SkeinHttpErrorOptions): SkeinHttpError;
218
+ /** 404 — the addressed resource does not exist. */
219
+ static notFound(message: string, options?: SkeinHttpErrorOptions): SkeinHttpError;
220
+ /** 409 — the request conflicts with current state (e.g. a thread already has an active run). */
221
+ static conflict(message: string, options?: SkeinHttpErrorOptions): SkeinHttpError;
222
+ }
223
+ /** Narrow an unknown thrown value to a {@link SkeinHttpError}. */
224
+ declare function isSkeinHttpError(value: unknown): value is SkeinHttpError;
225
+
226
+ /**
227
+ * The authenticated caller, normalized to the shape LangGraph produces: a required `identity`,
228
+ * `permissions` scopes, and open extra keys a handler may attach (e.g. `email`, `org_id`).
229
+ */
230
+ interface AuthUser {
231
+ identity: string;
232
+ display_name: string;
233
+ is_authenticated: boolean;
234
+ permissions: string[];
235
+ [key: string]: unknown;
236
+ }
237
+ /** The result of authenticating a request: the caller plus their permission scopes. */
238
+ interface AuthContext {
239
+ user: AuthUser;
240
+ scopes: string[];
241
+ }
242
+ /** A protocol resource an `@auth.on.*` handler can guard. Runs authorize through their thread. */
243
+ type AuthResource = "threads" | "assistants" | "store";
244
+ /** An action on a resource, mirroring LangGraph's `resource:action` event names. */
245
+ type AuthAction = "create" | "read" | "update" | "delete" | "search" | "create_run" | "put" | "get" | "list_namespaces";
246
+ /** A single metadata filter clause — an exact value or an `$eq`/`$contains` operator object. */
247
+ type AuthFilterValue = string | {
248
+ $eq?: string;
249
+ $contains?: string | string[];
250
+ };
251
+ /**
252
+ * Ownership filters returned by an `@auth.on.*` handler. Keys are metadata fields; a returned filter
253
+ * both scopes reads (a resource is visible only if its metadata satisfies every clause) and stamps
254
+ * writes (the clause values are merged into new resources' metadata). Shape-compatible with
255
+ * `@langchain/langgraph-api`'s `isAuthMatching`.
256
+ */
257
+ type AuthFilters = Record<string, AuthFilterValue>;
258
+ /**
259
+ * The injectable auth engine — one per runtime, no module-global state (unlike langgraph-api's
260
+ * `registerAuth`). Absent from `ProtocolDeps` means no auth is configured and every request is
261
+ * allowed (the default, so `skein dev` stays frictionless).
262
+ */
263
+ interface AuthEngine {
264
+ /** True when a `langgraph.json` `auth.path` was loaded; false disables the whole gate. */
265
+ readonly enabled: boolean;
266
+ /** When true, studio traffic must present real credentials like any other client. */
267
+ readonly studioAuthDisabled: boolean;
268
+ /** Run the user's authenticate handler over a request; throws 401 on rejection/missing identity. */
269
+ authenticate(request: Request): Promise<AuthContext | undefined>;
270
+ /** Consult the `@auth.on.*` handlers for a resource+action; throws 403 on deny, else returns filters. */
271
+ authorize(input: {
272
+ resource: AuthResource;
273
+ action: AuthAction;
274
+ value: unknown;
275
+ context: AuthContext | undefined;
276
+ }): Promise<{
277
+ filters?: AuthFilters;
278
+ value: unknown;
279
+ }>;
280
+ /** Whether a resource's metadata satisfies the ownership filters (`$eq`/`$contains` semantics). */
281
+ matchesFilters(metadata: Record<string, unknown> | undefined, filters?: AuthFilters): boolean;
282
+ }
283
+
284
+ export { type AssistantCreate, type AssistantRepo, type AuthAction, type AuthContext, type AuthEngine, type AuthFilterValue, type AuthFilters, type AuthResource, type AuthUser, type MultitaskStrategy, type QueuedRun, type RunConsumer, type RunConsumerOptions, type RunCreate, type RunEventBus, type RunFrame, type RunKwargs, type RunProcessor, type RunQueue, type RunRepo, type RunStatus, SkeinHttpError, type SkeinHttpErrorOptions, type SkeinStore, type StoreRepo, type StoreSearchQuery, TERMINAL_RUN_STATUSES, type ThreadCreate, type ThreadRepo, type ThreadUpdate, isSkeinHttpError, isTerminalRunStatus, serializeWireJson };
package/dist/index.js ADDED
@@ -0,0 +1,72 @@
1
+ // src/store/skein-store.ts
2
+ var TERMINAL_RUN_STATUSES = [
3
+ "success",
4
+ "error",
5
+ "timeout",
6
+ "interrupted"
7
+ ];
8
+ function isTerminalRunStatus(status) {
9
+ return TERMINAL_RUN_STATUSES.includes(status);
10
+ }
11
+
12
+ // src/wire/serialize-wire-json.ts
13
+ function isWireDictConvertible(value) {
14
+ return value != null && typeof value === "object" && "toDict" in value && typeof value.toDict === "function";
15
+ }
16
+ function serializeWireJson(value) {
17
+ return JSON.stringify(
18
+ value,
19
+ function(key, serialized) {
20
+ const raw = this[key];
21
+ if (isWireDictConvertible(raw)) {
22
+ const { type, data } = raw.toDict();
23
+ return { ...data, type };
24
+ }
25
+ return serialized;
26
+ }
27
+ );
28
+ }
29
+
30
+ // src/errors/skein-http-error.ts
31
+ var SkeinHttpError = class _SkeinHttpError extends Error {
32
+ status;
33
+ code;
34
+ details;
35
+ constructor(status, message, options = {}) {
36
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
37
+ this.name = "SkeinHttpError";
38
+ this.status = status;
39
+ this.code = options.code;
40
+ this.details = options.details;
41
+ }
42
+ /** 400 — the request was malformed (failed boundary validation). */
43
+ static badRequest(message, options) {
44
+ return new _SkeinHttpError(400, message, options);
45
+ }
46
+ /** 401 — the caller is not authenticated (no/invalid credentials for the configured auth). */
47
+ static unauthorized(message, options) {
48
+ return new _SkeinHttpError(401, message, options);
49
+ }
50
+ /** 403 — the caller is authenticated but not permitted to perform this action. */
51
+ static forbidden(message, options) {
52
+ return new _SkeinHttpError(403, message, options);
53
+ }
54
+ /** 404 — the addressed resource does not exist. */
55
+ static notFound(message, options) {
56
+ return new _SkeinHttpError(404, message, options);
57
+ }
58
+ /** 409 — the request conflicts with current state (e.g. a thread already has an active run). */
59
+ static conflict(message, options) {
60
+ return new _SkeinHttpError(409, message, options);
61
+ }
62
+ };
63
+ function isSkeinHttpError(value) {
64
+ return value instanceof SkeinHttpError;
65
+ }
66
+ export {
67
+ SkeinHttpError,
68
+ TERMINAL_RUN_STATUSES,
69
+ isSkeinHttpError,
70
+ isTerminalRunStatus,
71
+ serializeWireJson
72
+ };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@skein-js/core",
3
+ "version": "0.1.0",
4
+ "description": "Framework-agnostic Agent Protocol engine for LangGraph.js — the heart of skein-js.",
5
+ "license": "Apache-2.0",
6
+ "author": "Maina Wycliffe <wmmaina7@gmail.com>",
7
+ "homepage": "https://github.com/mainawycliffe/skein/tree/main/packages/core#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/mainawycliffe/skein.git",
11
+ "directory": "packages/core"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/mainawycliffe/skein/issues"
15
+ },
16
+ "keywords": [
17
+ "langgraph",
18
+ "agent-protocol",
19
+ "agents",
20
+ "llm",
21
+ "ai",
22
+ "sse"
23
+ ],
24
+ "type": "module",
25
+ "main": "./dist/index.js",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "LICENSE",
37
+ "README.md"
38
+ ],
39
+ "sideEffects": false,
40
+ "engines": {
41
+ "node": ">=20"
42
+ },
43
+ "peerDependencies": {
44
+ "@langchain/langgraph": "^1.4.0",
45
+ "@langchain/langgraph-sdk": "^1.9.0"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ }
50
+ }