@skein-js/server-kit 0.15.0 → 0.16.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.
@@ -0,0 +1,137 @@
1
+ // src/channels-runtime.ts
2
+ import {
3
+ createAuthScopedStore,
4
+ createContext,
5
+ createProtocolServiceFromContext
6
+ } from "@skein-js/agent-protocol";
7
+ import { SkeinConfigError } from "@skein-js/config";
8
+ import { SkeinHttpError } from "@skein-js/core";
9
+ async function resolveChannels(input) {
10
+ const names = Object.keys(input.channels);
11
+ if (names.length === 0) return void 0;
12
+ const channels = await importChannelsPackage(names);
13
+ const registry = channels.buildChannelRegistry({
14
+ channels: Object.fromEntries(
15
+ Object.entries(input.channels).map(([name, loaded]) => [
16
+ name,
17
+ {
18
+ module: loaded.module,
19
+ config: {
20
+ assistant: loaded.assistant,
21
+ ...loaded.allowedAssistants ? { allowedAssistants: loaded.allowedAssistants } : {},
22
+ ...loaded.publicUrl ? { publicUrl: loaded.publicUrl } : {}
23
+ }
24
+ }
25
+ ])
26
+ ),
27
+ graphIds: input.graphIds
28
+ });
29
+ const pipelineDeps = buildPipelineDeps(input.deps, input.service);
30
+ return {
31
+ routes: channels.channelRouteBindings(registry.names),
32
+ wrapDispatcher: (inner) => channels.wrapChannelDispatcher({
33
+ registry,
34
+ inner,
35
+ logger: input.deps.logger ?? console
36
+ }),
37
+ handlers: {
38
+ handleInboundEvent: async (req) => {
39
+ const name = req.url.split("?")[0].split("/channels/")[1] ?? "";
40
+ const registered = registry.get(name);
41
+ if (!registered) throw SkeinHttpError.notFound(`No channel named "${name}".`);
42
+ return channels.handleInboundEvent(
43
+ registered,
44
+ {
45
+ method: req.method,
46
+ url: req.url,
47
+ headers: req.headers,
48
+ ...typeof req.body === "string" ? { text: req.body } : {}
49
+ },
50
+ pipelineDeps
51
+ );
52
+ }
53
+ }
54
+ };
55
+ }
56
+ function buildPipelineDeps(deps, service) {
57
+ let requestFilters;
58
+ const scopedService = (authContext) => {
59
+ if (!authContext && !requestFilters) return service();
60
+ const base = createContext(deps);
61
+ return createProtocolServiceFromContext({
62
+ ...base,
63
+ ...authContext?.user ? { authUser: authContext.user } : {},
64
+ ...authContext?.scopes ? { authScopes: authContext.scopes } : {},
65
+ deps: requestFilters && deps.auth ? {
66
+ ...base.deps,
67
+ store: createAuthScopedStore(base.deps.store, deps.auth, requestFilters, "threads")
68
+ } : base.deps
69
+ });
70
+ };
71
+ return {
72
+ ...deps.store.idempotency ? { idempotency: deps.store.idempotency } : {},
73
+ clock: () => deps.clock ? deps.clock() : /* @__PURE__ */ new Date(),
74
+ logger: deps.logger ?? console,
75
+ // Straight off the run event bus — the same stream `runs.joinStream` serves, without the HTTP
76
+ // connection per conversation that reaching it from outside would cost.
77
+ runFrames: { subscribe: (runId) => deps.bus.subscribe(runId) },
78
+ authorize: async (principal, authz) => {
79
+ if (!deps.auth) return void 0;
80
+ const context = {
81
+ user: {
82
+ identity: principal.identity,
83
+ display_name: principal.identity,
84
+ is_authenticated: true,
85
+ permissions: principal.permissions ?? [],
86
+ ...principal.metadata ?? {}
87
+ },
88
+ scopes: principal.permissions ?? []
89
+ };
90
+ const decision = await deps.auth.authorize({
91
+ resource: authz.resource,
92
+ action: authz.action,
93
+ value: {},
94
+ context
95
+ });
96
+ requestFilters = decision.filters;
97
+ return context;
98
+ },
99
+ ensureThread: async (threadId, metadata, authContext) => {
100
+ await scopedService(authContext).threads.create({
101
+ thread_id: threadId,
102
+ metadata,
103
+ ifExists: "do_nothing"
104
+ });
105
+ },
106
+ threadStatus: async (threadId) => {
107
+ const thread = await service().threads.get(threadId).catch(() => null);
108
+ return thread?.status ?? null;
109
+ },
110
+ createRun: async (input) => {
111
+ const run = await scopedService(input.authContext).runs.createBackground(input.threadId, {
112
+ assistant_id: input.assistantId,
113
+ ...input.input !== void 0 ? { input: input.input } : {},
114
+ ...input.command ? { command: input.command } : {},
115
+ ...input.ifThreadStatus ? { if_thread_status: [...input.ifThreadStatus] } : {},
116
+ ...input.multitaskStrategy ? { multitask_strategy: input.multitaskStrategy } : {},
117
+ ...input.metadata ? { metadata: input.metadata } : {},
118
+ ...input.webhook ? { webhook: input.webhook } : {},
119
+ stream_mode: [...input.streamMode]
120
+ });
121
+ return { runId: run.run_id };
122
+ }
123
+ };
124
+ }
125
+ async function importChannelsPackage(names) {
126
+ try {
127
+ return await import("@skein-js/channels");
128
+ } catch (cause) {
129
+ throw new SkeinConfigError(
130
+ `skein.channels configures ${names.join(", ")}, but @skein-js/channels is not installed. Add it as a dependency.`,
131
+ { cause }
132
+ );
133
+ }
134
+ }
135
+ export {
136
+ resolveChannels
137
+ };
@@ -7,6 +7,7 @@ import {
7
7
  import { MemorySaver as MemorySaver2 } from "@langchain/langgraph";
8
8
  import {
9
9
  loadAuthEngine,
10
+ loadChannels,
10
11
  loadConfig
11
12
  } from "@skein-js/config";
12
13
  import { langGraphResolver as langGraphResolver2 } from "@skein-js/langgraph";
@@ -148,6 +149,43 @@ function resolveMemoryBusLimits(explicit = {}, env = process.env) {
148
149
  };
149
150
  }
150
151
 
152
+ // src/webhooks-config.ts
153
+ var WEBHOOK_SECRET_ENV = "SKEIN_WEBHOOK_SECRET";
154
+ function resolveSecrets(raw, env) {
155
+ const fromEnv = (env[WEBHOOK_SECRET_ENV] ?? "").split(",").map((secret) => secret.trim()).filter((secret) => secret.length > 0);
156
+ if (fromEnv.length > 0) return fromEnv;
157
+ const configured = typeof raw.secret === "string" ? [raw.secret] : raw.secret ?? [];
158
+ return configured.map((secret) => secret.trim()).filter((secret) => secret.length > 0);
159
+ }
160
+ function resolveWebhooks(raw, options = {}) {
161
+ const env = options.env ?? process.env;
162
+ const secrets = resolveSecrets(raw ?? {}, env);
163
+ if (!raw && secrets.length === 0) return void 0;
164
+ const config = {};
165
+ if (secrets.length > 0) {
166
+ config.secrets = secrets;
167
+ if (!env[WEBHOOK_SECRET_ENV] && raw?.secret !== void 0) {
168
+ options.warn?.(
169
+ `skein: a webhook signing key is set in langgraph.json, which puts it in version control. Set ${WEBHOOK_SECRET_ENV} instead \u2014 it takes precedence over this value.`
170
+ );
171
+ }
172
+ }
173
+ if (!raw) return config;
174
+ const retries = {};
175
+ if (typeof raw.retries?.max_attempts === "number") retries.maxAttempts = raw.retries.max_attempts;
176
+ if (typeof raw.retries?.initial_delay_ms === "number") {
177
+ retries.initialDelayMs = raw.retries.initial_delay_ms;
178
+ }
179
+ if (Object.keys(retries).length > 0) config.retries = retries;
180
+ if (typeof raw.max_payload_bytes === "number") config.maxPayloadBytes = raw.max_payload_bytes;
181
+ if (typeof raw.retain_hours === "number") config.retainHours = raw.retain_hours;
182
+ if (Array.isArray(raw.allowed_hosts) && raw.allowed_hosts.length > 0) {
183
+ config.allowedHosts = [...raw.allowed_hosts];
184
+ }
185
+ if (typeof raw.require_https === "boolean") config.requireHttps = raw.require_https;
186
+ return Object.keys(config).length > 0 ? config : void 0;
187
+ }
188
+
151
189
  // src/in-memory-deps.ts
152
190
  function isGraphResolver(graphs) {
153
191
  const candidate = graphs;
@@ -174,6 +212,7 @@ function graphMapToResolver(graphs) {
174
212
  };
175
213
  }
176
214
  function embedInMemoryGraphs(graphs, overrides = {}) {
215
+ const webhooks = resolveWebhooks(void 0);
177
216
  return {
178
217
  // `maxPageSize` resolved for the same reason as the bus limits below: an embedded host's
179
218
  // `SKEIN_MAX_PAGE_SIZE` has to reach the driver that applies it.
@@ -191,6 +230,13 @@ function embedInMemoryGraphs(graphs, overrides = {}) {
191
230
  ephemeralCheckpointer: () => new MemorySaver(),
192
231
  // Clones a checkpoint before it is re-put under another thread id — see `ProtocolDeps.cloneCheckpoint`.
193
232
  cloneCheckpoint: cloneLangGraphCheckpoint,
233
+ // Resolved for the same reason as `maxPageSize` and the bus limits: an embedded host's env has to
234
+ // reach the code that applies it. Without this, a host that sets `SKEIN_WEBHOOK_SECRET` and
235
+ // follows the docs gets callbacks that are silently **unsigned** — a fail-open indistinguishable
236
+ // from a working setup, since an unsigned callback is delivered exactly like a signed one and only
237
+ // the receiver ever finds out. There is no `langgraph.json` on this path, so the env var is the
238
+ // only input; `overrides` still spreads last and wins.
239
+ ...webhooks ? { webhooks } : {},
194
240
  ...overrides
195
241
  };
196
242
  }
@@ -235,6 +281,10 @@ async function loadInMemoryRuntime(configPath, importModule, staticSchemas) {
235
281
  deps.auth = await loadAuthEngine(config.auth, { configDir, importModule });
236
282
  return {
237
283
  deps,
284
+ channels: await loadChannels(config.skein?.channels, {
285
+ configDir,
286
+ ...importModule ? { importModule } : {}
287
+ }),
238
288
  cors: corsFromHttpConfig(config.http),
239
289
  routes: routesFromHttpConfig(config.http)
240
290
  };
@@ -250,6 +300,9 @@ async function loadReloadableInMemoryRuntime(configPath, importModule, staticSch
250
300
  const threadTtl = resolveThreadTtl(first.config.checkpointer?.ttl);
251
301
  const storeTtl = resolveStoreTtl(first.config.store?.ttl);
252
302
  const idempotency = resolveIdempotency(first.config.skein?.idempotency);
303
+ const webhooks = resolveWebhooks(first.config.skein?.webhooks, {
304
+ warn: (message) => console.warn(message)
305
+ });
253
306
  const store = new MemorySkeinStore2({
254
307
  maxPageSize: resolveMaxPageSize(),
255
308
  ...threadTtl ? { threadTtl } : {},
@@ -269,10 +322,18 @@ async function loadReloadableInMemoryRuntime(configPath, importModule, staticSch
269
322
  ...threadTtl ? { threadTtl } : {},
270
323
  // Unlike `threadTtl`, absence here means *defaults*, not *off*: the header is honoured either way.
271
324
  ...idempotency ? { idempotency } : {},
325
+ ...webhooks ? { webhooks } : {},
272
326
  ...extraDeps
273
327
  };
274
328
  return {
275
329
  deps,
330
+ // Loaded here so the modules are imported once, with the same importer the graphs used — under
331
+ // `skein dev` that is the vite-backed one, which is what lets a channel be a TypeScript file in
332
+ // the user's own repo rather than something they have to build first.
333
+ channels: await loadChannels(first.config.skein?.channels, {
334
+ configDir: first.configDir,
335
+ ...importModule ? { importModule } : {}
336
+ }),
276
337
  cors: corsFromHttpConfig(first.config.http),
277
338
  routes: routesFromHttpConfig(first.config.http),
278
339
  config: first.config,
@@ -303,6 +364,7 @@ export {
303
364
  resolveIdempotency,
304
365
  resolveMaxPageSize,
305
366
  resolveMemoryBusLimits,
367
+ resolveWebhooks,
306
368
  normalizeEmbeddableGraphs,
307
369
  graphMapToResolver,
308
370
  embedInMemoryGraphs,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  loadInMemoryRuntime,
3
3
  loadReloadableInMemoryRuntime
4
- } from "./chunk-TCYGP4ZJ.js";
4
+ } from "./chunk-OZ477M7A.js";
5
5
  import "./chunk-JUBBCC7R.js";
6
6
  export {
7
7
  loadInMemoryRuntime,
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { ProtocolRuntime, RouteBinding, Logger, ProtocolDeps, RunWorkerOptions, CronSchedulerOptions, RunFailureReport, IdempotencyConfig, GraphResolver, RouteMatcher, DisabledRouteGroups, ProtocolResponse } from '@skein-js/agent-protocol';
1
+ import { ProtocolRuntime, RouteBinding, Logger, ProtocolDeps, RunWorkerOptions, CronSchedulerOptions, RunFailureReport, IdempotencyConfig, WebhookDeliveryConfig, GraphResolver, RouteMatcher, DisabledRouteGroups, ProtocolResponse } from '@skein-js/agent-protocol';
2
2
  export { CompiledGraphFactory, DEFAULT_RUN_CONCURRENCY, DEFAULT_SHUTDOWN_GRACE_MS, GraphResolver, Logger, ProtocolDeps, ResolvedGraph, RunWorkerOptions } from '@skein-js/agent-protocol';
3
- import { ModuleImporter, LanggraphJson, GraphSchemas } from '@skein-js/config';
3
+ import { LoadedChannel, ModuleImporter, LanggraphJson, GraphSchemas } from '@skein-js/config';
4
4
  import { CorsOptions } from 'cors';
5
5
  export { CorsOptions } from 'cors';
6
6
  import { MemoryRunEventBusOptions } from '@skein-js/storage-memory';
@@ -114,6 +114,8 @@ interface ResolvedRuntimeDeps {
114
114
  routes: readonly RouteBinding[];
115
115
  /** The resolved logger — see {@link ResolvedProtocolRuntime.logger}. */
116
116
  logger?: Logger;
117
+ /** Channel modules named by `skein.channels`, already imported. Absent on the injected-deps path. */
118
+ channels?: Record<string, LoadedChannel>;
117
119
  }
118
120
  /**
119
121
  * Resolve the `{ config } | { deps }` seam down to a `ProtocolDeps` — injected as-is, or fresh
@@ -416,6 +418,13 @@ interface InMemoryRuntimeConfig {
416
418
  cors?: CorsOptions;
417
419
  /** The route table to mount, with any `http.disable_*` groups already removed. */
418
420
  routes: readonly RouteBinding[];
421
+ /**
422
+ * Channel modules named by `skein.channels`, already imported, keyed by name.
423
+ *
424
+ * Empty when none is configured, which is what keeps the channel routes out of the table entirely
425
+ * rather than merely disabled.
426
+ */
427
+ channels?: Record<string, LoadedChannel>;
419
428
  }
420
429
  /** Load `langgraph.json`, wiring fresh in-memory drivers and reading its `http.cors` for the adapter. */
421
430
  declare function loadInMemoryRuntime(configPath: string, importModule?: ModuleImporter, staticSchemas?: Record<string, GraphSchemas>): Promise<InMemoryRuntimeConfig>;
@@ -497,14 +506,55 @@ interface RawIdempotency {
497
506
  */
498
507
  declare function resolveIdempotency(raw: RawIdempotency | undefined): IdempotencyConfig | undefined;
499
508
 
509
+ /** The raw `skein.webhooks` block as `langgraph.json` spells it. */
510
+ interface RawWebhooks {
511
+ retries?: {
512
+ max_attempts?: number;
513
+ initial_delay_ms?: number;
514
+ };
515
+ secret?: string | string[];
516
+ max_payload_bytes?: number;
517
+ retain_hours?: number;
518
+ allowed_hosts?: string[];
519
+ require_https?: boolean;
520
+ }
521
+ /**
522
+ * Map the raw block to {@link WebhookDeliveryConfig}, or `undefined` when nothing is set.
523
+ *
524
+ * `undefined` means **defaults, not disabled**, the same distinction `resolveIdempotency` draws: a run
525
+ * that carries a `webhook` owes a callback whether or not a policy was configured. There is no
526
+ * setting that stops skein trying — only `retries.max_attempts: 1`, which asks it to try once.
527
+ */
528
+ declare function resolveWebhooks(raw: RawWebhooks | undefined, options?: {
529
+ env?: Record<string, string | undefined>;
530
+ warn?: (message: string) => void;
531
+ }): WebhookDeliveryConfig | undefined;
532
+
500
533
  type AnyCompiledGraph = CompiledGraph<any>;
501
534
  /**
502
- * A graph you can embed in code: any compiled LangGraph.js graph, or a factory that builds one per run
503
- * (called with the run's `configurable`). Keys of a graph map become graph ids.
535
+ * The surface the engine actually drives, stated structurally.
536
+ *
537
+ * `CompiledGraph` is not the right bound here even though every graph is one. LangChain's own
538
+ * `createAgent` returns a `ReactAgent`, which is graph-*like* — it streams and it has state — but is
539
+ * not structurally a `CompiledGraph`, so requiring that type rejected the blessed way to build an
540
+ * agent. The engine never needed it: `langGraphResolver` casts whatever it is to an `AgentGraph`, and
541
+ * `AgentGraph` requires exactly these two methods.
542
+ *
543
+ * Kept narrow enough to still catch a mistake — an object with neither method is not a graph — while
544
+ * accepting anything the runtime can genuinely drive.
545
+ */
546
+ interface EmbeddableAgentSurface {
547
+ stream(input: any, options?: any): any;
548
+ getState(config: any): any;
549
+ }
550
+ /**
551
+ * A graph you can embed in code: any compiled LangGraph.js graph, anything `createAgent` returns, or a
552
+ * factory that builds one per run (called with the run's `configurable`). Keys of a graph map become
553
+ * graph ids.
504
554
  */
505
- type EmbeddableGraph = AnyCompiledGraph | ((config: {
555
+ type EmbeddableGraph = AnyCompiledGraph | EmbeddableAgentSurface | ((config: {
506
556
  configurable?: Record<string, unknown>;
507
- }) => AnyCompiledGraph | Promise<AnyCompiledGraph>);
557
+ }) => AnyCompiledGraph | EmbeddableAgentSurface | Promise<AnyCompiledGraph | EmbeddableAgentSurface>);
508
558
  /**
509
559
  * Accept either a ready {@link GraphResolver} or a plain graph map and return a `GraphResolver` either
510
560
  * way — the normalization every in-code embedding helper shares (`embedInMemoryGraphs` here,
@@ -703,4 +753,4 @@ type RuntimeGlobal = typeof globalThis & {
703
753
  /** Detect Node, Bun, or Deno without importing a runtime-specific module. */
704
754
  declare function detectRuntimeCapabilities(scope?: RuntimeGlobal): RuntimeCapabilities;
705
755
 
706
- export { type ConsoleLogLevel, type ConsoleLoggerOptions, type CorsSetting, DEFAULT_HEAP_SAMPLE_MS, DEFAULT_HEAP_WARN_PERCENT, DevStateSnapshot, type EmbeddableGraph, type FileReader, HEAP_REARM_MARGIN_PERCENT, HEAP_REARM_PERCENT, type HeapHeadroom, type HeapPressureContext, type HeapPressureMonitor, type HeapPressureMonitorOptions, type InMemoryRuntimeConfig, type IntervalHandle, type LanggraphCorsConfig, type RawIdempotency, type RawStoreTtl, type RawThreadTtl, type ReloadableInMemoryRuntime, type ResolvedMemoryBusLimits, type ResolvedProtocolRuntime, type ResolvedRuntimeDeps, type RuntimeCapabilities, type RuntimeMemorySnapshot, type RuntimeSignalSubscription, type SkeinRuntimeCommonOptions, type SkeinRuntimeOptions, allowedOrigin, applyNodeCors, checkHeapHeadroom, consoleMountFromHttpConfig, corsFromHttpConfig, corsPreflightHeaders, corsResponseHeaders, createConsoleLogger, createInMemoryDeps, describeError, describeHeapHeadroom, describePoolPressure, detectRuntimeCapabilities, disabledRoutesFromHttpConfig, embedInMemoryGraphs, formatLogMeta, graphMapToResolver, joinList, loadInMemoryRuntime, loadReloadableInMemoryRuntime, normalizeEmbeddableGraphs, readContainerMemoryLimit, resolveCronTickMs, resolveHeapPressureOptions, resolveIdempotency, resolveMaxPageSize, resolveMemoryBusLimits, resolveProtocolRuntime, resolveRunConcurrency, resolveRunTimeoutMs, resolveRuntimeDeps, resolveShutdownGraceMs, resolveStoreTtl, resolveThreadTtl, routeMatcherFor, routesFromHttpConfig, runFailureIdentity, sendNodeError, sendNodePreflight, sendNodeResponse, startHeapPressureMonitor, stripBasePath, toCorsOptions };
756
+ export { type ConsoleLogLevel, type ConsoleLoggerOptions, type CorsSetting, DEFAULT_HEAP_SAMPLE_MS, DEFAULT_HEAP_WARN_PERCENT, DevStateSnapshot, type EmbeddableGraph, type FileReader, HEAP_REARM_MARGIN_PERCENT, HEAP_REARM_PERCENT, type HeapHeadroom, type HeapPressureContext, type HeapPressureMonitor, type HeapPressureMonitorOptions, type InMemoryRuntimeConfig, type IntervalHandle, type LanggraphCorsConfig, type RawIdempotency, type RawStoreTtl, type RawThreadTtl, type RawWebhooks, type ReloadableInMemoryRuntime, type ResolvedMemoryBusLimits, type ResolvedProtocolRuntime, type ResolvedRuntimeDeps, type RuntimeCapabilities, type RuntimeMemorySnapshot, type RuntimeSignalSubscription, type SkeinRuntimeCommonOptions, type SkeinRuntimeOptions, allowedOrigin, applyNodeCors, checkHeapHeadroom, consoleMountFromHttpConfig, corsFromHttpConfig, corsPreflightHeaders, corsResponseHeaders, createConsoleLogger, createInMemoryDeps, describeError, describeHeapHeadroom, describePoolPressure, detectRuntimeCapabilities, disabledRoutesFromHttpConfig, embedInMemoryGraphs, formatLogMeta, graphMapToResolver, joinList, loadInMemoryRuntime, loadReloadableInMemoryRuntime, normalizeEmbeddableGraphs, readContainerMemoryLimit, resolveCronTickMs, resolveHeapPressureOptions, resolveIdempotency, resolveMaxPageSize, resolveMemoryBusLimits, resolveProtocolRuntime, resolveRunConcurrency, resolveRunTimeoutMs, resolveRuntimeDeps, resolveShutdownGraceMs, resolveStoreTtl, resolveThreadTtl, resolveWebhooks, routeMatcherFor, routesFromHttpConfig, runFailureIdentity, sendNodeError, sendNodePreflight, sendNodeResponse, startHeapPressureMonitor, stripBasePath, toCorsOptions };
package/dist/index.js CHANGED
@@ -15,14 +15,16 @@ import {
15
15
  resolveMemoryBusLimits,
16
16
  resolveStoreTtl,
17
17
  resolveThreadTtl,
18
+ resolveWebhooks,
18
19
  routesFromHttpConfig,
19
20
  toCorsOptions
20
- } from "./chunk-TCYGP4ZJ.js";
21
+ } from "./chunk-OZ477M7A.js";
21
22
  import "./chunk-JUBBCC7R.js";
22
23
 
23
24
  // src/resolve-runtime.ts
24
25
  import {
25
26
  createProtocolRuntime,
27
+ fetchWebhookDispatcher,
26
28
  skeinRoutes
27
29
  } from "@skein-js/agent-protocol";
28
30
 
@@ -166,22 +168,45 @@ function resolveLogger(option, injected, frameworkLogger) {
166
168
  return option ?? frameworkLogger;
167
169
  }
168
170
  async function resolveRuntimeDeps(options, frameworkLogger) {
169
- const loaded = options.deps ? { deps: options.deps, cors: void 0, routes: skeinRoutes } : await (await import("./in-memory-runtime-AOVHAXHJ.js")).loadInMemoryRuntime(options.config, options.importModule);
171
+ const loaded = options.deps ? { deps: options.deps, cors: void 0, routes: skeinRoutes, channels: void 0 } : await (await import("./in-memory-runtime-HE3LTSLD.js")).loadInMemoryRuntime(options.config, options.importModule);
170
172
  const logger = resolveLogger(options.logger, loaded.deps.logger, frameworkLogger);
171
173
  if (logger && !loaded.deps.logger) loaded.deps.logger = logger;
172
- return { deps: loaded.deps, cors: loaded.cors, routes: loaded.routes, logger };
174
+ return {
175
+ deps: loaded.deps,
176
+ cors: loaded.cors,
177
+ routes: loaded.routes,
178
+ ...loaded.channels ? { channels: loaded.channels } : {},
179
+ logger
180
+ };
173
181
  }
174
182
  async function resolveProtocolRuntime(options, frameworkLogger) {
175
183
  const {
176
184
  deps,
177
185
  cors: corsFromConfig,
178
186
  routes,
187
+ channels,
179
188
  logger
180
189
  } = await resolveRuntimeDeps(options, frameworkLogger);
181
190
  const heapPressureOptions = resolveHeapPressureOptions();
182
191
  const runTimeoutMs = resolveRunTimeoutMs(deps.runTimeoutMs);
183
192
  if (runTimeoutMs !== void 0) deps.runTimeoutMs = runTimeoutMs;
193
+ const runtimeRef = {};
194
+ const channelSurface = channels ? await (await import("./channels-runtime-OADE6ORT.js")).resolveChannels({
195
+ channels,
196
+ graphIds: deps.graphs.ids,
197
+ deps,
198
+ service: () => {
199
+ const current = runtimeRef.current;
200
+ if (!current) throw new Error("channel pipeline used before the runtime was assembled");
201
+ return current.service;
202
+ }
203
+ }) : void 0;
204
+ if (channelSurface) {
205
+ const inner = deps.webhookDispatcher ?? fetchWebhookDispatcher;
206
+ deps.webhookDispatcher = channelSurface.wrapDispatcher(inner);
207
+ }
184
208
  const runtime = createProtocolRuntime(deps, {
209
+ ...channelSurface ? { handlers: channelSurface.handlers } : {},
185
210
  worker: {
186
211
  ...options.worker,
187
212
  maxConcurrency: resolveRunConcurrency(options.worker?.maxConcurrency),
@@ -195,6 +220,7 @@ async function resolveProtocolRuntime(options, frameworkLogger) {
195
220
  enabled: options.scheduler?.enabled ?? routes.some((route) => route.group === "crons")
196
221
  }
197
222
  });
223
+ runtimeRef.current = runtime;
198
224
  await runtime.service.assistants.registerGraphAssistants();
199
225
  if (options.warm) {
200
226
  await Promise.all(
@@ -230,7 +256,15 @@ async function resolveProtocolRuntime(options, frameworkLogger) {
230
256
  await runtime.worker.stop();
231
257
  }
232
258
  };
233
- return { runtime: { ...runtime, worker }, cors: corsFromConfig, routes, logger };
259
+ return {
260
+ runtime: { ...runtime, worker },
261
+ cors: corsFromConfig,
262
+ // Channel routes are *appended*, never declared in `skeinRoutes`: they exist only when a channel
263
+ // is configured, which is what makes the feature undetectable to a deployment that never wanted
264
+ // it — strictly stronger than an `http.disable_*` flag, and it needs no `RouteGroup` to express.
265
+ routes: channelSurface ? [...routes, ...channelSurface.routes] : routes,
266
+ logger
267
+ };
234
268
  }
235
269
 
236
270
  // src/log-meta.ts
@@ -529,6 +563,7 @@ function sendNodeError(error, res, logger, adapterName = "skein") {
529
563
  return;
530
564
  }
531
565
  if (isSkeinHttpError(error)) {
566
+ if (error.status >= 500) logger?.error(`Request failed: ${error.message}`, error);
532
567
  res.writeHead(error.status, { "content-type": "application/json" });
533
568
  res.end(
534
569
  JSON.stringify({
@@ -688,6 +723,7 @@ export {
688
723
  resolveShutdownGraceMs,
689
724
  resolveStoreTtl,
690
725
  resolveThreadTtl,
726
+ resolveWebhooks,
691
727
  routeMatcherFor,
692
728
  routesFromHttpConfig,
693
729
  runFailureIdentity,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skein-js/server-kit",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
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
5
  "license": "Apache-2.0",
6
6
  "author": "Maina Wycliffe <wmmaina7@gmail.com>",
@@ -49,21 +49,29 @@
49
49
  "cors": "^2.8.5",
50
50
  "superjson": "^2.2.6",
51
51
  "zod": "^3.25.76",
52
- "@skein-js/agent-protocol": "0.15.0",
53
- "@skein-js/config": "0.15.0",
54
- "@skein-js/core": "0.15.0",
55
- "@skein-js/langgraph": "0.15.0",
56
- "@skein-js/storage-memory": "0.15.0"
52
+ "@skein-js/agent-protocol": "0.16.0",
53
+ "@skein-js/config": "0.16.0",
54
+ "@skein-js/core": "0.16.0",
55
+ "@skein-js/langgraph": "0.16.0",
56
+ "@skein-js/storage-memory": "0.16.0"
57
57
  },
58
58
  "peerDependencies": {
59
- "@langchain/langgraph": "^1.4.0"
59
+ "@langchain/langgraph": "^1.4.0",
60
+ "@skein-js/channels": "0.16.0"
60
61
  },
61
62
  "devDependencies": {
62
- "@langchain/core": "^1.2.0",
63
+ "@langchain/core": "^1.2.9",
63
64
  "@langchain/langgraph": "^1.4.0",
64
- "@types/cors": "^2.8.17"
65
+ "@langchain/langgraph-sdk": "^1.9.0",
66
+ "@types/cors": "^2.8.17",
67
+ "@skein-js/channels": "0.16.0"
65
68
  },
66
69
  "publishConfig": {
67
70
  "access": "public"
71
+ },
72
+ "peerDependenciesMeta": {
73
+ "@skein-js/channels": {
74
+ "optional": true
75
+ }
68
76
  }
69
77
  }