@lenne.tech/nest-server 12.9.4 → 12.10.1

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.
Files changed (152) hide show
  1. package/.claude/rules/configurable-features.md +5 -1
  2. package/.claude/rules/package-management.md +38 -12
  3. package/.claude/rules/role-system.md +12 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/CLAUDE.md +10 -1
  6. package/FRAMEWORK-API.md +2 -1
  7. package/dist/core/common/decorators/rest-user.decorator.js +4 -0
  8. package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
  9. package/dist/core/common/filters/http-exception-log.filter.js +3 -0
  10. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  11. package/dist/core/common/helpers/context.helper.js +9 -0
  12. package/dist/core/common/helpers/context.helper.js.map +1 -1
  13. package/dist/core/common/helpers/decorator.helper.js +4 -0
  14. package/dist/core/common/helpers/decorator.helper.js.map +1 -1
  15. package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
  16. package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
  17. package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
  18. package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +237 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
  22. package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
  23. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  24. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  25. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  26. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  27. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  28. package/dist/core/common/plugins/complexity.plugin.js +73 -9
  29. package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
  30. package/dist/core/common/services/request-context.service.d.ts +2 -0
  31. package/dist/core/common/services/request-context.service.js +3 -0
  32. package/dist/core/common/services/request-context.service.js.map +1 -1
  33. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  34. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  35. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  36. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  37. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  38. package/dist/core/modules/ai/core-ai.module.js +2 -0
  39. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  40. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  41. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  42. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  43. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  44. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  45. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  46. package/dist/core/modules/ai/index.d.ts +8 -0
  47. package/dist/core/modules/ai/index.js +8 -0
  48. package/dist/core/modules/ai/index.js.map +1 -1
  49. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  50. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  51. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  52. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  53. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  54. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  57. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  58. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  59. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  60. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  61. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  62. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  63. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  64. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  65. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  66. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  67. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  68. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  69. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  70. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  71. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  72. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  73. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  74. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  75. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  76. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  77. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  78. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  79. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  80. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  81. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  82. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  83. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  84. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  85. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  86. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  87. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  88. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  89. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  90. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  91. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  92. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  93. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  94. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  95. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  96. package/dist/core.module.js +2 -1
  97. package/dist/core.module.js.map +1 -1
  98. package/dist/index.d.ts +1 -0
  99. package/dist/index.js +1 -0
  100. package/dist/index.js.map +1 -1
  101. package/dist/types/graphql-upload.d.ts +34 -2
  102. package/docs/REQUEST-LIFECYCLE.md +59 -10
  103. package/migration-guides/12.10.0-to-12.10.1.md +182 -0
  104. package/migration-guides/12.9.3-to-12.9.4.md +3 -1
  105. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  106. package/package.json +46 -21
  107. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  108. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  109. package/src/core/common/helpers/context.helper.ts +14 -0
  110. package/src/core/common/helpers/decorator.helper.ts +5 -0
  111. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  112. package/src/core/common/helpers/graphql-upload.helper.ts +520 -0
  113. package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
  114. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  115. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  116. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  117. package/src/core/common/plugins/complexity.plugin.ts +150 -9
  118. package/src/core/common/services/request-context.service.ts +11 -0
  119. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  120. package/src/core/modules/ai/README.md +101 -0
  121. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  122. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  123. package/src/core/modules/ai/core-ai.module.ts +3 -0
  124. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  125. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  126. package/src/core/modules/ai/index.ts +8 -0
  127. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  128. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  129. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  130. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  131. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  132. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  133. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  134. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  135. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  136. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  137. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  138. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  139. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  140. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  141. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  142. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  143. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  144. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  145. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  146. package/src/core/modules/better-auth/README.md +204 -0
  147. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  148. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  149. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  150. package/src/core.module.ts +5 -1
  151. package/src/index.ts +1 -0
  152. package/src/types/graphql-upload.d.ts +34 -2
@@ -0,0 +1,383 @@
1
+ import { BadGatewayException, Logger, ServiceUnavailableException } from '@nestjs/common';
2
+ import type { LanguageModel } from 'ai';
3
+
4
+ import { outboundFetch } from '../../../common/helpers/outbound-url.helper.js';
5
+ import { ErrorCode } from '../../error-code/index.js';
6
+ import {
7
+ ILlmProvider,
8
+ LlmAttachment,
9
+ LlmCapabilities,
10
+ LlmCompletionOptions,
11
+ LlmMessage,
12
+ LlmResponse,
13
+ LlmToolCall,
14
+ LlmToolSchema,
15
+ LlmUsage,
16
+ } from '../interfaces/llm-provider.interface.js';
17
+ import { ResolvedAiConnection } from '../interfaces/resolved-ai-connection.interface.js';
18
+ import { AiSdkPackageError, loadAiSdk, loadNestjsResilience } from './ai-sdk.packages.js';
19
+
20
+ /** Upper bound for an attachment the transport downloads itself (a model that cannot read the URL). */
21
+ export const AI_SDK_MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
22
+
23
+ /** Upper bound for all attachments one model call downloads together. */
24
+ export const AI_SDK_MAX_ATTACHMENT_BYTES_PER_CALL = 50 * 1024 * 1024;
25
+
26
+ /** Upper bound for the number of attachments one model call downloads. */
27
+ export const AI_SDK_MAX_ATTACHMENT_DOWNLOADS = 10;
28
+
29
+ /** What {@link readBodyWithLimit} reads: a web `ReadableStream` of bytes — the global one or undici's. */
30
+ export interface ByteStreamLike {
31
+ getReader(): {
32
+ cancel(reason?: unknown): Promise<void>;
33
+ read(): Promise<{ done: boolean; value?: Uint8Array }>;
34
+ releaseLock(): void;
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Reads a response body chunk by chunk and stops — cancelling the stream — as soon as it passes `limit` bytes or the
40
+ * call's shared `budget` runs out. Never trusts `Content-Length`: a chunked body has none, and a compressed one declares
41
+ * the compressed size while `fetch` hands out the decompressed bytes. `arrayBuffer()` would hold all of it before any
42
+ * check could run.
43
+ */
44
+ export async function readBodyWithLimit(
45
+ body: ByteStreamLike | null | undefined,
46
+ limit: number,
47
+ budget: { remaining: number } = { remaining: Number.POSITIVE_INFINITY },
48
+ ): Promise<Uint8Array> {
49
+ if (!body) {
50
+ return new Uint8Array();
51
+ }
52
+ const reader = body.getReader();
53
+ const chunks: Uint8Array[] = [];
54
+ let total = 0;
55
+ try {
56
+ for (;;) {
57
+ const { done, value } = await reader.read();
58
+ if (done || !value) {
59
+ break;
60
+ }
61
+ total += value.byteLength;
62
+ budget.remaining -= value.byteLength;
63
+ if (total > limit || budget.remaining < 0) {
64
+ await reader.cancel().catch(() => undefined);
65
+ throw new BadGatewayException('Attachment too large');
66
+ }
67
+ chunks.push(value);
68
+ }
69
+ } finally {
70
+ reader.releaseLock();
71
+ }
72
+ const data = new Uint8Array(total);
73
+ let offset = 0;
74
+ for (const chunk of chunks) {
75
+ data.set(chunk, offset);
76
+ offset += chunk.byteLength;
77
+ }
78
+ return data;
79
+ }
80
+
81
+ /**
82
+ * How an {@link AiSdkProvider} gets its model and runs a call.
83
+ */
84
+ export interface AiSdkProviderOptions {
85
+ /** Resolves the AI SDK `LanguageModel` — once per provider instance, on the first call. */
86
+ model: () => LanguageModel | Promise<LanguageModel>;
87
+ /**
88
+ * `'nestjs'`: retries and timeout through `@nestjs/resilience` (connections of `providerType: 'nestjs-ai'`, whose
89
+ * project installed it with `@nestjs/ai`). `'sdk'` (default): the AI SDK's own retries and a timeout signal — a project
90
+ * that registered a model builder may have installed nothing but `ai` and a provider package.
91
+ */
92
+ resilience?: 'nestjs' | 'sdk';
93
+ }
94
+
95
+ /**
96
+ * {@link ILlmProvider} over an AI SDK `LanguageModel` (nestjs-ai plan §2): any provider the AI SDK supports
97
+ * (`@ai-sdk/anthropic`, `@ai-sdk/openai`, …) and every model registered in `@nestjs/ai`'s `AiModule.forRoot({ models })`.
98
+ *
99
+ * SECURITY: native tools are handed to the model WITHOUT `execute` — the AI SDK returns the model's tool calls and stops
100
+ * after one step, and `CoreAiService` runs them through its own gates (role filter, tool policies and grants,
101
+ * `authorize()`, confirmation, plan mode, budgets). Nothing here executes a tool.
102
+ *
103
+ * Attachments: an attachment URL the model cannot read itself is downloaded by the transport — through
104
+ * `outboundFetch()`, the SSRF guard for user-entered URLs, never the AI SDK's own unguarded download — streamed, at most
105
+ * {@link AI_SDK_MAX_ATTACHMENT_DOWNLOADS} per call, {@link AI_SDK_MAX_ATTACHMENT_BYTES} each and
106
+ * {@link AI_SDK_MAX_ATTACHMENT_BYTES_PER_CALL} together. Usage feeds the budget and audit like the built-in provider's.
107
+ */
108
+ export class AiSdkProvider implements ILlmProvider {
109
+ readonly capabilities: LlmCapabilities;
110
+ readonly name: string;
111
+
112
+ protected readonly logger = new Logger(AiSdkProvider.name);
113
+ protected modelPromise?: Promise<LanguageModel>;
114
+
115
+ constructor(
116
+ protected readonly connection: ResolvedAiConnection,
117
+ protected readonly options: AiSdkProviderOptions,
118
+ ) {
119
+ this.name = `ai-sdk:${connection.providerType}`;
120
+ this.capabilities = {
121
+ jsonResponse: connection.supportsJsonResponse === true,
122
+ // AI SDK providers speak native tool calling; a connection can still opt out explicitly
123
+ nativeTools: connection.supportsNativeTools !== false,
124
+ systemPrompt: true,
125
+ };
126
+ }
127
+
128
+ async chat(messages: LlmMessage[], tools: LlmToolSchema[], options?: LlmCompletionOptions): Promise<LlmResponse> {
129
+ const sdk = await loadAiSdk(
130
+ `The AI connection "${this.connection.name}" (providerType "${this.connection.providerType}")`,
131
+ );
132
+ const model = await this.resolveModel();
133
+ const timeoutMs = options?.timeoutMs ?? this.connection.timeoutMs ?? 120_000;
134
+ const request = this.buildRequest(sdk, model, messages, tools, options);
135
+
136
+ let result: any;
137
+ try {
138
+ result = await this.run((signal) => sdk.generateText({ ...request, abortSignal: signal }), timeoutMs, options);
139
+ } catch (error) {
140
+ throw this.toTransportError(error);
141
+ }
142
+ return this.mapResult(result);
143
+ }
144
+
145
+ /**
146
+ * The options of one `generateText()` call. Native tools carry a description and a JSON schema — and never an
147
+ * `execute`: without one the AI SDK returns the model's tool calls instead of running them, so every gate of
148
+ * `CoreAiService` stays in charge. An override must keep it that way.
149
+ */
150
+ protected buildRequest(
151
+ sdk: any,
152
+ model: LanguageModel,
153
+ messages: LlmMessage[],
154
+ tools: LlmToolSchema[],
155
+ options?: LlmCompletionOptions,
156
+ ): Record<string, any> {
157
+ const request: Record<string, any> = {
158
+ experimental_download: (
159
+ requests: Array<{ abortSignal?: AbortSignal; isUrlSupportedByModel: boolean; url: URL }>,
160
+ ) => this.downloadAttachments(requests),
161
+ maxOutputTokens: options?.maxTokens ?? this.connection.defaultMaxTokens ?? 2048,
162
+ // Retries are this transport's (see run()), never a second layer inside the SDK on top of them
163
+ maxRetries: this.options.resilience === 'nestjs' ? 0 : 2,
164
+ messages: this.mapMessages(messages),
165
+ model,
166
+ temperature: options?.temperature ?? this.connection.defaultTemperature ?? 0.1,
167
+ };
168
+ const instructions = messages
169
+ .filter((message) => message.role === 'system')
170
+ .map((message) => message.content)
171
+ .filter(Boolean)
172
+ .join('\n\n');
173
+ if (instructions) {
174
+ request.instructions = instructions;
175
+ }
176
+ if (this.capabilities.nativeTools && tools.length) {
177
+ request.tools = Object.fromEntries(
178
+ tools.map((tool) => [
179
+ tool.name,
180
+ { description: tool.description, inputSchema: sdk.jsonSchema(tool.parameters ?? { type: 'object' }) },
181
+ ]),
182
+ );
183
+ }
184
+ if (this.capabilities.jsonResponse && options?.jsonResponse !== false && !request.tools && sdk.Output?.json) {
185
+ request.output = sdk.Output.json();
186
+ }
187
+ return request;
188
+ }
189
+
190
+ /** The model, resolved once. A failure is not kept: the next call tries again. */
191
+ protected resolveModel(): Promise<LanguageModel> {
192
+ if (!this.modelPromise) {
193
+ this.modelPromise = Promise.resolve()
194
+ .then(() => this.options.model())
195
+ .then((model) => {
196
+ if (!model) {
197
+ throw new AiSdkPackageError(
198
+ `The AI connection "${this.connection.name}" resolved no AI SDK model for "${this.connection.model}".`,
199
+ );
200
+ }
201
+ return model;
202
+ });
203
+ this.modelPromise.catch(() => (this.modelPromise = undefined));
204
+ }
205
+ return this.modelPromise;
206
+ }
207
+
208
+ /**
209
+ * One model call with retries and a timeout per attempt. `'nestjs'` wraps it in `@nestjs/resilience` policies (three
210
+ * attempts on what the provider marks retryable, then the timeout); `'sdk'` lets the AI SDK retry (`maxRetries: 2`)
211
+ * under one timeout signal.
212
+ */
213
+ protected async run<T>(
214
+ call: (signal: AbortSignal) => Promise<T>,
215
+ timeoutMs: number,
216
+ options?: LlmCompletionOptions,
217
+ ): Promise<T> {
218
+ const callerSignal = options?.abortSignal;
219
+ if (this.options.resilience === 'nestjs') {
220
+ const resilience = await loadNestjsResilience(
221
+ `The AI connection "${this.connection.name}" (providerType "nestjs-ai")`,
222
+ );
223
+ const policy = resilience.ResiliencePolicy.wrap(
224
+ new resilience.RetryPolicy({ attempts: 3, retryIf: (error: unknown) => isRetryableModelError(error) }),
225
+ new resilience.TimeoutPolicy(timeoutMs),
226
+ );
227
+ return policy.execute(
228
+ ({ signal }: { signal: AbortSignal }) => call(signal),
229
+ callerSignal ? { signal: callerSignal } : undefined,
230
+ );
231
+ }
232
+ const timeout = AbortSignal.timeout(timeoutMs);
233
+ const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout;
234
+ return call(signal);
235
+ }
236
+
237
+ /**
238
+ * Our messages as AI SDK model messages. System messages travel as `instructions`; the emulated `tool` role becomes a
239
+ * user message (as on the OpenAI-compatible provider) — the loop carries tool results as text, not as SDK tool-result
240
+ * parts tied to an id.
241
+ */
242
+ protected mapMessages(messages: LlmMessage[]): Array<Record<string, any>> {
243
+ return messages
244
+ .filter((message) => message.role !== 'system')
245
+ .map((message) => {
246
+ if (message.role === 'assistant') {
247
+ return { content: message.content ?? '', role: 'assistant' };
248
+ }
249
+ const attachments = (message.attachments ?? []).map((attachment) => this.mapAttachment(attachment));
250
+ const parts = attachments.filter(Boolean);
251
+ if (!parts.length) {
252
+ return { content: message.content ?? '', role: 'user' };
253
+ }
254
+ return {
255
+ content: [...(message.content ? [{ text: message.content, type: 'text' }] : []), ...parts],
256
+ role: 'user',
257
+ };
258
+ });
259
+ }
260
+
261
+ /** An attachment as an image or file part; `undefined` when it carries neither a URL nor a data URL. */
262
+ protected mapAttachment(attachment: LlmAttachment): Record<string, any> | undefined {
263
+ const mediaType = attachment.mimeType || 'application/octet-stream';
264
+ let data: string | URL | undefined;
265
+ if (attachment.dataUrl?.startsWith('data:')) {
266
+ const comma = attachment.dataUrl.indexOf(',');
267
+ data = comma > 0 ? attachment.dataUrl.slice(comma + 1) : undefined;
268
+ } else if (attachment.url) {
269
+ try {
270
+ data = new URL(attachment.url);
271
+ } catch {
272
+ data = undefined;
273
+ }
274
+ }
275
+ if (!data) {
276
+ return undefined;
277
+ }
278
+ return mediaType.startsWith('image/')
279
+ ? { image: data, mediaType, type: 'image' }
280
+ : { data, filename: attachment.name, mediaType, type: 'file' };
281
+ }
282
+
283
+ /**
284
+ * The AI SDK's download hook: a URL the model reads itself is left to the provider (`null`); every other one is
285
+ * fetched through `outboundFetch()` — private and internal addresses refused, every redirect hop checked — and capped
286
+ * at {@link AI_SDK_MAX_ATTACHMENT_BYTES}.
287
+ */
288
+ protected async downloadAttachments(
289
+ requests: Array<{ abortSignal?: AbortSignal; isUrlSupportedByModel: boolean; url: URL }>,
290
+ ): Promise<Array<null | { data: Uint8Array; mediaType: string | undefined }>> {
291
+ const downloads = requests.filter((request) => !request.isUrlSupportedByModel);
292
+ if (downloads.length > AI_SDK_MAX_ATTACHMENT_DOWNLOADS) {
293
+ throw new BadGatewayException(
294
+ `Too many attachments to download (${downloads.length}, at most ${AI_SDK_MAX_ATTACHMENT_DOWNLOADS})`,
295
+ );
296
+ }
297
+ // One byte budget for the whole call, shared by the parallel downloads
298
+ const budget = { remaining: AI_SDK_MAX_ATTACHMENT_BYTES_PER_CALL };
299
+ return Promise.all(
300
+ requests.map(async ({ abortSignal, isUrlSupportedByModel, url }) => {
301
+ if (isUrlSupportedByModel) {
302
+ return null;
303
+ }
304
+ const response = await outboundFetch(url.toString(), abortSignal ? { signal: abortSignal } : {});
305
+ if (!response.ok) {
306
+ await response.body?.cancel().catch(() => undefined);
307
+ throw new BadGatewayException(`Attachment download failed with HTTP ${response.status}`);
308
+ }
309
+ const declared = Number(response.headers.get('content-length'));
310
+ if (Number.isFinite(declared) && declared > AI_SDK_MAX_ATTACHMENT_BYTES) {
311
+ await response.body?.cancel().catch(() => undefined);
312
+ throw new BadGatewayException('Attachment too large');
313
+ }
314
+ const data = await readBodyWithLimit(response.body, AI_SDK_MAX_ATTACHMENT_BYTES, budget);
315
+ return { data, mediaType: response.headers.get('content-type') ?? undefined };
316
+ }),
317
+ );
318
+ }
319
+
320
+ /** The AI SDK result as our {@link LlmResponse}. */
321
+ protected mapResult(result: any): LlmResponse {
322
+ const toolCalls: LlmToolCall[] = (result?.toolCalls ?? [])
323
+ .filter((call: any) => typeof call?.toolName === 'string')
324
+ .map((call: any) => ({
325
+ arguments: call.input && typeof call.input === 'object' && !Array.isArray(call.input) ? call.input : {},
326
+ id: call.toolCallId,
327
+ name: call.toolName,
328
+ }));
329
+ return {
330
+ finishReason: typeof result?.finishReason === 'string' ? result.finishReason : result?.finishReason?.unified,
331
+ raw: result?.response?.body,
332
+ text: typeof result?.text === 'string' ? result.text : '',
333
+ toolCalls: toolCalls.length ? toolCalls : undefined,
334
+ usage: mapAiSdkUsage(result?.totalUsage ?? result?.usage),
335
+ };
336
+ }
337
+
338
+ /** An error of the call as the HTTP answer the built-in provider gives for the same failure. */
339
+ protected toTransportError(error: unknown): Error {
340
+ if (error instanceof AiSdkPackageError || error instanceof ServiceUnavailableException) {
341
+ return error;
342
+ }
343
+ if (error instanceof BadGatewayException) {
344
+ return error;
345
+ }
346
+ const message = (error as Error)?.message ?? String(error);
347
+ this.logger.warn(`AI connection "${this.connection.name}" call failed: ${message}`);
348
+ return new ServiceUnavailableException(ErrorCode.AI_CONNECTION_NOT_AVAILABLE);
349
+ }
350
+ }
351
+
352
+ /** AI SDK usage as {@link LlmUsage}; `undefined` when the provider reported nothing. */
353
+ export function mapAiSdkUsage(usage: any): LlmUsage | undefined {
354
+ if (!usage || typeof usage !== 'object') {
355
+ return undefined;
356
+ }
357
+ const promptTokens = numberOrUndefined(usage.inputTokens);
358
+ const completionTokens = numberOrUndefined(usage.outputTokens);
359
+ const reasoningTokens = numberOrUndefined(usage.outputTokenDetails?.reasoningTokens ?? usage.reasoningTokens);
360
+ const totalTokens =
361
+ numberOrUndefined(usage.totalTokens) ??
362
+ (promptTokens !== undefined || completionTokens !== undefined
363
+ ? (promptTokens ?? 0) + (completionTokens ?? 0)
364
+ : undefined);
365
+ if ([promptTokens, completionTokens, reasoningTokens, totalTokens].every((value) => value === undefined)) {
366
+ return undefined;
367
+ }
368
+ return {
369
+ ...(completionTokens !== undefined && { completionTokens }),
370
+ ...(promptTokens !== undefined && { promptTokens }),
371
+ ...(reasoningTokens !== undefined && { reasoningTokens }),
372
+ ...(totalTokens !== undefined && { totalTokens }),
373
+ };
374
+ }
375
+
376
+ function numberOrUndefined(value: unknown): number | undefined {
377
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
378
+ }
379
+
380
+ /** What the provider marks retryable (408, 409, 429, 5xx, network) — the AI SDK's `APICallError.isRetryable`. */
381
+ export function isRetryableModelError(error: unknown): boolean {
382
+ return (error as { isRetryable?: unknown })?.isRetryable === true;
383
+ }
@@ -1,9 +1,43 @@
1
- import { Injectable, Logger } from '@nestjs/common';
1
+ import { Injectable, Logger, Optional } from '@nestjs/common';
2
+ import { ModuleRef } from '@nestjs/core';
3
+ import type { LanguageModel } from 'ai';
2
4
 
3
5
  import { ILlmProvider } from '../interfaces/llm-provider.interface.js';
4
6
  import { ResolvedAiConnection } from '../interfaces/resolved-ai-connection.interface.js';
7
+ import { createAiEgressFetch } from './ai-egress.helper.js';
8
+ import { AiSdkPackageError, loadAiSdk, loadNestjsAi } from './ai-sdk.packages.js';
9
+ import { AiSdkProvider } from './ai-sdk.provider.js';
5
10
  import { OpenAiCompatibleProvider } from './openai-compatible.provider.js';
6
11
 
12
+ /**
13
+ * What a project's AI SDK model builder receives besides the connection (nestjs-ai plan §2).
14
+ */
15
+ export interface AiSdkModelBuilderContext {
16
+ /**
17
+ * A `fetch` that refuses every host outside `ai.allowedBaseUrlHosts` — hand it to the provider
18
+ * (`createAnthropic({ apiKey, baseURL, fetch })`), or the egress allowlist does not cover the provider's requests.
19
+ */
20
+ fetch: typeof fetch;
21
+ }
22
+
23
+ /**
24
+ * Builds the AI SDK `LanguageModel` of a database-managed connection: `connection.apiKey` is the DECRYPTED key,
25
+ * `connection.model` the model id. The core imports no `@ai-sdk/*` package — the project does:
26
+ *
27
+ * ```typescript
28
+ * factory.registerAiSdkModel('anthropic', (connection, { fetch }) =>
29
+ * createAnthropic({ apiKey: connection.apiKey, fetch })(connection.model),
30
+ * );
31
+ * ```
32
+ */
33
+ export type AiSdkModelBuilder = (
34
+ connection: ResolvedAiConnection,
35
+ context: AiSdkModelBuilderContext,
36
+ ) => LanguageModel | Promise<LanguageModel>;
37
+
38
+ /** The `providerType` of a connection that names a model registered in `@nestjs/ai`'s `AiModule.forRoot({ models })`. */
39
+ export const NESTJS_AI_PROVIDER_TYPE = 'nestjs-ai';
40
+
7
41
  /**
8
42
  * Builds an {@link ILlmProvider} from a resolved connection.
9
43
  *
@@ -23,12 +57,69 @@ export class LlmProviderFactory {
23
57
  private readonly logger = new Logger(LlmProviderFactory.name);
24
58
  private readonly builders = new Map<string, (connection: ResolvedAiConnection) => ILlmProvider>();
25
59
 
26
- constructor() {
60
+ constructor(@Optional() protected readonly moduleRef?: ModuleRef) {
27
61
  // Default builder for the OpenAI-compatible API shape (protocol, not a vendor).
28
62
  const openAiCompatibleBuilder = (connection: ResolvedAiConnection) => new OpenAiCompatibleProvider(connection);
29
63
  this.registerBuilder('openai-compatible', openAiCompatibleBuilder);
30
64
  // Convenience alias for connections that store the shorter protocol key.
31
65
  this.registerBuilder('openai', openAiCompatibleBuilder);
66
+ // A model registered in @nestjs/ai's AiModule.forRoot({ models }), by name (`connection.model`). Inert until a
67
+ // connection names this providerType: nothing of @nestjs/ai is loaded before (nestjs-ai plan §2).
68
+ this.registerBuilder(
69
+ NESTJS_AI_PROVIDER_TYPE,
70
+ (connection) =>
71
+ new AiSdkProvider(connection, {
72
+ model: () => this.resolveNestjsAiModel(connection),
73
+ resilience: 'nestjs',
74
+ }),
75
+ );
76
+ }
77
+
78
+ /**
79
+ * Register an AI SDK model builder for a `providerType` (12.10.0, nestjs-ai plan §2): connections of that type —
80
+ * managed in the database, with encrypted keys, per tenant — run on an {@link AiSdkProvider} over the model the
81
+ * builder returns. The builder runs on the first call of each connection; `ai` is checked against its tested range
82
+ * then, and immediately here so a missing or untested `ai` fails the boot of the module that registers the builder.
83
+ */
84
+ async registerAiSdkModel(providerType: string, builder: AiSdkModelBuilder): Promise<void> {
85
+ await loadAiSdk(`LlmProviderFactory.registerAiSdkModel('${providerType}')`);
86
+ this.registerBuilder(
87
+ providerType,
88
+ (connection) =>
89
+ new AiSdkProvider(connection, {
90
+ model: () => builder(connection, { fetch: createAiEgressFetch(connection.name) }),
91
+ }),
92
+ );
93
+ }
94
+
95
+ /**
96
+ * The `@nestjs/ai` model a `nestjs-ai` connection names. Resolved from the application, never constructed: a model
97
+ * name the project did not register fails the call with a message naming it.
98
+ */
99
+ protected async resolveNestjsAiModel(connection: ResolvedAiConnection): Promise<LanguageModel> {
100
+ const nestjsAi = await loadNestjsAi(
101
+ `The AI connection "${connection.name}" (providerType "${NESTJS_AI_PROVIDER_TYPE}")`,
102
+ );
103
+ let models: { get(name?: string): LanguageModel; has(name: string): boolean } | undefined;
104
+ try {
105
+ models = this.moduleRef?.get(nestjsAi.AiModels, { strict: false });
106
+ } catch {
107
+ models = undefined;
108
+ }
109
+ if (!models) {
110
+ throw new AiSdkPackageError(
111
+ `The AI connection "${connection.name}" names a @nestjs/ai model, but the application imports no ` +
112
+ 'AiModule.forRoot({ models }).',
113
+ );
114
+ }
115
+ const name = connection.model || 'default';
116
+ if (!models.has(name)) {
117
+ throw new AiSdkPackageError(
118
+ `The AI connection "${connection.name}" names the @nestjs/ai model "${name}", which AiModule.forRoot({ models }) ` +
119
+ 'does not register.',
120
+ );
121
+ }
122
+ return models.get(name);
32
123
  }
33
124
 
34
125
  /**
@@ -1,6 +1,5 @@
1
1
  import { BadGatewayException, Logger, ServiceUnavailableException } from '@nestjs/common';
2
2
 
3
- import { ConfigService } from '../../../common/services/config.service.js';
4
3
  import { ErrorCode } from '../../error-code/index.js';
5
4
  import {
6
5
  ILlmProvider,
@@ -12,6 +11,7 @@ import {
12
11
  LlmUsage,
13
12
  } from '../interfaces/llm-provider.interface.js';
14
13
  import { ResolvedAiConnection } from '../interfaces/resolved-ai-connection.interface.js';
14
+ import { aiEgressHostCandidates, normaliseAiEgressHost, resolveAiEgressAllowlist } from './ai-egress.helper.js';
15
15
 
16
16
  /**
17
17
  * Provider for OpenAI-compatible chat-completions endpoints.
@@ -302,11 +302,7 @@ export class OpenAiCompatibleProvider implements ILlmProvider {
302
302
  // omits the default port, so a conscientious `llm.example.com:443` entry would
303
303
  // otherwise never match `https://llm.example.com/` — a lockout whose only symptom is
304
304
  // a WARN and "the AI stopped working". Nothing here widens the set of reachable hosts.
305
- const defaultPort = parsed.protocol === 'https:' ? '443' : parsed.protocol === 'http:' ? '80' : '';
306
- const candidates = [parsed.host, parsed.hostname];
307
- if (defaultPort && parsed.host === parsed.hostname) {
308
- candidates.push(`${parsed.hostname}:${defaultPort}`);
309
- }
305
+ const candidates = aiEgressHostCandidates(parsed);
310
306
  if (!candidates.map((candidate) => this.normaliseHostEntry(candidate)).some((c) => allowedHosts.includes(c))) {
311
307
  this.logger.warn(
312
308
  `AI connection "${this.connection.name}" host "${parsed.host}" is not in ai.allowedBaseUrlHosts`,
@@ -385,19 +381,8 @@ export class OpenAiCompatibleProvider implements ILlmProvider {
385
381
  * decision, a malformed value is an accident nobody is told about.
386
382
  */
387
383
  protected resolveAllowedBaseUrlHosts(): string[] {
388
- const configured = ConfigService.get<unknown>('ai.allowedBaseUrlHosts');
389
- if (configured === undefined || configured === null) {
390
- return [];
391
- }
392
- const entries = typeof configured === 'string' ? configured.split(',') : configured;
393
- if (!Array.isArray(entries)) {
394
- this.logger.error(
395
- `ai.allowedBaseUrlHosts is a ${typeof configured} and carries no hostnames — the SSRF egress ` +
396
- 'allowlist is NOT active. Use an array or a comma-separated string.',
397
- );
398
- return [];
399
- }
400
- return entries.map((host) => this.normaliseHostEntry(String(host))).filter(Boolean);
384
+ // One implementation for every AI egress path (the AI SDK transport uses it too) — see ai-egress.helper
385
+ return resolveAiEgressAllowlist(this.logger);
401
386
  }
402
387
 
403
388
  /**
@@ -409,10 +394,7 @@ export class OpenAiCompatibleProvider implements ILlmProvider {
409
394
  * produced a confusing refusal — never protection.
410
395
  */
411
396
  protected normaliseHostEntry(value: string): string {
412
- return value
413
- .trim()
414
- .toLowerCase()
415
- .replace(/\.(?=$|:)/, '');
397
+ return normaliseAiEgressHost(value);
416
398
  }
417
399
 
418
400
  /**