@sahan-sac/ai-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @sahan-sac/ai-core
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b620f44: First release. ai-core: the free-by-default provider chain (Gemini, OpenRouter, NVIDIA, then paid Vertex) with hedging, cooldowns and deadlines, env-driven model resolution, image generation, prompt guards and the shared env schema (ENABLE_BLOG_AI, ENABLE_CHATBOT). blog-kit: full-post, SEO, draft and cover generation, AI images through an ImageSink port, and pure blog utilities. chat-kit: runChat, guarded prompts, output filtering, the knowledge builder, the ChatStore contract and the visitor rate-limit cookie. Licensed Apache-2.0.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including the
49
+ 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
52
+ owner or by an individual or Legal Entity authorized to submit on
53
+ behalf of the copyright owner. For the purposes of this definition,
54
+ "submitted" means any form of electronic, verbal, or written
55
+ communication sent to the Licensor or its representatives,
56
+ including but not limited to communication on electronic mailing
57
+ lists, source code control systems, and issue tracking systems
58
+ that are managed by, or on behalf of, the Licensor for the purpose
59
+ of discussing and improving the Work, but excluding communication
60
+ that is conspicuously marked or otherwise designated in writing
61
+ by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or Derivative
96
+ Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing
142
+ the origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Sahan Sachintha
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # @sahan-sac/ai-core
2
+
3
+ The AI layer shared by `@sahan-sac/blog-kit` and `@sahan-sac/chat-kit`: a free-by-default provider chain (Gemini, OpenRouter, NVIDIA, then paid Vertex), model resolution from environment variables, image generation (NVIDIA FLUX, then paid Gemini/Vertex), and prompt-injection guards.
4
+
5
+ Headless and framework-agnostic: no Prisma, no Next.js APIs, no React. Everything takes a parsed env or config object; only `aiEnvFromProcess()` reads `process.env`.
6
+
7
+ ## Subpaths
8
+
9
+ | Import | What |
10
+ | --- | --- |
11
+ | `@sahan-sac/ai-core/env` | `aiEnvSchema` (zod), `parseAiEnv(source)`, `aiEnvFromProcess()`, `AiEnv` |
12
+ | `@sahan-sac/ai-core/availability` | `textAiConfigured`, `blogAiEnabled`, `blogAiImagesEnabled`, `chatbotEnabled` |
13
+ | `@sahan-sac/ai-core/providers` | `createAiService` (ordered chain, hedging, cooldowns, deadlines, output validation), `realProviders(env, "blog" \| "chat")`, `sharedAiHealth`, provider factories |
14
+ | `@sahan-sac/ai-core/models` | `textModels`, `imageModels`, verified free defaults, `paidAllowed`, `vertexConfigured` |
15
+ | `@sahan-sac/ai-core/image` | `imageConfigFromEnv`, `generateImage` |
16
+ | `@sahan-sac/ai-core/vertex` | `getVertexAccessToken` (service-account JWT exchange, cached) |
17
+ | `@sahan-sac/ai-core/guard` | `wrapUserData`, `looksLikeLeak`, `ModelPrompt` |
18
+ | `@sahan-sac/ai-core/log` | `AiLogger`, `consoleAiLogger` |
19
+
20
+ `providers`, `image` and `vertex` import `server-only`: use them from server code only.
21
+
22
+ ## Environment
23
+
24
+ Spread the schema into your own env module so the names never drift:
25
+
26
+ ```ts
27
+ import { aiEnvSchema } from "@sahan-sac/ai-core/env";
28
+
29
+ const schema = z.object({ ...aiEnvSchema.shape, DATABASE_URL: z.string() });
30
+ ```
31
+
32
+ | Variable | Default | Meaning |
33
+ | --- | --- | --- |
34
+ | `ENABLE_BLOG_AI` | `false` | Blog AI assistant (also needs a text provider key) |
35
+ | `ENABLE_CHATBOT` | `true` | Chatbot (also needs a text provider key); `false`/`0`/`no`/`off` turns it off |
36
+ | `AI_ALLOW_PAID` | `false` | Lets paid providers (Vertex text and images, Gemini images) join the chains |
37
+ | `GEMINI_API_KEY`, `OPENROUTER_API_KEY`, `OPENROUTER_API_KEY_2`, `NVIDIA_API_KEY` | unset | Free text providers; `NVIDIA_API_KEY` is also the free image provider |
38
+ | `OPENROUTER_BASE_URL`, `OPENROUTER_ALLOW_PAID_MODELS` | OpenRouter API, `false` | OpenRouter settings |
39
+ | `GOOGLE_CLIENT_EMAIL`, `GOOGLE_PRIVATE_KEY`, `GOOGLE_CLOUD_PROJECT` | unset | Vertex service account (paid). Keep the key on one line with literal `\n` |
40
+ | `GOOGLE_TOKEN_URI` | Google's token endpoint | Override only for testing |
41
+ | `BLOG_*_MODEL`, `CHAT_*_MODEL`, `IMAGE_*_MODEL`, `*_MODEL`, `IMAGEN_MODEL` | verified free defaults | Model overrides: purpose variable, then provider-wide, then default |
42
+
43
+ ## Example
44
+
45
+ ```ts
46
+ import { chatbotEnabled } from "@sahan-sac/ai-core/availability";
47
+ import { aiEnvFromProcess } from "@sahan-sac/ai-core/env";
48
+ import { createAiService, realProviders, sharedAiHealth } from "@sahan-sac/ai-core/providers";
49
+
50
+ const env = aiEnvFromProcess();
51
+ if (chatbotEnabled(env)) {
52
+ const ai = createAiService({ providers: realProviders(env, "chat"), health: sharedAiHealth, timeoutMs: 12_000, deadlineMs: 20_000 });
53
+ const result = await ai.generate({ system: "You are helpful.", user: "Hello" }, { maxTokens: 200 });
54
+ }
55
+ ```
@@ -0,0 +1,13 @@
1
+ import { AiEnv } from './env.js';
2
+ import 'zod';
3
+
4
+ /** At least one text provider can answer: a free key, or Vertex with AI_ALLOW_PAID. */
5
+ declare function textAiConfigured(env: AiEnv): boolean;
6
+ /** The blog AI assistant: ENABLE_BLOG_AI=true (off by default) and a text provider. */
7
+ declare function blogAiEnabled(env: AiEnv): boolean;
8
+ /** Blog AI images (featured and inline): blog AI plus at least one image provider. */
9
+ declare function blogAiImagesEnabled(env: AiEnv): boolean;
10
+ /** The chatbot: ENABLE_CHATBOT (on unless set to false) and a text provider. */
11
+ declare function chatbotEnabled(env: AiEnv): boolean;
12
+
13
+ export { blogAiEnabled, blogAiImagesEnabled, chatbotEnabled, textAiConfigured };
@@ -0,0 +1,64 @@
1
+ // src/image.ts
2
+ import "server-only";
3
+
4
+ // src/models.ts
5
+ var DEFAULT_IMAGE_MODELS = {
6
+ nvidia: "black-forest-labs/flux.1-dev",
7
+ gemini: "gemini-3.1-flash-image",
8
+ vertex: "gemini-3.1-flash-image"
9
+ };
10
+ var pick = (...values) => values.find((value) => value && value.trim()).trim();
11
+ function imageModels(env) {
12
+ return {
13
+ nvidia: pick(env.IMAGE_NVIDIA_MODEL, DEFAULT_IMAGE_MODELS.nvidia),
14
+ gemini: pick(env.IMAGE_GEMINI_MODEL, DEFAULT_IMAGE_MODELS.gemini),
15
+ vertex: pick(env.IMAGE_VERTEX_MODEL, env.IMAGEN_MODEL, DEFAULT_IMAGE_MODELS.vertex)
16
+ };
17
+ }
18
+ var paidAllowed = (env) => env.AI_ALLOW_PAID === true;
19
+ function vertexConfigured(env) {
20
+ return Boolean(env.GOOGLE_CLIENT_EMAIL && env.GOOGLE_PRIVATE_KEY && env.GOOGLE_CLOUD_PROJECT);
21
+ }
22
+
23
+ // src/image.ts
24
+ function vertexImageAvailable(env) {
25
+ return vertexConfigured(env);
26
+ }
27
+ function imageConfigFromEnv(env) {
28
+ const models = imageModels(env);
29
+ const paid = paidAllowed(env);
30
+ const config = {};
31
+ if (env.NVIDIA_API_KEY) config.nvidia = { apiKey: env.NVIDIA_API_KEY, model: models.nvidia };
32
+ if (paid && env.GEMINI_API_KEY) config.gemini = { apiKey: env.GEMINI_API_KEY, model: models.gemini };
33
+ if (paid && vertexImageAvailable(env)) {
34
+ config.vertex = {
35
+ clientEmail: env.GOOGLE_CLIENT_EMAIL,
36
+ privateKey: env.GOOGLE_PRIVATE_KEY,
37
+ tokenUri: env.GOOGLE_TOKEN_URI,
38
+ project: env.GOOGLE_CLOUD_PROJECT,
39
+ model: models.vertex
40
+ };
41
+ }
42
+ return config.nvidia || config.gemini || config.vertex ? config : null;
43
+ }
44
+
45
+ // src/availability.ts
46
+ function textAiConfigured(env) {
47
+ if (env.GEMINI_API_KEY || env.OPENROUTER_API_KEY || env.OPENROUTER_API_KEY_2 || env.NVIDIA_API_KEY) return true;
48
+ return paidAllowed(env) && vertexConfigured(env);
49
+ }
50
+ function blogAiEnabled(env) {
51
+ return env.ENABLE_BLOG_AI && textAiConfigured(env);
52
+ }
53
+ function blogAiImagesEnabled(env) {
54
+ return blogAiEnabled(env) && imageConfigFromEnv(env) !== null;
55
+ }
56
+ function chatbotEnabled(env) {
57
+ return env.ENABLE_CHATBOT && textAiConfigured(env);
58
+ }
59
+ export {
60
+ blogAiEnabled,
61
+ blogAiImagesEnabled,
62
+ chatbotEnabled,
63
+ textAiConfigured
64
+ };
package/dist/env.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod';
2
+
3
+ declare const DEFAULT_GOOGLE_TOKEN_URI = "https://oauth2.googleapis.com/token";
4
+ declare const aiEnvSchema: z.ZodObject<{
5
+ AI_ALLOW_PAID: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<boolean, string | undefined>>;
6
+ ENABLE_BLOG_AI: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<boolean, string | undefined>>;
7
+ ENABLE_CHATBOT: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<boolean, string | undefined>>;
8
+ OPENROUTER_BASE_URL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
9
+ OPENROUTER_API_KEY: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
10
+ OPENROUTER_API_KEY_2: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
11
+ OPENROUTER_ALLOW_PAID_MODELS: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<boolean, string | undefined>>;
12
+ GEMINI_API_KEY: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
13
+ NVIDIA_API_KEY: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
14
+ OPENROUTER_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
15
+ GEMINI_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
16
+ NVIDIA_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
17
+ VERTEX_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
18
+ IMAGEN_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
19
+ BLOG_GEMINI_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
20
+ BLOG_OPENROUTER_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
21
+ BLOG_NVIDIA_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
22
+ BLOG_VERTEX_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
23
+ CHAT_GEMINI_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
24
+ CHAT_OPENROUTER_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
25
+ CHAT_NVIDIA_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
26
+ CHAT_VERTEX_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
27
+ IMAGE_NVIDIA_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
28
+ IMAGE_GEMINI_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
29
+ IMAGE_VERTEX_MODEL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
30
+ GOOGLE_CLIENT_EMAIL: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
31
+ GOOGLE_PRIVATE_KEY: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>, z.ZodTransform<string | undefined, string | undefined>>;
32
+ GOOGLE_CLOUD_PROJECT: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
33
+ GOOGLE_TOKEN_URI: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>, z.ZodTransform<string, string | undefined>>;
34
+ }, z.core.$strip>;
35
+ type AiEnv = z.infer<typeof aiEnvSchema>;
36
+ type EnvSource = Record<string, string | undefined>;
37
+ /** Parses the AI variables; throws naming the bad variables, never their values. */
38
+ declare function parseAiEnv(source: EnvSource): AiEnv;
39
+ /** Convenience for apps without their own env module: reads process.env. */
40
+ declare function aiEnvFromProcess(): AiEnv;
41
+
42
+ export { type AiEnv, DEFAULT_GOOGLE_TOKEN_URI, type EnvSource, aiEnvFromProcess, aiEnvSchema, parseAiEnv };
package/dist/env.js ADDED
@@ -0,0 +1,69 @@
1
+ // src/env.ts
2
+ import { z } from "zod";
3
+ var text = z.string().optional().transform((value) => {
4
+ const trimmed = value?.trim();
5
+ return trimmed ? trimmed : void 0;
6
+ });
7
+ var ON = ["1", "true", "yes", "on"];
8
+ var flag = z.string().optional().transform((value) => ON.includes((value ?? "").trim().toLowerCase()));
9
+ var flagDefaultOn = z.string().optional().transform((value) => {
10
+ const normalized = (value ?? "").trim().toLowerCase();
11
+ return normalized === "" || ON.includes(normalized);
12
+ });
13
+ var privateKey = text.transform((value) => value?.replace(/\\n/g, "\n"));
14
+ var DEFAULT_GOOGLE_TOKEN_URI = "https://oauth2.googleapis.com/token";
15
+ var aiEnvSchema = z.object({
16
+ // Paid providers (Vertex text and images, Gemini images) join the chains
17
+ // only with AI_ALLOW_PAID; off by default, so AI costs $0.
18
+ AI_ALLOW_PAID: flag,
19
+ // Feature switches. The blog assistant is off until turned on; the chatbot
20
+ // is on unless turned off. Each also needs a text provider key.
21
+ ENABLE_BLOG_AI: flag,
22
+ ENABLE_CHATBOT: flagDefaultOn,
23
+ OPENROUTER_BASE_URL: text,
24
+ OPENROUTER_API_KEY: text,
25
+ OPENROUTER_API_KEY_2: text,
26
+ OPENROUTER_ALLOW_PAID_MODELS: flag,
27
+ GEMINI_API_KEY: text,
28
+ NVIDIA_API_KEY: text,
29
+ // Model overrides, all optional (models.ts): purpose variable, then the
30
+ // provider-wide *_MODEL, then a verified free default.
31
+ OPENROUTER_MODEL: text,
32
+ GEMINI_MODEL: text,
33
+ NVIDIA_MODEL: text,
34
+ VERTEX_MODEL: text,
35
+ IMAGEN_MODEL: text,
36
+ BLOG_GEMINI_MODEL: text,
37
+ BLOG_OPENROUTER_MODEL: text,
38
+ BLOG_NVIDIA_MODEL: text,
39
+ BLOG_VERTEX_MODEL: text,
40
+ CHAT_GEMINI_MODEL: text,
41
+ CHAT_OPENROUTER_MODEL: text,
42
+ CHAT_NVIDIA_MODEL: text,
43
+ CHAT_VERTEX_MODEL: text,
44
+ IMAGE_NVIDIA_MODEL: text,
45
+ IMAGE_GEMINI_MODEL: text,
46
+ IMAGE_VERTEX_MODEL: text,
47
+ // Google Vertex service account (paid).
48
+ GOOGLE_CLIENT_EMAIL: text,
49
+ GOOGLE_PRIVATE_KEY: privateKey,
50
+ GOOGLE_CLOUD_PROJECT: text,
51
+ GOOGLE_TOKEN_URI: text.transform((value) => value ?? DEFAULT_GOOGLE_TOKEN_URI)
52
+ });
53
+ function parseAiEnv(source) {
54
+ const result = aiEnvSchema.safeParse(source);
55
+ if (!result.success) {
56
+ const names = [...new Set(result.error.issues.map((issue) => String(issue.path[0] ?? "?")))];
57
+ throw new Error(`Invalid AI environment variables: ${names.join(", ")}`);
58
+ }
59
+ return result.data;
60
+ }
61
+ function aiEnvFromProcess() {
62
+ return parseAiEnv(process.env);
63
+ }
64
+ export {
65
+ DEFAULT_GOOGLE_TOKEN_URI,
66
+ aiEnvFromProcess,
67
+ aiEnvSchema,
68
+ parseAiEnv
69
+ };
@@ -0,0 +1,18 @@
1
+ declare const DATA_START = "<<<SAHAN_USER_DATA_START>>>";
2
+ declare const DATA_END = "<<<SAHAN_USER_DATA_END>>>";
3
+ /** Strips control characters, caps length, and neutralizes any attempt to
4
+ * forge the delimiter markers themselves before fencing the text as data. */
5
+ declare function wrapUserData(text: string): string;
6
+ interface ModelPrompt {
7
+ system: string;
8
+ user: string;
9
+ }
10
+ /**
11
+ * A conservative output check: refuses a model reply that looks like it is
12
+ * echoing back these very instructions or a secret-shaped token, rather than
13
+ * writing about the topic. Defense in depth only — the system prompt above
14
+ * is what actually prevents this.
15
+ */
16
+ declare function looksLikeLeak(text: string): boolean;
17
+
18
+ export { DATA_END, DATA_START, type ModelPrompt, looksLikeLeak, wrapUserData };
package/dist/guard.js ADDED
Binary file
@@ -0,0 +1,71 @@
1
+ import { AiEnv } from './env.js';
2
+ import 'zod';
3
+
4
+ interface VertexImageConfig {
5
+ clientEmail: string;
6
+ privateKey: string;
7
+ tokenUri: string;
8
+ project: string;
9
+ /** Tried before the defaults. An `imagen-*` model uses the :predict API; anything else uses Gemini's generateContent. */
10
+ model?: string;
11
+ /** Region for `model`; defaults to "global" for Gemini 3.x models, else us-central1. */
12
+ location?: string;
13
+ }
14
+ type ImageOutcome = {
15
+ ok: true;
16
+ base64: string;
17
+ mimeType: string;
18
+ } | {
19
+ ok: false;
20
+ error: string;
21
+ };
22
+ type AspectRatio = "1:1" | "16:9" | "4:3";
23
+ interface ImageModel {
24
+ model: string;
25
+ location: string;
26
+ }
27
+ declare const DEFAULT_IMAGE_MODELS: readonly ImageModel[];
28
+ /** The configured model first (if any), then the defaults, without duplicates. */
29
+ declare function imageModelChain(config: Pick<VertexImageConfig, "model" | "location">): ImageModel[];
30
+ /** The first image in either response shape: Imagen `predictions[]` or Gemini `candidates[].content.parts[].inlineData`. */
31
+ declare function extractImage(data: unknown): {
32
+ base64: string;
33
+ mimeType: string;
34
+ } | null;
35
+ declare function generateImageVertex(prompt: string, config: VertexImageConfig, options?: {
36
+ aspectRatio?: AspectRatio;
37
+ signal?: AbortSignal;
38
+ fetchImpl?: typeof fetch;
39
+ }): Promise<ImageOutcome>;
40
+ /** True when the Vertex service account needed for Vertex image generation is configured. */
41
+ declare function vertexImageAvailable(env: AiEnv): boolean;
42
+ /** The request body for an NVIDIA genai image model: FLUX.1-dev settings, fewer steps for schnell. */
43
+ declare function nvidiaImageRequest(model: string, prompt: string, aspectRatio: AspectRatio, seed: number): Record<string, unknown>;
44
+ /** The image in an NVIDIA genai reply (`artifacts[0].base64`), with its type sniffed from the bytes. */
45
+ declare function extractNvidiaImage(data: unknown): {
46
+ base64: string;
47
+ mimeType: string;
48
+ } | null;
49
+ type ProviderOptions = {
50
+ signal?: AbortSignal;
51
+ fetchImpl?: typeof fetch;
52
+ };
53
+ interface ImageConfig {
54
+ nvidia?: {
55
+ apiKey: string;
56
+ model: string;
57
+ };
58
+ gemini?: {
59
+ apiKey: string;
60
+ model: string;
61
+ };
62
+ vertex?: VertexImageConfig;
63
+ }
64
+ /** The configured image providers, free first; null when there is none. Paid ones only with AI_ALLOW_PAID. */
65
+ declare function imageConfigFromEnv(env: AiEnv): ImageConfig | null;
66
+ /** Tries NVIDIA, then Gemini, then Vertex (whichever are configured) until one returns an image. */
67
+ declare function generateImage(prompt: string, config: ImageConfig, options?: {
68
+ aspectRatio?: AspectRatio;
69
+ } & ProviderOptions): Promise<ImageOutcome>;
70
+
71
+ export { type AspectRatio, DEFAULT_IMAGE_MODELS, type ImageConfig, type ImageOutcome, type VertexImageConfig, extractImage, extractNvidiaImage, generateImage, generateImageVertex, imageConfigFromEnv, imageModelChain, nvidiaImageRequest, vertexImageAvailable };