@juspay/neurolink 13.8.31 → 13.10.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/dist/index.d.ts CHANGED
@@ -460,7 +460,7 @@ export { DEFAULT_COMPACTION_THRESHOLD, resolveHistoryBudget, } from "./context/b
460
460
  * await server.start();
461
461
  * ```
462
462
  */
463
- export { AgentExecuteRequestSchema, AlreadyRunningError, BaseServerAdapter, ConfigurationError, createAgentRoutes, createAgentWebSocketHandler, createAllRoutes, createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompressionMiddleware, createDataStreamResponse, createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware, createServer, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes, ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError, pipeAsyncIterableToDataStream, RouteConflictError, RouteNotFoundError, registerAllRoutes, ServerAdapterError, ServerAdapterErrorCode, ServerAdapterFactory, ServerAuthenticationError, ServerAuthorizationError, ServerNameParamSchema, ServerRateLimitError, ServerStartError, ServerStopError, ServerTimeoutError, ServerValidationError, SessionIdParamSchema, StreamAbortedError, StreamingError, ToolArgumentsSchema, ToolExecuteRequestSchema, ToolNameParamSchema, ToolSearchQuerySchema, ValidationError, validateParams, validateQuery, validateRequest, WebSocketConnectionError, WebSocketConnectionManager, WebSocketError, WebSocketMessageRouter, wrapError, } from "./server/index.js";
463
+ export { AgentExecuteRequestSchema, AlreadyRunningError, BaseServerAdapter, ConfigurationError, createAgentRoutes, createAgentWebSocketHandler, createAllRoutes, createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompressionMiddleware, createDataStreamResponse, createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware, createServer, createSessionMiddleware, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes, ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError, pipeAsyncIterableToDataStream, RouteConflictError, RouteNotFoundError, registerAllRoutes, ServerAdapterError, ServerAdapterErrorCode, ServerAdapterFactory, ServerAuthenticationError, ServerAuthorizationError, ServerNameParamSchema, ServerRateLimitError, ServerStartError, ServerStopError, ServerTimeoutError, ServerValidationError, SessionIdParamSchema, StreamAbortedError, StreamingError, ToolArgumentsSchema, ToolExecuteRequestSchema, ToolNameParamSchema, ToolSearchQuerySchema, ValidationError, validateParams, validateQuery, validateRequest, WebSocketConnectionError, WebSocketConnectionManager, WebSocketError, WebSocketMessageRouter, wrapError, } from "./server/index.js";
464
464
  /**
465
465
  * @deprecated Use `ServerTimeoutError` instead — renamed to end the naming
466
466
  * collision with the canonical `utils/timeout.ts` `TimeoutError`. Kept as an
package/dist/index.js CHANGED
@@ -701,7 +701,7 @@ createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompr
701
701
  // Streaming
702
702
  createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware,
703
703
  // Server Factory
704
- createServer, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes,
704
+ createServer, createSessionMiddleware, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes,
705
705
  // Error Constants
706
706
  ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError,
707
707
  // OpenAPI
@@ -1364,6 +1364,12 @@ export declare class NeuroLink {
1364
1364
  * Create stream response
1365
1365
  */
1366
1366
  private createStreamResponse;
1367
+ /**
1368
+ * Whether `error` is the refusal of a conversation memory writer that opted in
1369
+ * to the erasure write protocol: the typed epoch error, or the CONFIG_ERROR
1370
+ * that storage which is unreachable, or not Redis, raises while the protocol is on.
1371
+ */
1372
+ private isStrictConversationAdmissionFailure;
1367
1373
  /**
1368
1374
  * Handle stream error with fallback
1369
1375
  */
package/dist/neurolink.js CHANGED
@@ -76,7 +76,7 @@ import { SkillsManager } from "./skills/skillsManager.js";
76
76
  import { createSkillCallTools, createSkillTools } from "./skills/skillTools.js";
77
77
  import { getMetricsAggregator, MetricsAggregator, } from "./observability/metricsAggregator.js";
78
78
  import { AnalyticsService, calculateAdvancedCost, parseAnalyticsQualityScore, } from "./analytics/index.js";
79
- import { SpanStatus, SpanType, CircuitBreakerOpenError, ConversationMemoryError, DEFAULT_DECISION_HOOK_TIMEOUT_MS, MAX_DECISION_HOOK_TIMEOUT_MS, ModelAccessDeniedError, } from "./types/index.js";
79
+ import { SpanStatus, SpanType, CircuitBreakerOpenError, ConversationMemoryError, ConversationWriterEpochError, DEFAULT_DECISION_HOOK_TIMEOUT_MS, MAX_DECISION_HOOK_TIMEOUT_MS, ModelAccessDeniedError, } from "./types/index.js";
80
80
  import { resolveTerminalAgentMode } from "./agent/prompts/terminalAgentPrompt.js";
81
81
  import { getExporterRegistry } from "./observability/exporterRegistry.js";
82
82
  import { SpanSerializer } from "./observability/utils/spanSerializer.js";
@@ -6053,6 +6053,11 @@ Current user's request: ${currentInput}`;
6053
6053
  await this.conversationMemory.initialize();
6054
6054
  }
6055
6055
  catch (err) {
6056
+ // Strict storage admission must not silently downgrade to process-local history.
6057
+ if (this.conversationMemoryConfig?.conversationMemory
6058
+ ?.erasureWriteProtocol === "conversation-erasure-v1") {
6059
+ throw err;
6060
+ }
6056
6061
  logger.warn("[NEUROLINK] Redis memory init failed, falling back to in-memory", {
6057
6062
  error: err instanceof Error ? err.message : String(err),
6058
6063
  generateInternalId,
@@ -10067,6 +10072,20 @@ Current user's request: ${currentInput}`;
10067
10072
  });
10068
10073
  return response;
10069
10074
  }
10075
+ /**
10076
+ * Whether `error` is the refusal of a conversation memory writer that opted in
10077
+ * to the erasure write protocol: the typed epoch error, or the CONFIG_ERROR
10078
+ * that storage which is unreachable, or not Redis, raises while the protocol is on.
10079
+ */
10080
+ isStrictConversationAdmissionFailure(error) {
10081
+ if (error instanceof ConversationWriterEpochError) {
10082
+ return true;
10083
+ }
10084
+ return (error instanceof ConversationMemoryError &&
10085
+ error.code === "CONFIG_ERROR" &&
10086
+ this.conversationMemoryConfig?.conversationMemory
10087
+ ?.erasureWriteProtocol === "conversation-erasure-v1");
10088
+ }
10070
10089
  /**
10071
10090
  * Handle stream error with fallback
10072
10091
  */
@@ -10080,6 +10099,12 @@ Current user's request: ${currentInput}`;
10080
10099
  if (error instanceof ContextBudgetExceededError) {
10081
10100
  throw error;
10082
10101
  }
10102
+ // A writer that opted in to the erasure write protocol and could not be
10103
+ // admitted must not be answered by a fallback provider that has none of
10104
+ // its history and stores nothing: fail closed, as generate() does.
10105
+ if (this.isStrictConversationAdmissionFailure(error)) {
10106
+ throw error;
10107
+ }
10083
10108
  logger.error("Stream generation failed, attempting fallback", {
10084
10109
  error: error instanceof Error ? error.message : String(error),
10085
10110
  });
@@ -83,6 +83,9 @@ export class BaseServerAdapter extends EventEmitter {
83
83
  "Content-Type",
84
84
  "Authorization",
85
85
  "X-Request-ID",
86
+ // The session middleware's default header: without it a browser
87
+ // client on another origin could not send it.
88
+ "X-Session-Id",
86
89
  ],
87
90
  credentials: config.cors?.credentials ?? false,
88
91
  maxAge: config.cors?.maxAge ?? 86400,
@@ -36,6 +36,7 @@ export { createCompressionMiddleware, createErrorHandlingMiddleware, createLoggi
36
36
  export { createDeprecationMiddleware } from "./middleware/deprecation.js";
37
37
  export { createMCPBodyAttachmentMiddleware, fastifyMCPBodyHook, } from "./middleware/mcpBodyAttachment.js";
38
38
  export { createRateLimitMiddleware, createSlidingWindowRateLimitMiddleware, InMemoryRateLimitStore, } from "./middleware/rateLimit.js";
39
+ export { createSessionMiddleware } from "./middleware/session.js";
39
40
  export { CommonSchemas, createFieldValidator, createRequestValidationMiddleware, ValidationError, } from "./middleware/validation.js";
40
41
  export { AgentExecuteRequestSchema as OpenAPIAgentExecuteRequestSchema, AgentExecuteResponseSchema, AgentInputSchema, ApiKeySecurityScheme, BasicSecurityScheme, BearerSecurityScheme, CommonParameters, ConversationMessageSchema, createApiInfo, createDeleteOperation, createErrorResponse as createOpenAPIErrorResponse, createGetOperation, createHeaderParameter, createOpenAPIGenerator, createPathParameter, createPostOperation, createQueryParameter, createServer as createOpenAPIServer, createStreamingPostOperation, createStreamingResponse, createSuccessResponse, DefaultServers, ErrorResponseSchema, generateOpenAPIFromConfig, generateOpenAPISpec, HealthResponseSchema, MCPServerStatusSchema, MCPServersListResponseSchema, MCPServerToolSchema, MetricsResponseSchema, NeuroLinkApiInfo, OpenAPIGenerator, OpenAPISchemas, ProviderInfoSchema, ReadyResponseSchema, SessionSchema, SessionsListResponseSchema, StandardErrorResponses, StandardTags, TokenUsageSchema, ToolCallSchema, ToolDefinitionSchema, ToolExecuteRequestSchema as OpenAPIToolExecuteRequestSchema, ToolExecuteResponseSchema, ToolListResponseSchema, ToolParameterSchema, } from "./openapi/index.js";
41
42
  export { createAgentRoutes, createAllRoutes, createHealthRoutes, createMCPRoutes, createMemoryRoutes, createOpenApiRoutes, createToolRoutes, createTranscribeRoutes, registerAllRoutes, createClaudeProxyRoutes, createOpenAIProxyRoutes, createCodexProxyRoutes, createGeminiProxyRoutes, } from "./routes/index.js";
@@ -79,6 +79,7 @@ export { createCompressionMiddleware, createErrorHandlingMiddleware, createLoggi
79
79
  export { createDeprecationMiddleware } from "./middleware/deprecation.js";
80
80
  export { createMCPBodyAttachmentMiddleware, fastifyMCPBodyHook, } from "./middleware/mcpBodyAttachment.js";
81
81
  export { createRateLimitMiddleware, createSlidingWindowRateLimitMiddleware, InMemoryRateLimitStore, } from "./middleware/rateLimit.js";
82
+ export { createSessionMiddleware } from "./middleware/session.js";
82
83
  export { CommonSchemas, createFieldValidator, createRequestValidationMiddleware, ValidationError, } from "./middleware/validation.js";
83
84
  // ============================================
84
85
  // OpenAPI
@@ -5,6 +5,7 @@
5
5
  export { createAuthMiddleware } from "./auth.js";
6
6
  export { createCacheMiddleware } from "./cache.js";
7
7
  export { createRateLimitMiddleware } from "./rateLimit.js";
8
+ export { createSessionMiddleware } from "./session.js";
8
9
  export { createRequestValidationMiddleware } from "./validation.js";
9
10
  export { createTimingMiddleware, createRequestIdMiddleware, createErrorHandlingMiddleware, createSecurityHeadersMiddleware, createLoggingMiddleware, createCompressionMiddleware, } from "./common.js";
10
11
  export { createAbortSignalMiddleware, createExpressAbortMiddleware, } from "./abortSignal.js";
@@ -5,6 +5,7 @@
5
5
  export { createAuthMiddleware } from "./auth.js";
6
6
  export { createCacheMiddleware } from "./cache.js";
7
7
  export { createRateLimitMiddleware } from "./rateLimit.js";
8
+ export { createSessionMiddleware } from "./session.js";
8
9
  export { createRequestValidationMiddleware } from "./validation.js";
9
10
  export { createTimingMiddleware, createRequestIdMiddleware, createErrorHandlingMiddleware, createSecurityHeadersMiddleware, createLoggingMiddleware, createCompressionMiddleware, } from "./common.js";
10
11
  export { createAbortSignalMiddleware, createExpressAbortMiddleware, } from "./abortSignal.js";
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Session Middleware
3
+ * Sets `ctx.session` from a header (or cookie) and scopes it to the
4
+ * authenticated user.
5
+ */
6
+ import type { MiddlewareDefinition, ServerSessionConfig } from "../../types/index.js";
7
+ /**
8
+ * Create session middleware.
9
+ *
10
+ * Reads a session id from `X-Session-Id` (or the configured header) and sets
11
+ * `ctx.session.id`. When the header is absent or empty and `cookieName` is set,
12
+ * that cookie supplies the id instead. When a user is authenticated the id
13
+ * becomes `<urlencoded-userId>~<id>`, so two users who send the same id get
14
+ * different sessions: the in-memory conversation manager keys sessions by id
15
+ * alone, and without the prefix one user could read and extend another's
16
+ * conversation by guessing its id. The delimiter is `~` rather than `:`,
17
+ * because Redis session ids and the perUserAuth memory routes reject `:`. A
18
+ * request with no id gets no session.
19
+ *
20
+ * The prefix isolates the conversations the agent routes keep. It is not an
21
+ * access check on the memory routes. Without `perUserAuth` they look a session
22
+ * up by the id in the URL (on the in-memory manager by that id alone, on Redis
23
+ * by it together with the `userId` query parameter), so a caller who can reach
24
+ * them and knows a prefixed id such as `bob~chat-1` reads that session unless
25
+ * the server prevents it. With `perUserAuth` they are scoped to the caller and
26
+ * refuse a session id that contains `:`. The `~` form this middleware writes
27
+ * is accepted there, so a session it created can be listed, read and deleted
28
+ * through the memory routes as well as used through the agent routes.
29
+ *
30
+ * The prefix also relies on `ctx.user` naming one person: when every client
31
+ * shares one credential they share one `ctx.user`, and one prefix.
32
+ *
33
+ * The server must carry middleware state for this to do anything. By default
34
+ * (`carryMiddlewareState` off) Express, Fastify and Koa build a fresh context
35
+ * for every middleware step and for the handler, so this middleware sees no
36
+ * `ctx.user` and the `ctx.session` it sets never reaches the handler; Hono
37
+ * shares the context only for a request whose client sent its own
38
+ * `X-Request-ID`. Nothing warns about it. `registerAllRoutes()` with
39
+ * `perUserAuth` turns the carry on for the server; otherwise create the server
40
+ * with `carryMiddlewareState: true`.
41
+ *
42
+ * With `perUserAuth` on the routes, the agent routes take the session only from
43
+ * `ctx.session`, and only for an authenticated request, so this middleware is
44
+ * how a signed-in client keeps a conversation. A request with no `ctx.user`
45
+ * (optional authentication) gets no conversation even when it sends an id, so
46
+ * anonymous callers never share one.
47
+ *
48
+ * With `perUserAuth` off (the default) the agent routes take the session from the
49
+ * request body and this middleware has no effect on them, whether
50
+ * `carryMiddlewareState` is off (the handler never receives `ctx.session`) or on
51
+ * (it does, and the routes do not read it); with the carry on it still sets
52
+ * `ctx.session` for your own routes. That holds on Express, Fastify and Koa, and
53
+ * on Hono when the client sent no `X-Request-ID`. The exception is a context that
54
+ * did not receive the adapters' carry: Hono when the client sent its own
55
+ * `X-Request-ID` (with the carry on or off), an adapter you wrote, or a handler
56
+ * called directly. There an authenticated user's session is `ctx.session` alone
57
+ * (the body's is ignored), and an anonymous caller's is `ctx.session`, else the
58
+ * body's, so anonymous callers that send the same id share one bare
59
+ * conversation.
60
+ *
61
+ * The agent routes keep a conversation only when conversation memory is
62
+ * enabled on the `NeuroLink` instance; without it nothing is remembered
63
+ * whatever the session id.
64
+ *
65
+ * A browser client on another origin must be allowed to send the header. The
66
+ * default `X-Session-Id` is in the servers' default CORS allowed headers. A
67
+ * custom `headerName` is not: add it to `cors.headers`, which replaces the
68
+ * default list when you set it. A cookie sent cross-origin also needs
69
+ * `cors.credentials: true` and a listed origin rather than `*`.
70
+ *
71
+ * Ids start with a letter or digit and continue with letters, digits, `.`, `_`
72
+ * or `-`, 128 characters at most. A header that is not valid is a 400. A
73
+ * cookie that is not valid is ignored, as if absent: a browser sends it on its
74
+ * own, so it must not turn every request into an error.
75
+ *
76
+ * Register it after authentication. The registration order is what runs: the
77
+ * `order` number (12, with auth at 10) is informational and nothing sorts by
78
+ * it, so a session middleware registered before authentication sees no user and
79
+ * sets an unprefixed id without any warning.
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * const neurolink = new NeuroLink({ conversationMemory: { enabled: true } });
84
+ * const server = await createServer(neurolink, { framework: "hono" });
85
+ * server.registerMiddleware(createAuthMiddleware({ type: "bearer", validate }));
86
+ * server.registerMiddleware(createSessionMiddleware());
87
+ * // perUserAuth also turns on carryMiddlewareState for this server.
88
+ * registerAllRoutes(server, "/api", { perUserAuth: true });
89
+ * // A client sends `X-Session-Id: chat-1`; the agent routes then keep that
90
+ * // conversation, separately for each authenticated user.
91
+ * ```
92
+ */
93
+ export declare function createSessionMiddleware(config?: ServerSessionConfig): MiddlewareDefinition;
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Session Middleware
3
+ * Sets `ctx.session` from a header (or cookie) and scopes it to the
4
+ * authenticated user.
5
+ */
6
+ import { ValidationError } from "../errors.js";
7
+ /**
8
+ * What a caller may name a session: short, starting with a letter or digit, and
9
+ * with no `~`, so the user prefix added below can never be spoofed by a crafted
10
+ * id. `:` is also refused: Redis session ids and the perUserAuth memory routes
11
+ * reject it, and a requested id must be usable as that segment as well as an
12
+ * in-memory map key.
13
+ */
14
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
15
+ const SESSION_ID_MESSAGE = "session id must be 1 to 128 characters: a letter or digit, then letters, digits, '.', '_' or '-'";
16
+ /**
17
+ * Join an authenticated user and a requested session id into one map key.
18
+ *
19
+ * `:` cannot appear: Redis `getSessionKey` and the perUserAuth memory routes
20
+ * reject it, so `<userId>:<id>` is listed by GET /memory/sessions but cannot
21
+ * be read or stored on Redis. `~` cannot appear in a requested id, and
22
+ * `encodeURIComponent` plus an extra `~` → `%7E` pass keeps it out of the
23
+ * user segment, including multi-tenant ids such as `cust:merchant:shop`.
24
+ */
25
+ function scopedSessionId(userId, requested) {
26
+ const user = encodeURIComponent(userId).replaceAll("~", "%7E");
27
+ return `${user}~${requested}`;
28
+ }
29
+ function readHeader(headers, name) {
30
+ const wanted = name.toLowerCase();
31
+ for (const [key, value] of Object.entries(headers)) {
32
+ if (key.toLowerCase() === wanted) {
33
+ return value;
34
+ }
35
+ }
36
+ return undefined;
37
+ }
38
+ function withSession(ctx, requested, next) {
39
+ ctx.session = {
40
+ id: ctx.user ? scopedSessionId(ctx.user.id, requested) : requested,
41
+ };
42
+ return next();
43
+ }
44
+ function readCookie(headers, name) {
45
+ const raw = readHeader(headers, "cookie");
46
+ if (!raw) {
47
+ return undefined;
48
+ }
49
+ for (const part of raw.split(";")) {
50
+ const separator = part.indexOf("=");
51
+ if (separator > 0 && part.slice(0, separator).trim() === name) {
52
+ try {
53
+ return decodeURIComponent(part.slice(separator + 1).trim());
54
+ }
55
+ catch {
56
+ return part.slice(separator + 1).trim();
57
+ }
58
+ }
59
+ }
60
+ return undefined;
61
+ }
62
+ /**
63
+ * Create session middleware.
64
+ *
65
+ * Reads a session id from `X-Session-Id` (or the configured header) and sets
66
+ * `ctx.session.id`. When the header is absent or empty and `cookieName` is set,
67
+ * that cookie supplies the id instead. When a user is authenticated the id
68
+ * becomes `<urlencoded-userId>~<id>`, so two users who send the same id get
69
+ * different sessions: the in-memory conversation manager keys sessions by id
70
+ * alone, and without the prefix one user could read and extend another's
71
+ * conversation by guessing its id. The delimiter is `~` rather than `:`,
72
+ * because Redis session ids and the perUserAuth memory routes reject `:`. A
73
+ * request with no id gets no session.
74
+ *
75
+ * The prefix isolates the conversations the agent routes keep. It is not an
76
+ * access check on the memory routes. Without `perUserAuth` they look a session
77
+ * up by the id in the URL (on the in-memory manager by that id alone, on Redis
78
+ * by it together with the `userId` query parameter), so a caller who can reach
79
+ * them and knows a prefixed id such as `bob~chat-1` reads that session unless
80
+ * the server prevents it. With `perUserAuth` they are scoped to the caller and
81
+ * refuse a session id that contains `:`. The `~` form this middleware writes
82
+ * is accepted there, so a session it created can be listed, read and deleted
83
+ * through the memory routes as well as used through the agent routes.
84
+ *
85
+ * The prefix also relies on `ctx.user` naming one person: when every client
86
+ * shares one credential they share one `ctx.user`, and one prefix.
87
+ *
88
+ * The server must carry middleware state for this to do anything. By default
89
+ * (`carryMiddlewareState` off) Express, Fastify and Koa build a fresh context
90
+ * for every middleware step and for the handler, so this middleware sees no
91
+ * `ctx.user` and the `ctx.session` it sets never reaches the handler; Hono
92
+ * shares the context only for a request whose client sent its own
93
+ * `X-Request-ID`. Nothing warns about it. `registerAllRoutes()` with
94
+ * `perUserAuth` turns the carry on for the server; otherwise create the server
95
+ * with `carryMiddlewareState: true`.
96
+ *
97
+ * With `perUserAuth` on the routes, the agent routes take the session only from
98
+ * `ctx.session`, and only for an authenticated request, so this middleware is
99
+ * how a signed-in client keeps a conversation. A request with no `ctx.user`
100
+ * (optional authentication) gets no conversation even when it sends an id, so
101
+ * anonymous callers never share one.
102
+ *
103
+ * With `perUserAuth` off (the default) the agent routes take the session from the
104
+ * request body and this middleware has no effect on them, whether
105
+ * `carryMiddlewareState` is off (the handler never receives `ctx.session`) or on
106
+ * (it does, and the routes do not read it); with the carry on it still sets
107
+ * `ctx.session` for your own routes. That holds on Express, Fastify and Koa, and
108
+ * on Hono when the client sent no `X-Request-ID`. The exception is a context that
109
+ * did not receive the adapters' carry: Hono when the client sent its own
110
+ * `X-Request-ID` (with the carry on or off), an adapter you wrote, or a handler
111
+ * called directly. There an authenticated user's session is `ctx.session` alone
112
+ * (the body's is ignored), and an anonymous caller's is `ctx.session`, else the
113
+ * body's, so anonymous callers that send the same id share one bare
114
+ * conversation.
115
+ *
116
+ * The agent routes keep a conversation only when conversation memory is
117
+ * enabled on the `NeuroLink` instance; without it nothing is remembered
118
+ * whatever the session id.
119
+ *
120
+ * A browser client on another origin must be allowed to send the header. The
121
+ * default `X-Session-Id` is in the servers' default CORS allowed headers. A
122
+ * custom `headerName` is not: add it to `cors.headers`, which replaces the
123
+ * default list when you set it. A cookie sent cross-origin also needs
124
+ * `cors.credentials: true` and a listed origin rather than `*`.
125
+ *
126
+ * Ids start with a letter or digit and continue with letters, digits, `.`, `_`
127
+ * or `-`, 128 characters at most. A header that is not valid is a 400. A
128
+ * cookie that is not valid is ignored, as if absent: a browser sends it on its
129
+ * own, so it must not turn every request into an error.
130
+ *
131
+ * Register it after authentication. The registration order is what runs: the
132
+ * `order` number (12, with auth at 10) is informational and nothing sorts by
133
+ * it, so a session middleware registered before authentication sees no user and
134
+ * sets an unprefixed id without any warning.
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * const neurolink = new NeuroLink({ conversationMemory: { enabled: true } });
139
+ * const server = await createServer(neurolink, { framework: "hono" });
140
+ * server.registerMiddleware(createAuthMiddleware({ type: "bearer", validate }));
141
+ * server.registerMiddleware(createSessionMiddleware());
142
+ * // perUserAuth also turns on carryMiddlewareState for this server.
143
+ * registerAllRoutes(server, "/api", { perUserAuth: true });
144
+ * // A client sends `X-Session-Id: chat-1`; the agent routes then keep that
145
+ * // conversation, separately for each authenticated user.
146
+ * ```
147
+ */
148
+ export function createSessionMiddleware(config = {}) {
149
+ const { headerName = "X-Session-Id", cookieName, skipPaths = [] } = config;
150
+ return {
151
+ name: "session",
152
+ // Informational: the adapters run middleware in registration order, so
153
+ // this only reads correctly when it is registered after authentication.
154
+ order: 12,
155
+ excludePaths: skipPaths,
156
+ handler: async (ctx, next) => {
157
+ // An empty header counts as absent, so the opted-in cookie can still
158
+ // supply the id.
159
+ const header = readHeader(ctx.headers, headerName);
160
+ if (header !== undefined && header !== "") {
161
+ if (!SESSION_ID_PATTERN.test(header)) {
162
+ throw new ValidationError([{ field: headerName, message: SESSION_ID_MESSAGE }], ctx.requestId);
163
+ }
164
+ return withSession(ctx, header, next);
165
+ }
166
+ const cookie = cookieName
167
+ ? readCookie(ctx.headers, cookieName)
168
+ : undefined;
169
+ if (cookie !== undefined && SESSION_ID_PATTERN.test(cookie)) {
170
+ return withSession(ctx, cookie, next);
171
+ }
172
+ return next();
173
+ },
174
+ };
175
+ }
@@ -128,6 +128,14 @@ export type MemoryToolResultRecord = {
128
128
  export type ConversationMemoryConfig = {
129
129
  /** Enable conversation memory feature */
130
130
  enabled: boolean;
131
+ /**
132
+ * Opt in to the `conversation-erasure-v1` write protocol on the Redis
133
+ * backend. Initialization then refuses to proceed (and `NeuroLink` does not
134
+ * fall back to in-memory history) unless the server is a standalone Redis
135
+ * with `maxmemory-policy noeviction`. Left unset, writers keep the ordinary
136
+ * storage behaviour and cannot erase permanently.
137
+ */
138
+ erasureWriteProtocol?: ConversationErasureProtocol;
131
139
  /**
132
140
  * How a session's stored tool steps are replayed into later prompts.
133
141
  * Default `"marker"`. `"full"` replays real tool-call / tool-result turns
@@ -473,10 +481,83 @@ export type ConversationMemoryEvents = {
473
481
  * Error types specific to conversation memory
474
482
  */
475
483
  export declare class ConversationMemoryError extends Error {
476
- code: "STORAGE_ERROR" | "CONFIG_ERROR" | "SESSION_NOT_FOUND" | "CLEANUP_ERROR";
484
+ code: "STORAGE_ERROR" | "CONFIG_ERROR" | "SESSION_NOT_FOUND" | "CLEANUP_ERROR" | "SESSION_ERASED";
477
485
  details?: Record<string, unknown> | undefined;
478
- constructor(message: string, code: "STORAGE_ERROR" | "CONFIG_ERROR" | "SESSION_NOT_FOUND" | "CLEANUP_ERROR", details?: Record<string, unknown> | undefined);
486
+ constructor(message: string, code: "STORAGE_ERROR" | "CONFIG_ERROR" | "SESSION_NOT_FOUND" | "CLEANUP_ERROR" | "SESSION_ERASED", details?: Record<string, unknown> | undefined);
479
487
  }
488
+ /** Write-protocol identifier of the conversation erasure fence. */
489
+ export type ConversationErasureProtocol = "conversation-erasure-v1";
490
+ /**
491
+ * Raised when a write reaches a session that was permanently erased. The
492
+ * erasure tombstone outlives the session's data, so a late writer cannot
493
+ * resurrect it.
494
+ */
495
+ export declare class ConversationSessionErasedError extends Error {
496
+ readonly code = "SESSION_ERASED";
497
+ constructor();
498
+ }
499
+ /**
500
+ * Raised when a fenced write cannot prove it belongs to the store epoch it was
501
+ * admitted under: the context is missing or not fenced, the Redis server
502
+ * restarted, or its eviction counter moved.
503
+ */
504
+ export declare class ConversationWriterEpochError extends Error {
505
+ readonly code = "SESSION_WRITER_EPOCH_LOST";
506
+ constructor();
507
+ }
508
+ /**
509
+ * What a Redis conversation writer resolved at initialization.
510
+ * `legacy` keeps the ordinary storage behaviour and cannot erase permanently;
511
+ * `fenced` binds every write to the server run id, store epoch and eviction
512
+ * counter observed at initialization.
513
+ */
514
+ export type ConversationErasureWriteContext = {
515
+ mode: "legacy";
516
+ reason: string;
517
+ strict: false;
518
+ } | {
519
+ mode: "fenced";
520
+ strict: boolean;
521
+ runId: string;
522
+ epoch: string;
523
+ evictedKeys: string;
524
+ evictionPolicy: "noeviction";
525
+ };
526
+ /** Whether this writer participates in the v1 erasure fence. */
527
+ export type ConversationErasureWriterStatus = {
528
+ status: "unsupported";
529
+ protocol: ConversationErasureProtocol;
530
+ strict: boolean;
531
+ reason: string;
532
+ } | {
533
+ status: "participating";
534
+ strict: boolean;
535
+ backend: "redis-standalone";
536
+ protocol: ConversationErasureProtocol;
537
+ serverRunIdDigest: string;
538
+ storeEpochDigest: string;
539
+ evictionPolicy: "noeviction";
540
+ evictionCounter: number;
541
+ };
542
+ /** Receipt returned by a confirmed permanent erasure. */
543
+ export type ConversationErasureResult = {
544
+ status: "erased";
545
+ backend: "redis-standalone";
546
+ protocol: ConversationErasureProtocol;
547
+ participatingWritesFenced: true;
548
+ strictWriteProtocol: true;
549
+ legacyWritersFenced: false;
550
+ sessionId: string;
551
+ userId: string;
552
+ namespaceDigest: string;
553
+ serverRunIdDigest: string;
554
+ storeEpochDigest: string;
555
+ evictionPolicy: "noeviction";
556
+ evictionCounter: number;
557
+ deletedKeys: number;
558
+ removedIndexMembers: number;
559
+ tombstoneExpiry: null;
560
+ };
480
561
  /**
481
562
  * NeuroLink initialization options
482
563
  * Configuration for creating NeuroLink instances with conversation memory
@@ -45,3 +45,27 @@ export class ConversationMemoryError extends Error {
45
45
  this.name = "ConversationMemoryError";
46
46
  }
47
47
  }
48
+ /**
49
+ * Raised when a write reaches a session that was permanently erased. The
50
+ * erasure tombstone outlives the session's data, so a late writer cannot
51
+ * resurrect it.
52
+ */
53
+ export class ConversationSessionErasedError extends Error {
54
+ code = "SESSION_ERASED";
55
+ constructor() {
56
+ super("Session permanently erased; write refused");
57
+ this.name = "ConversationSessionErasedError";
58
+ }
59
+ }
60
+ /**
61
+ * Raised when a fenced write cannot prove it belongs to the store epoch it was
62
+ * admitted under: the context is missing or not fenced, the Redis server
63
+ * restarted, or its eviction counter moved.
64
+ */
65
+ export class ConversationWriterEpochError extends Error {
66
+ code = "SESSION_WRITER_EPOCH_LOST";
67
+ constructor() {
68
+ super("Conversation writer epoch is unavailable or changed; write refused");
69
+ this.name = "ConversationWriterEpochError";
70
+ }
71
+ }
@@ -115,7 +115,12 @@ export type CORSConfig = {
115
115
  origins?: string[];
116
116
  /** Allowed HTTP methods */
117
117
  methods?: string[];
118
- /** Allowed headers */
118
+ /**
119
+ * Allowed request headers. Default `Content-Type`, `Authorization`,
120
+ * `X-Request-ID` and `X-Session-Id`. A list you pass replaces the default, it
121
+ * is not added to it, so keep the ones your clients send, and add the header
122
+ * name of a custom `createSessionMiddleware({ headerName })`.
123
+ */
119
124
  headers?: string[];
120
125
  /** Allow credentials */
121
126
  credentials?: boolean;
@@ -486,7 +491,12 @@ export type RouteGroup = {
486
491
  export type MiddlewareDefinition = {
487
492
  /** Middleware name */
488
493
  name: string;
489
- /** Execution order (lower = earlier) */
494
+ /**
495
+ * Where this middleware belongs relative to the others, for reading and for
496
+ * the debug log. Informational only: the adapters do not sort by it, they run
497
+ * middleware in the order it was registered. The built-ins' numbers (for
498
+ * example authentication 10, session 12) say what to register first.
499
+ */
490
500
  order?: number;
491
501
  /** Middleware handler */
492
502
  handler: MiddlewareHandler;
@@ -1171,6 +1181,34 @@ export type ServerValidationResult<T> = {
1171
1181
  error: ErrorResponse;
1172
1182
  data?: undefined;
1173
1183
  };
1184
+ /**
1185
+ * Session middleware configuration
1186
+ *
1187
+ * The middleware only has an effect on a server that carries middleware state
1188
+ * (`ServerAdapterConfig.carryMiddlewareState`, which `registerAllRoutes()`
1189
+ * turns on when given `perUserAuth`); without it the handler does not see the
1190
+ * session it sets, except on Hono for a request whose client sent its own
1191
+ * `X-Request-ID`, which shares one context with the handler either way (with
1192
+ * `perUserAuth` off, the agent routes can then use that session).
1193
+ */
1194
+ export type ServerSessionConfig = {
1195
+ /**
1196
+ * Header that carries the session id (default: "X-Session-Id"). A header
1197
+ * holding an invalid id is a 400; an empty one counts as absent. The default
1198
+ * is in the servers' default CORS allowed headers; a different name is not,
1199
+ * so a browser client on another origin needs it added to `cors.headers`.
1200
+ */
1201
+ headerName?: string;
1202
+ /**
1203
+ * Cookie that carries the session id, read when the header is absent or
1204
+ * empty. Off by default: a cookie is sent by the browser on its own, so
1205
+ * enabling it is the operator's decision. A cookie holding an invalid id is
1206
+ * ignored, as if absent, rather than failing the request.
1207
+ */
1208
+ cookieName?: string;
1209
+ /** Skip the middleware for certain paths */
1210
+ skipPaths?: string[];
1211
+ };
1174
1212
  /**
1175
1213
  * Authentication configuration
1176
1214
  */