@eidentic/nextjs 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work, excluding
103
+ those notices that do not pertain to any part of the Derivative
104
+ Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Baran Özdemir
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # @eidentic/nextjs
2
+
3
+ Next.js App Router integration for Eidentic — `withEidentic` wraps an agent as a
4
+ `POST` route handler that emits an AI SDK UI-compatible stream, and `eidenticNextConfig`
5
+ patches your `next.config.ts` to prevent native-addon bundling errors (`better-sqlite3`,
6
+ etc.). Works with `useChat` from the Vercel AI SDK out of the box.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pnpm add @eidentic/nextjs @eidentic/libsql
12
+ ```
13
+
14
+ > Use `@eidentic/libsql` (pure-JS) instead of `@eidentic/sqlite` (native addon) in Next.js
15
+ > and other bundler environments.
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ // next.config.ts
21
+ import { eidenticNextConfig } from "@eidentic/nextjs";
22
+ import type { NextConfig } from "next";
23
+
24
+ export default eidenticNextConfig({} satisfies NextConfig);
25
+ ```
26
+
27
+ ```ts
28
+ // app/api/chat/route.ts
29
+ import { withEidentic } from "@eidentic/nextjs";
30
+ import { Agent, AIModel } from "eidentic";
31
+ import { LibsqlStore } from "@eidentic/libsql";
32
+ import { anthropic } from "@ai-sdk/anthropic";
33
+
34
+ export const runtime = "nodejs";
35
+
36
+ const agent = new Agent({
37
+ id: "support",
38
+ model: new AIModel(anthropic("claude-sonnet-4-5")),
39
+ store: new LibsqlStore("file:eidentic.db"),
40
+ });
41
+
42
+ export const POST = withEidentic(agent);
43
+ ```
44
+
45
+ ```tsx
46
+ // Any React component
47
+ import { useChat } from "ai/react";
48
+
49
+ export function Chat() {
50
+ const { messages, input, handleInputChange, handleSubmit } = useChat({ api: "/api/chat" });
51
+ return (/* render messages and input */);
52
+ }
53
+ ```
54
+
55
+ ## Links
56
+
57
+ - [GitHub](https://github.com/eidentic/eidentic)
58
+ - [Issue tracker](https://github.com/eidentic/eidentic/issues)
59
+ - [Root README](https://github.com/eidentic/eidentic#readme)
60
+
61
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ eidenticNextConfig: () => eidenticNextConfig,
24
+ withEidentic: () => withEidentic
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+ var import_server = require("@eidentic/server");
28
+ function toHeaders(h) {
29
+ if (h instanceof Headers) return h;
30
+ return new Headers(h);
31
+ }
32
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
33
+ function withEidentic(agent, opts = {}) {
34
+ const protocol = opts.protocol ?? "ai-sdk-ui";
35
+ const maxBodyBytes = opts.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
36
+ return async function handler(req) {
37
+ const contentLength = req.headers.get("content-length");
38
+ if (contentLength !== null) {
39
+ const bytes = parseInt(contentLength, 10);
40
+ if (!isNaN(bytes) && bytes > maxBodyBytes) {
41
+ return new Response(
42
+ JSON.stringify({ error: `Request body too large (max ${maxBodyBytes} bytes)` }),
43
+ { status: 413, headers: { "Content-Type": "application/json" } }
44
+ );
45
+ }
46
+ }
47
+ let rawText;
48
+ try {
49
+ const reader = req.body?.getReader();
50
+ if (!reader) {
51
+ rawText = "";
52
+ } else {
53
+ const decoder = new TextDecoder();
54
+ const chunks = [];
55
+ let totalBytes = 0;
56
+ while (true) {
57
+ const { done, value } = await reader.read();
58
+ if (done) break;
59
+ if (value) {
60
+ totalBytes += value.byteLength;
61
+ if (totalBytes > maxBodyBytes) {
62
+ reader.cancel().catch(() => {
63
+ });
64
+ return new Response(
65
+ JSON.stringify({ error: `Request body too large (max ${maxBodyBytes} bytes)` }),
66
+ { status: 413, headers: { "Content-Type": "application/json" } }
67
+ );
68
+ }
69
+ chunks.push(value);
70
+ }
71
+ }
72
+ rawText = decoder.decode(
73
+ chunks.length === 1 ? chunks[0] : chunks.reduce((acc, c) => {
74
+ const merged = new Uint8Array(acc.byteLength + c.byteLength);
75
+ merged.set(acc, 0);
76
+ merged.set(c, acc.byteLength);
77
+ return merged;
78
+ }, new Uint8Array(0))
79
+ );
80
+ }
81
+ } catch {
82
+ return new Response(
83
+ JSON.stringify({ error: "Invalid JSON body" }),
84
+ { status: 400, headers: { "Content-Type": "application/json" } }
85
+ );
86
+ }
87
+ let body;
88
+ try {
89
+ body = JSON.parse(rawText);
90
+ } catch {
91
+ return new Response(
92
+ JSON.stringify({ error: "Invalid JSON body" }),
93
+ { status: 400, headers: { "Content-Type": "application/json" } }
94
+ );
95
+ }
96
+ const input = body.input ?? body.message;
97
+ if (typeof input !== "string" || input.trim() === "") {
98
+ return new Response(
99
+ JSON.stringify({ error: "Missing or invalid 'input' (or 'message') field" }),
100
+ { status: 400, headers: { "Content-Type": "application/json" } }
101
+ );
102
+ }
103
+ const sessionId = typeof body.sessionId === "string" && body.sessionId.length > 0 ? body.sessionId : crypto.randomUUID();
104
+ let userId;
105
+ let orgId;
106
+ if (opts.identify) {
107
+ const principal = await opts.identify(req);
108
+ userId = principal.userId;
109
+ orgId = principal.orgId;
110
+ } else {
111
+ userId = typeof body.userId === "string" && body.userId.length > 0 ? body.userId : void 0;
112
+ }
113
+ const signal = req.signal;
114
+ const events = agent.query(input, { sessionId, userId, orgId, signal });
115
+ if (protocol === "ai-sdk-ui") {
116
+ const streamOpts = {};
117
+ if (opts.headers) {
118
+ streamOpts.headers = toHeaders(opts.headers);
119
+ }
120
+ return (0, import_server.toUIMessageStreamResponse)(events, streamOpts);
121
+ }
122
+ const extraHeaders = opts.headers ? toHeaders(opts.headers) : new Headers();
123
+ extraHeaders.set("Content-Type", "application/x-ndjson");
124
+ extraHeaders.set("Transfer-Encoding", "chunked");
125
+ const stream = new ReadableStream({
126
+ async start(controller) {
127
+ const encoder = new TextEncoder();
128
+ try {
129
+ for await (const ev of events) {
130
+ if (signal.aborted) break;
131
+ controller.enqueue(encoder.encode(JSON.stringify(ev) + "\n"));
132
+ }
133
+ } catch (err) {
134
+ if (!signal.aborted) {
135
+ const msg = err instanceof Error ? err.message : String(err);
136
+ controller.enqueue(
137
+ encoder.encode(
138
+ JSON.stringify({
139
+ type: "result",
140
+ subtype: "error",
141
+ output: msg,
142
+ usage: { inputTokens: 0, outputTokens: 0 },
143
+ numTurns: 0,
144
+ sessionId
145
+ }) + "\n"
146
+ )
147
+ );
148
+ }
149
+ } finally {
150
+ controller.close();
151
+ }
152
+ }
153
+ });
154
+ return new Response(stream, { headers: extraHeaders });
155
+ };
156
+ }
157
+ function eidenticNextConfig(userConfig = {}) {
158
+ const existing = Array.isArray(userConfig.serverExternalPackages) ? userConfig.serverExternalPackages : [];
159
+ const eidentic = ["better-sqlite3"];
160
+ const merged = [.../* @__PURE__ */ new Set([...existing, ...eidentic])];
161
+ return {
162
+ ...userConfig,
163
+ serverExternalPackages: merged
164
+ };
165
+ }
166
+ // Annotate the CommonJS export names for ESM import in node:
167
+ 0 && (module.exports = {
168
+ eidenticNextConfig,
169
+ withEidentic
170
+ });
@@ -0,0 +1,213 @@
1
+ import { Agent } from '@eidentic/core';
2
+
3
+ /**
4
+ * @eidentic/nextjs — Next.js App Router integration for Eidentic agents.
5
+ *
6
+ * ## Quick start
7
+ *
8
+ * ```ts
9
+ * // app/api/chat/route.ts
10
+ * import { withEidentic } from "@eidentic/nextjs";
11
+ * import { myAgent } from "@/lib/agent";
12
+ *
13
+ * export const runtime = "nodejs"; // Required: Eidentic uses Node.js APIs
14
+ * export const POST = withEidentic(myAgent);
15
+ * ```
16
+ *
17
+ * ## next.config setup
18
+ *
19
+ * Avoid native-module bundling errors with `eidenticNextConfig`:
20
+ *
21
+ * ```ts
22
+ * // next.config.ts
23
+ * import { eidenticNextConfig } from "@eidentic/nextjs";
24
+ * import type { NextConfig } from "next";
25
+ *
26
+ * const nextConfig: NextConfig = {};
27
+ * export default eidenticNextConfig(nextConfig);
28
+ * ```
29
+ *
30
+ * If you use `@eidentic/sqlite` (which depends on `better-sqlite3`, a native
31
+ * addon), the config helper ensures it is not bundled by the Next.js Webpack
32
+ * pipeline. Prefer `@eidentic/libsql` in serverless/edge environments since
33
+ * it has no native addon.
34
+ */
35
+
36
+ /**
37
+ * Wire protocol for the route handler response.
38
+ *
39
+ * - `"ai-sdk-ui"` (default) — AI SDK v6 UI message-stream format.
40
+ * Compatible with `useChat` from `@ai-sdk/react`. This is the recommended
41
+ * default: structured, typed, and compatible with the entire AI SDK
42
+ * ecosystem.
43
+ *
44
+ * - `"ndjson"` — Raw NDJSON stream of `StreamEvent` objects, one per line.
45
+ * Use this with `@eidentic/react`'s `useEidenticStream`. Choose this when you
46
+ * need access to low-level Eidentic events (tool results, session metadata,
47
+ * cost/usage) that the AI SDK UI protocol does not surface.
48
+ */
49
+ type EidenticProtocol = "ai-sdk-ui" | "ndjson";
50
+ interface WithEidenticOptions {
51
+ /**
52
+ * Stream protocol. Defaults to `"ai-sdk-ui"`.
53
+ *
54
+ * Use `"ai-sdk-ui"` when the frontend uses `useChat` (AI SDK / CopilotKit).
55
+ * Use `"ndjson"` when the frontend uses `@eidentic/react`'s `useEidenticStream`
56
+ * or when you need raw `StreamEvent` access.
57
+ *
58
+ * @default "ai-sdk-ui"
59
+ */
60
+ protocol?: EidenticProtocol;
61
+ /**
62
+ * Extra HTTP headers to include in the streaming response.
63
+ * Forwarded to `toUIMessageStreamResponse` (for `"ai-sdk-ui"` protocol) or
64
+ * set on the raw `Response` (for `"ndjson"` protocol).
65
+ */
66
+ headers?: Headers | Record<string, string>;
67
+ /**
68
+ * Maximum allowed request body size in bytes. Requests with a `Content-Length`
69
+ * header exceeding this limit are rejected with HTTP 413 before the body is
70
+ * parsed. Defaults to 1 MB (1_048_576 bytes).
71
+ *
72
+ * @default 1_048_576
73
+ */
74
+ maxBodyBytes?: number;
75
+ /**
76
+ * Derive the trusted principal identity server-side from the incoming request.
77
+ * When provided, the returned `userId` and `orgId` are used instead of any
78
+ * values supplied in the request body, preventing clients from spoofing their
79
+ * identity.
80
+ *
81
+ * IMPORTANT: This is the recommended way to set `userId` in multi-tenant
82
+ * deployments. Always derive identity from your application's authenticated
83
+ * session (e.g. via cookies, JWT, or a session store), NOT from the request
84
+ * body, which is caller-controlled.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * export const POST = withEidentic(agent, {
89
+ * async identify(req) {
90
+ * const session = await getServerSession(req); // your auth helper
91
+ * return { userId: session.user.id };
92
+ * },
93
+ * });
94
+ * ```
95
+ */
96
+ identify?: (req: Request) => {
97
+ userId?: string;
98
+ orgId?: string;
99
+ } | Promise<{
100
+ userId?: string;
101
+ orgId?: string;
102
+ }>;
103
+ }
104
+ /**
105
+ * Creates a Next.js App Router POST route handler that streams a Eidentic
106
+ * agent's response to the client.
107
+ *
108
+ * **SECURITY NOTICE — this function performs NO authentication or authorization.**
109
+ * It is a low-level convenience wrapper that reads the request body and starts
110
+ * an agent run. In any multi-tenant deployment you MUST:
111
+ *
112
+ * 1. Authenticate the caller BEFORE the handler runs (e.g. via Next.js middleware,
113
+ * or an `identify` option that reads your session cookie / JWT).
114
+ * 2. Derive `userId` and `sessionId` from your application's authenticated session,
115
+ * NOT from the request body (`body.userId` / `body.sessionId` are caller-controlled
116
+ * and can be forged). Use the `identify` option for this.
117
+ * 3. Never expose this handler on a public route without protecting it.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * // app/api/chat/route.ts
122
+ * import { withEidentic } from "@eidentic/nextjs";
123
+ * import { myAgent } from "@/lib/agent";
124
+ *
125
+ * // IMPORTANT: Eidentic requires the Node.js runtime (SQLite, crypto, etc.).
126
+ * // Add this export to every route file that uses withEidentic.
127
+ * export const runtime = "nodejs";
128
+ *
129
+ * // Simple (single-tenant / no auth):
130
+ * export const POST = withEidentic(myAgent);
131
+ *
132
+ * // Multi-tenant — derive userId server-side from the authenticated session:
133
+ * export const POST = withEidentic(myAgent, {
134
+ * async identify(req) {
135
+ * const session = await getServerSession(req); // your auth helper
136
+ * if (!session) throw new Error("Unauthenticated"); // or return 401 yourself
137
+ * return { userId: session.user.id };
138
+ * },
139
+ * });
140
+ * // or with options:
141
+ * // export const POST = withEidentic(myAgent, { protocol: "ndjson" });
142
+ * ```
143
+ *
144
+ * ### Request body (JSON)
145
+ *
146
+ * | Field | Type | Required | Description |
147
+ * |-------------|----------|----------|------------------------------------------|
148
+ * | `input` | `string` | yes* | The user message |
149
+ * | `message` | `string` | yes* | Alias for `input` (useChat default name) |
150
+ * | `sessionId` | `string` | no | Resume an existing session |
151
+ * | `userId` | `string` | no | User ID for memory scoping (see WARNING) |
152
+ *
153
+ * *One of `input` or `message` must be present and non-empty.
154
+ *
155
+ * WARNING: `userId` and `sessionId` in the request body are caller-controlled.
156
+ * Always derive identity server-side via the `identify` option in multi-tenant
157
+ * deployments — do not rely on client-supplied values for access control.
158
+ *
159
+ * ### Protocol: `"ai-sdk-ui"` (default)
160
+ *
161
+ * The response uses the Vercel AI SDK v6 UI message-stream SSE format.
162
+ * Wire it up with `useChat` from `@ai-sdk/react`:
163
+ *
164
+ * ```tsx
165
+ * import { useChat } from "@ai-sdk/react";
166
+ * const { messages, input, handleInputChange, handleSubmit } = useChat({
167
+ * api: "/api/chat",
168
+ * });
169
+ * ```
170
+ *
171
+ * ### Protocol: `"ndjson"`
172
+ *
173
+ * Each line is a JSON-serialised `StreamEvent` followed by `\n`.
174
+ * Content-Type is `application/x-ndjson`.
175
+ * Use `@eidentic/react`'s `useEidenticStream` on the client.
176
+ */
177
+ declare function withEidentic(agent: Agent, opts?: WithEidenticOptions): (req: Request) => Promise<Response>;
178
+ /**
179
+ * Merges Eidentic-required Next.js config onto a user-supplied base config.
180
+ *
181
+ * What it does:
182
+ * - Appends `"better-sqlite3"` to `serverExternalPackages` so the Webpack
183
+ * bundler never tries to bundle the native addon (which would fail).
184
+ *
185
+ * **If you use `@eidentic/libsql` instead of `@eidentic/sqlite`** you don't need
186
+ * this (libsql has no native addon), but it's harmless to include anyway.
187
+ *
188
+ * @example
189
+ * ```ts
190
+ * // next.config.ts
191
+ * import { eidenticNextConfig } from "@eidentic/nextjs";
192
+ * import type { NextConfig } from "next";
193
+ *
194
+ * const baseConfig: NextConfig = {
195
+ * // your existing config here
196
+ * };
197
+ *
198
+ * export default eidenticNextConfig(baseConfig);
199
+ * ```
200
+ */
201
+ declare function eidenticNextConfig(userConfig?: NextConfigShape): NextConfigShape;
202
+ /**
203
+ * Minimal shape of Next.js config that this package touches.
204
+ * Using a loose record type avoids a `next` peer dep at the type level,
205
+ * so the package builds correctly in environments where `next` is only
206
+ * available at runtime.
207
+ */
208
+ interface NextConfigShape {
209
+ serverExternalPackages?: string[];
210
+ [key: string]: unknown;
211
+ }
212
+
213
+ export { type EidenticProtocol, type NextConfigShape, type WithEidenticOptions, eidenticNextConfig, withEidentic };
@@ -0,0 +1,213 @@
1
+ import { Agent } from '@eidentic/core';
2
+
3
+ /**
4
+ * @eidentic/nextjs — Next.js App Router integration for Eidentic agents.
5
+ *
6
+ * ## Quick start
7
+ *
8
+ * ```ts
9
+ * // app/api/chat/route.ts
10
+ * import { withEidentic } from "@eidentic/nextjs";
11
+ * import { myAgent } from "@/lib/agent";
12
+ *
13
+ * export const runtime = "nodejs"; // Required: Eidentic uses Node.js APIs
14
+ * export const POST = withEidentic(myAgent);
15
+ * ```
16
+ *
17
+ * ## next.config setup
18
+ *
19
+ * Avoid native-module bundling errors with `eidenticNextConfig`:
20
+ *
21
+ * ```ts
22
+ * // next.config.ts
23
+ * import { eidenticNextConfig } from "@eidentic/nextjs";
24
+ * import type { NextConfig } from "next";
25
+ *
26
+ * const nextConfig: NextConfig = {};
27
+ * export default eidenticNextConfig(nextConfig);
28
+ * ```
29
+ *
30
+ * If you use `@eidentic/sqlite` (which depends on `better-sqlite3`, a native
31
+ * addon), the config helper ensures it is not bundled by the Next.js Webpack
32
+ * pipeline. Prefer `@eidentic/libsql` in serverless/edge environments since
33
+ * it has no native addon.
34
+ */
35
+
36
+ /**
37
+ * Wire protocol for the route handler response.
38
+ *
39
+ * - `"ai-sdk-ui"` (default) — AI SDK v6 UI message-stream format.
40
+ * Compatible with `useChat` from `@ai-sdk/react`. This is the recommended
41
+ * default: structured, typed, and compatible with the entire AI SDK
42
+ * ecosystem.
43
+ *
44
+ * - `"ndjson"` — Raw NDJSON stream of `StreamEvent` objects, one per line.
45
+ * Use this with `@eidentic/react`'s `useEidenticStream`. Choose this when you
46
+ * need access to low-level Eidentic events (tool results, session metadata,
47
+ * cost/usage) that the AI SDK UI protocol does not surface.
48
+ */
49
+ type EidenticProtocol = "ai-sdk-ui" | "ndjson";
50
+ interface WithEidenticOptions {
51
+ /**
52
+ * Stream protocol. Defaults to `"ai-sdk-ui"`.
53
+ *
54
+ * Use `"ai-sdk-ui"` when the frontend uses `useChat` (AI SDK / CopilotKit).
55
+ * Use `"ndjson"` when the frontend uses `@eidentic/react`'s `useEidenticStream`
56
+ * or when you need raw `StreamEvent` access.
57
+ *
58
+ * @default "ai-sdk-ui"
59
+ */
60
+ protocol?: EidenticProtocol;
61
+ /**
62
+ * Extra HTTP headers to include in the streaming response.
63
+ * Forwarded to `toUIMessageStreamResponse` (for `"ai-sdk-ui"` protocol) or
64
+ * set on the raw `Response` (for `"ndjson"` protocol).
65
+ */
66
+ headers?: Headers | Record<string, string>;
67
+ /**
68
+ * Maximum allowed request body size in bytes. Requests with a `Content-Length`
69
+ * header exceeding this limit are rejected with HTTP 413 before the body is
70
+ * parsed. Defaults to 1 MB (1_048_576 bytes).
71
+ *
72
+ * @default 1_048_576
73
+ */
74
+ maxBodyBytes?: number;
75
+ /**
76
+ * Derive the trusted principal identity server-side from the incoming request.
77
+ * When provided, the returned `userId` and `orgId` are used instead of any
78
+ * values supplied in the request body, preventing clients from spoofing their
79
+ * identity.
80
+ *
81
+ * IMPORTANT: This is the recommended way to set `userId` in multi-tenant
82
+ * deployments. Always derive identity from your application's authenticated
83
+ * session (e.g. via cookies, JWT, or a session store), NOT from the request
84
+ * body, which is caller-controlled.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * export const POST = withEidentic(agent, {
89
+ * async identify(req) {
90
+ * const session = await getServerSession(req); // your auth helper
91
+ * return { userId: session.user.id };
92
+ * },
93
+ * });
94
+ * ```
95
+ */
96
+ identify?: (req: Request) => {
97
+ userId?: string;
98
+ orgId?: string;
99
+ } | Promise<{
100
+ userId?: string;
101
+ orgId?: string;
102
+ }>;
103
+ }
104
+ /**
105
+ * Creates a Next.js App Router POST route handler that streams a Eidentic
106
+ * agent's response to the client.
107
+ *
108
+ * **SECURITY NOTICE — this function performs NO authentication or authorization.**
109
+ * It is a low-level convenience wrapper that reads the request body and starts
110
+ * an agent run. In any multi-tenant deployment you MUST:
111
+ *
112
+ * 1. Authenticate the caller BEFORE the handler runs (e.g. via Next.js middleware,
113
+ * or an `identify` option that reads your session cookie / JWT).
114
+ * 2. Derive `userId` and `sessionId` from your application's authenticated session,
115
+ * NOT from the request body (`body.userId` / `body.sessionId` are caller-controlled
116
+ * and can be forged). Use the `identify` option for this.
117
+ * 3. Never expose this handler on a public route without protecting it.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * // app/api/chat/route.ts
122
+ * import { withEidentic } from "@eidentic/nextjs";
123
+ * import { myAgent } from "@/lib/agent";
124
+ *
125
+ * // IMPORTANT: Eidentic requires the Node.js runtime (SQLite, crypto, etc.).
126
+ * // Add this export to every route file that uses withEidentic.
127
+ * export const runtime = "nodejs";
128
+ *
129
+ * // Simple (single-tenant / no auth):
130
+ * export const POST = withEidentic(myAgent);
131
+ *
132
+ * // Multi-tenant — derive userId server-side from the authenticated session:
133
+ * export const POST = withEidentic(myAgent, {
134
+ * async identify(req) {
135
+ * const session = await getServerSession(req); // your auth helper
136
+ * if (!session) throw new Error("Unauthenticated"); // or return 401 yourself
137
+ * return { userId: session.user.id };
138
+ * },
139
+ * });
140
+ * // or with options:
141
+ * // export const POST = withEidentic(myAgent, { protocol: "ndjson" });
142
+ * ```
143
+ *
144
+ * ### Request body (JSON)
145
+ *
146
+ * | Field | Type | Required | Description |
147
+ * |-------------|----------|----------|------------------------------------------|
148
+ * | `input` | `string` | yes* | The user message |
149
+ * | `message` | `string` | yes* | Alias for `input` (useChat default name) |
150
+ * | `sessionId` | `string` | no | Resume an existing session |
151
+ * | `userId` | `string` | no | User ID for memory scoping (see WARNING) |
152
+ *
153
+ * *One of `input` or `message` must be present and non-empty.
154
+ *
155
+ * WARNING: `userId` and `sessionId` in the request body are caller-controlled.
156
+ * Always derive identity server-side via the `identify` option in multi-tenant
157
+ * deployments — do not rely on client-supplied values for access control.
158
+ *
159
+ * ### Protocol: `"ai-sdk-ui"` (default)
160
+ *
161
+ * The response uses the Vercel AI SDK v6 UI message-stream SSE format.
162
+ * Wire it up with `useChat` from `@ai-sdk/react`:
163
+ *
164
+ * ```tsx
165
+ * import { useChat } from "@ai-sdk/react";
166
+ * const { messages, input, handleInputChange, handleSubmit } = useChat({
167
+ * api: "/api/chat",
168
+ * });
169
+ * ```
170
+ *
171
+ * ### Protocol: `"ndjson"`
172
+ *
173
+ * Each line is a JSON-serialised `StreamEvent` followed by `\n`.
174
+ * Content-Type is `application/x-ndjson`.
175
+ * Use `@eidentic/react`'s `useEidenticStream` on the client.
176
+ */
177
+ declare function withEidentic(agent: Agent, opts?: WithEidenticOptions): (req: Request) => Promise<Response>;
178
+ /**
179
+ * Merges Eidentic-required Next.js config onto a user-supplied base config.
180
+ *
181
+ * What it does:
182
+ * - Appends `"better-sqlite3"` to `serverExternalPackages` so the Webpack
183
+ * bundler never tries to bundle the native addon (which would fail).
184
+ *
185
+ * **If you use `@eidentic/libsql` instead of `@eidentic/sqlite`** you don't need
186
+ * this (libsql has no native addon), but it's harmless to include anyway.
187
+ *
188
+ * @example
189
+ * ```ts
190
+ * // next.config.ts
191
+ * import { eidenticNextConfig } from "@eidentic/nextjs";
192
+ * import type { NextConfig } from "next";
193
+ *
194
+ * const baseConfig: NextConfig = {
195
+ * // your existing config here
196
+ * };
197
+ *
198
+ * export default eidenticNextConfig(baseConfig);
199
+ * ```
200
+ */
201
+ declare function eidenticNextConfig(userConfig?: NextConfigShape): NextConfigShape;
202
+ /**
203
+ * Minimal shape of Next.js config that this package touches.
204
+ * Using a loose record type avoids a `next` peer dep at the type level,
205
+ * so the package builds correctly in environments where `next` is only
206
+ * available at runtime.
207
+ */
208
+ interface NextConfigShape {
209
+ serverExternalPackages?: string[];
210
+ [key: string]: unknown;
211
+ }
212
+
213
+ export { type EidenticProtocol, type NextConfigShape, type WithEidenticOptions, eidenticNextConfig, withEidentic };
package/dist/index.js ADDED
@@ -0,0 +1,146 @@
1
+ // src/index.ts
2
+ import {
3
+ toUIMessageStreamResponse
4
+ } from "@eidentic/server";
5
+ function toHeaders(h) {
6
+ if (h instanceof Headers) return h;
7
+ return new Headers(h);
8
+ }
9
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
10
+ function withEidentic(agent, opts = {}) {
11
+ const protocol = opts.protocol ?? "ai-sdk-ui";
12
+ const maxBodyBytes = opts.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
13
+ return async function handler(req) {
14
+ const contentLength = req.headers.get("content-length");
15
+ if (contentLength !== null) {
16
+ const bytes = parseInt(contentLength, 10);
17
+ if (!isNaN(bytes) && bytes > maxBodyBytes) {
18
+ return new Response(
19
+ JSON.stringify({ error: `Request body too large (max ${maxBodyBytes} bytes)` }),
20
+ { status: 413, headers: { "Content-Type": "application/json" } }
21
+ );
22
+ }
23
+ }
24
+ let rawText;
25
+ try {
26
+ const reader = req.body?.getReader();
27
+ if (!reader) {
28
+ rawText = "";
29
+ } else {
30
+ const decoder = new TextDecoder();
31
+ const chunks = [];
32
+ let totalBytes = 0;
33
+ while (true) {
34
+ const { done, value } = await reader.read();
35
+ if (done) break;
36
+ if (value) {
37
+ totalBytes += value.byteLength;
38
+ if (totalBytes > maxBodyBytes) {
39
+ reader.cancel().catch(() => {
40
+ });
41
+ return new Response(
42
+ JSON.stringify({ error: `Request body too large (max ${maxBodyBytes} bytes)` }),
43
+ { status: 413, headers: { "Content-Type": "application/json" } }
44
+ );
45
+ }
46
+ chunks.push(value);
47
+ }
48
+ }
49
+ rawText = decoder.decode(
50
+ chunks.length === 1 ? chunks[0] : chunks.reduce((acc, c) => {
51
+ const merged = new Uint8Array(acc.byteLength + c.byteLength);
52
+ merged.set(acc, 0);
53
+ merged.set(c, acc.byteLength);
54
+ return merged;
55
+ }, new Uint8Array(0))
56
+ );
57
+ }
58
+ } catch {
59
+ return new Response(
60
+ JSON.stringify({ error: "Invalid JSON body" }),
61
+ { status: 400, headers: { "Content-Type": "application/json" } }
62
+ );
63
+ }
64
+ let body;
65
+ try {
66
+ body = JSON.parse(rawText);
67
+ } catch {
68
+ return new Response(
69
+ JSON.stringify({ error: "Invalid JSON body" }),
70
+ { status: 400, headers: { "Content-Type": "application/json" } }
71
+ );
72
+ }
73
+ const input = body.input ?? body.message;
74
+ if (typeof input !== "string" || input.trim() === "") {
75
+ return new Response(
76
+ JSON.stringify({ error: "Missing or invalid 'input' (or 'message') field" }),
77
+ { status: 400, headers: { "Content-Type": "application/json" } }
78
+ );
79
+ }
80
+ const sessionId = typeof body.sessionId === "string" && body.sessionId.length > 0 ? body.sessionId : crypto.randomUUID();
81
+ let userId;
82
+ let orgId;
83
+ if (opts.identify) {
84
+ const principal = await opts.identify(req);
85
+ userId = principal.userId;
86
+ orgId = principal.orgId;
87
+ } else {
88
+ userId = typeof body.userId === "string" && body.userId.length > 0 ? body.userId : void 0;
89
+ }
90
+ const signal = req.signal;
91
+ const events = agent.query(input, { sessionId, userId, orgId, signal });
92
+ if (protocol === "ai-sdk-ui") {
93
+ const streamOpts = {};
94
+ if (opts.headers) {
95
+ streamOpts.headers = toHeaders(opts.headers);
96
+ }
97
+ return toUIMessageStreamResponse(events, streamOpts);
98
+ }
99
+ const extraHeaders = opts.headers ? toHeaders(opts.headers) : new Headers();
100
+ extraHeaders.set("Content-Type", "application/x-ndjson");
101
+ extraHeaders.set("Transfer-Encoding", "chunked");
102
+ const stream = new ReadableStream({
103
+ async start(controller) {
104
+ const encoder = new TextEncoder();
105
+ try {
106
+ for await (const ev of events) {
107
+ if (signal.aborted) break;
108
+ controller.enqueue(encoder.encode(JSON.stringify(ev) + "\n"));
109
+ }
110
+ } catch (err) {
111
+ if (!signal.aborted) {
112
+ const msg = err instanceof Error ? err.message : String(err);
113
+ controller.enqueue(
114
+ encoder.encode(
115
+ JSON.stringify({
116
+ type: "result",
117
+ subtype: "error",
118
+ output: msg,
119
+ usage: { inputTokens: 0, outputTokens: 0 },
120
+ numTurns: 0,
121
+ sessionId
122
+ }) + "\n"
123
+ )
124
+ );
125
+ }
126
+ } finally {
127
+ controller.close();
128
+ }
129
+ }
130
+ });
131
+ return new Response(stream, { headers: extraHeaders });
132
+ };
133
+ }
134
+ function eidenticNextConfig(userConfig = {}) {
135
+ const existing = Array.isArray(userConfig.serverExternalPackages) ? userConfig.serverExternalPackages : [];
136
+ const eidentic = ["better-sqlite3"];
137
+ const merged = [.../* @__PURE__ */ new Set([...existing, ...eidentic])];
138
+ return {
139
+ ...userConfig,
140
+ serverExternalPackages: merged
141
+ };
142
+ }
143
+ export {
144
+ eidenticNextConfig,
145
+ withEidentic
146
+ };
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@eidentic/nextjs",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "license": "Apache-2.0",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/eidentic/eidentic.git",
12
+ "directory": "packages/nextjs"
13
+ },
14
+ "main": "./dist/index.cjs",
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "sideEffects": false,
25
+ "files": [
26
+ "dist",
27
+ "LICENSE",
28
+ "README.md"
29
+ ],
30
+ "dependencies": {
31
+ "@eidentic/core": "0.1.0",
32
+ "@eidentic/server": "0.1.0",
33
+ "@eidentic/types": "0.1.0"
34
+ },
35
+ "peerDependencies": {
36
+ "next": ">=14"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "next": {
40
+ "optional": false
41
+ }
42
+ },
43
+ "description": "Next.js App Router integration for Eidentic — `withEidentic` route helper and `eidenticNextConfig` for native-addon bundling.",
44
+ "keywords": [
45
+ "ai",
46
+ "agents",
47
+ "typescript",
48
+ "eidentic",
49
+ "nextjs",
50
+ "app-router",
51
+ "server-components",
52
+ "streaming"
53
+ ],
54
+ "homepage": "https://github.com/eidentic/eidentic#readme",
55
+ "bugs": {
56
+ "url": "https://github.com/eidentic/eidentic/issues"
57
+ },
58
+ "engines": {
59
+ "node": ">=22"
60
+ },
61
+ "scripts": {
62
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
63
+ "typecheck": "tsc --noEmit"
64
+ }
65
+ }