@lenne.tech/nest-server 12.9.3 → 12.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/.claude/rules/configurable-features.md +4 -0
  2. package/.claude/rules/package-management.md +35 -6
  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 +8 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +206 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  22. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  23. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  24. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  25. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  26. package/dist/core/common/services/request-context.service.d.ts +2 -0
  27. package/dist/core/common/services/request-context.service.js +3 -0
  28. package/dist/core/common/services/request-context.service.js.map +1 -1
  29. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  30. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  31. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  32. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  33. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  34. package/dist/core/modules/ai/core-ai.module.js +2 -0
  35. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  36. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  37. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  38. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  39. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  40. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  41. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  42. package/dist/core/modules/ai/index.d.ts +8 -0
  43. package/dist/core/modules/ai/index.js +8 -0
  44. package/dist/core/modules/ai/index.js.map +1 -1
  45. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  46. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  47. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  48. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  49. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  50. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  51. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  52. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  53. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  54. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  57. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  58. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  59. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  60. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  61. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  62. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  63. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  64. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  65. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  66. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  67. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  68. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  69. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  70. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  71. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  72. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  73. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  74. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  75. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  76. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  77. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  78. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  79. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  80. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  81. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  82. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  83. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  84. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  85. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  86. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  87. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  88. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  89. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  90. package/dist/core/modules/file/core-file.controller.js +8 -0
  91. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  92. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  93. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  94. package/dist/core.module.js +2 -1
  95. package/dist/core.module.js.map +1 -1
  96. package/dist/index.d.ts +1 -0
  97. package/dist/index.js +1 -0
  98. package/dist/index.js.map +1 -1
  99. package/dist/types/graphql-upload.d.ts +34 -2
  100. package/docs/REQUEST-LIFECYCLE.md +46 -9
  101. package/docs/security-overrides.md +44 -10
  102. package/migration-guides/12.9.3-to-12.9.4.md +137 -0
  103. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  104. package/package.json +62 -37
  105. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  106. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  107. package/src/core/common/helpers/context.helper.ts +14 -0
  108. package/src/core/common/helpers/decorator.helper.ts +5 -0
  109. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  110. package/src/core/common/helpers/graphql-upload.helper.ts +427 -0
  111. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  112. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  113. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  114. package/src/core/common/services/request-context.service.ts +11 -0
  115. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  116. package/src/core/modules/ai/README.md +101 -0
  117. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  118. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  119. package/src/core/modules/ai/core-ai.module.ts +3 -0
  120. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  121. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  122. package/src/core/modules/ai/index.ts +8 -0
  123. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  124. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  125. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  126. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  127. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  128. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  129. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  130. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  131. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  132. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  133. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  134. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  135. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  136. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  137. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  138. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  139. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  140. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  141. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  142. package/src/core/modules/better-auth/README.md +204 -0
  143. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  144. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  145. package/src/core/modules/file/README.md +1 -0
  146. package/src/core/modules/file/core-file.controller.ts +17 -0
  147. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  148. package/src/core.module.ts +5 -1
  149. package/src/index.ts +1 -0
  150. package/src/types/graphql-upload.d.ts +34 -2
@@ -0,0 +1,153 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join } from 'node:path';
3
+
4
+ /**
5
+ * The optional AI SDK and NestJS AI packages, loaded lazily and checked against the versions this release was tested
6
+ * with (nestjs-ai plan §2, principle 2).
7
+ *
8
+ * `ai`, `@nestjs/ai` and `@nestjs/resilience` are OPTIONAL peers: a project that does not install them loads nothing
9
+ * here. A project that does gets a loud error naming the package and the tested range when the installed version lies
10
+ * outside it, or when the members the framework calls are missing — never a quiet misbehaviour of a 0.0.x release.
11
+ * Each check runs once per process.
12
+ */
13
+
14
+ /** The version ranges each package was tested with: `[lowest inclusive, highest exclusive]`. */
15
+ export const AI_SDK_TESTED_RANGES = {
16
+ '@nestjs/ai': ['0.0.2', '0.0.3'],
17
+ '@nestjs/resilience': ['0.0.3', '0.0.4'],
18
+ ai: ['7.0.0', '8.0.0'],
19
+ } as const satisfies Record<string, readonly [string, string]>;
20
+
21
+ export type AiSdkPackageName = keyof typeof AI_SDK_TESTED_RANGES;
22
+
23
+ /** A package is missing, outside its tested range, or lacks a member the framework calls. */
24
+ export class AiSdkPackageError extends Error {
25
+ constructor(message: string) {
26
+ super(message);
27
+ this.name = 'AiSdkPackageError';
28
+ }
29
+ }
30
+
31
+ const checked = new Map<AiSdkPackageName, Promise<any>>();
32
+
33
+ /** The tested range of a package, as people read it (`>=0.0.2 <0.0.3`). */
34
+ export function aiSdkTestedRange(name: AiSdkPackageName): string {
35
+ const [low, high] = AI_SDK_TESTED_RANGES[name];
36
+ return `>=${low} <${high}`;
37
+ }
38
+
39
+ /**
40
+ * Compares two release versions numerically. A pre-release (`1.2.3-beta.1`) compares as lower than its release, so
41
+ * `7.0.0-beta` is outside `>=7.0.0` — a pre-release was not tested.
42
+ */
43
+ export function compareReleaseVersions(a: string, b: string): number {
44
+ const parse = (value: string) => {
45
+ const [core, pre] = value.split('-', 2);
46
+ return { parts: core.split('.').map((part) => Number.parseInt(part, 10) || 0), pre: pre !== undefined };
47
+ };
48
+ const left = parse(a);
49
+ const right = parse(b);
50
+ for (let i = 0; i < 3; i++) {
51
+ const diff = (left.parts[i] ?? 0) - (right.parts[i] ?? 0);
52
+ if (diff !== 0) {
53
+ return diff;
54
+ }
55
+ }
56
+ return left.pre === right.pre ? 0 : left.pre ? -1 : 1;
57
+ }
58
+
59
+ /** Whether `version` lies in the tested range of `name`. */
60
+ export function isTestedAiSdkVersion(name: AiSdkPackageName, version: string): boolean {
61
+ const [low, high] = AI_SDK_TESTED_RANGES[name];
62
+ return compareReleaseVersions(version, low) >= 0 && compareReleaseVersions(version, high) < 0;
63
+ }
64
+
65
+ /**
66
+ * The installed version of a package, resolved from the project (`process.cwd()`), the way the framework loads project
67
+ * files (`.claude/rules/architecture.md` → Module Format). `undefined` when its `package.json` cannot be read — the
68
+ * member check below still runs then.
69
+ */
70
+ function installedVersion(name: AiSdkPackageName): string | undefined {
71
+ try {
72
+ const requireFromProject = createRequire(join(process.cwd(), 'package.json'));
73
+ return requireFromProject(`${name}/package.json`)?.version;
74
+ } catch {
75
+ return undefined;
76
+ }
77
+ }
78
+
79
+ /** The members of each package the framework calls; a release without them is refused. */
80
+ const REQUIRED_MEMBERS: Record<AiSdkPackageName, (module: any) => string[]> = {
81
+ '@nestjs/ai': (module) => [
82
+ typeof module.AiModels?.prototype?.get === 'function' ? '' : 'AiModels.get()',
83
+ typeof module.AiTools?.prototype?.call === 'function' ? '' : 'AiTools.call()',
84
+ 'tools' in (module.AiTools?.prototype ?? {}) ? '' : 'AiTools.tools',
85
+ ],
86
+ '@nestjs/resilience': (module) => [
87
+ typeof module.ResiliencePolicy?.wrap === 'function' ? '' : 'ResiliencePolicy.wrap()',
88
+ typeof module.RetryPolicy === 'function' ? '' : 'RetryPolicy',
89
+ typeof module.TimeoutPolicy === 'function' ? '' : 'TimeoutPolicy',
90
+ ],
91
+ ai: (module) => [
92
+ typeof module.generateText === 'function' ? '' : 'generateText()',
93
+ typeof module.jsonSchema === 'function' ? '' : 'jsonSchema()',
94
+ ],
95
+ };
96
+
97
+ /**
98
+ * Checks a loaded package: tested version range and the members the framework calls. Exported for the tests; the
99
+ * loaders below call it once per package.
100
+ */
101
+ export function assertAiSdkPackage(name: AiSdkPackageName, module: unknown, version: string | undefined): void {
102
+ if (version !== undefined && !isTestedAiSdkVersion(name, version)) {
103
+ throw new AiSdkPackageError(
104
+ `${name}@${version} is installed, but @lenne.tech/nest-server was tested with ${name} ${aiSdkTestedRange(name)}. ` +
105
+ `Install a version in that range, or update @lenne.tech/nest-server. The framework refuses to run an untested ` +
106
+ `release of a 0.x package rather than misbehave with it.`,
107
+ );
108
+ }
109
+ const missing = REQUIRED_MEMBERS[name](module).filter(Boolean);
110
+ if (missing.length) {
111
+ throw new AiSdkPackageError(
112
+ `${name}${version ? `@${version}` : ''} lacks ${missing.join(', ')}, which @lenne.tech/nest-server calls. ` +
113
+ `Tested range: ${name} ${aiSdkTestedRange(name)}.`,
114
+ );
115
+ }
116
+ }
117
+
118
+ async function load(name: AiSdkPackageName, importer: () => Promise<unknown>, feature: string): Promise<any> {
119
+ let pending = checked.get(name);
120
+ if (!pending) {
121
+ pending = importer().then(
122
+ (module) => {
123
+ assertAiSdkPackage(name, module, installedVersion(name));
124
+ return module;
125
+ },
126
+ (error: unknown) => {
127
+ throw new AiSdkPackageError(
128
+ `${feature} needs the package "${name}" (tested range ${aiSdkTestedRange(name)}), which could not be loaded: ` +
129
+ `${(error as Error)?.message ?? error}. Install it in the project.`,
130
+ );
131
+ },
132
+ );
133
+ // A failure is not cached: the next attempt (after the project installed the package) tries again
134
+ pending.catch(() => checked.delete(name));
135
+ checked.set(name, pending);
136
+ }
137
+ return pending;
138
+ }
139
+
140
+ /** The AI SDK (`ai`). `feature` names what needs it, in configuration words, for the error message. */
141
+ export function loadAiSdk(feature: string): Promise<any> {
142
+ return load('ai', () => import('ai'), feature);
143
+ }
144
+
145
+ /** `@nestjs/ai`. */
146
+ export function loadNestjsAi(feature: string): Promise<any> {
147
+ return load('@nestjs/ai', () => import('@nestjs/ai'), feature);
148
+ }
149
+
150
+ /** `@nestjs/resilience` (a required peer of `@nestjs/ai`). */
151
+ export function loadNestjsResilience(feature: string): Promise<any> {
152
+ return load('@nestjs/resilience', () => import('@nestjs/resilience'), feature);
153
+ }
@@ -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
  /**