@ai-setting/roy-agent-core 1.4.13 → 1.4.14

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 (103) hide show
  1. package/dist/packages/core/src/config/index.js +32 -0
  2. package/dist/packages/core/src/env/agent/index.js +24 -0
  3. package/dist/packages/core/src/env/commands/index.js +14 -0
  4. package/dist/packages/core/src/env/debug/formatters/index.js +11 -0
  5. package/dist/packages/core/src/env/debug/index.js +26 -0
  6. package/dist/packages/core/src/env/hook/index.js +29 -0
  7. package/dist/packages/core/src/env/index.js +81 -0
  8. package/dist/packages/core/src/env/llm/index.js +40 -0
  9. package/dist/packages/core/src/env/log-trace/index.js +83 -0
  10. package/dist/packages/core/src/env/mcp/index.js +39 -0
  11. package/dist/packages/core/src/env/mcp/tool/index.js +14 -0
  12. package/dist/packages/core/src/env/memory/built-in/index.js +11 -0
  13. package/dist/packages/core/src/env/memory/index.js +56 -0
  14. package/dist/packages/core/src/env/memory/plugin/index.js +36 -0
  15. package/dist/packages/core/src/env/prompt/index.js +20 -0
  16. package/dist/packages/core/src/env/session/index.js +25 -0
  17. package/dist/packages/core/src/env/session/storage/index.js +18 -0
  18. package/dist/packages/core/src/env/skill/index.js +34 -0
  19. package/dist/packages/core/src/env/skill/tool/index.js +9 -0
  20. package/dist/packages/core/src/env/task/delegate/index.js +18 -0
  21. package/dist/packages/core/src/env/task/hooks/index.js +7 -0
  22. package/dist/packages/core/src/env/task/index.js +30 -0
  23. package/dist/packages/core/src/env/task/plugins/index.js +23 -0
  24. package/dist/packages/core/src/env/task/storage/index.js +14 -0
  25. package/dist/packages/core/src/env/task/tools/index.js +17 -0
  26. package/dist/packages/core/src/env/task/tools/operation/index.js +15 -0
  27. package/dist/{shared/chunk-1d4rwms4.js → packages/core/src/env/tool/built-in/index.js} +4 -4
  28. package/dist/packages/core/src/env/tool/index.js +39 -0
  29. package/dist/packages/core/src/env/workflow/decorators/index.js +27 -0
  30. package/dist/packages/core/src/env/workflow/engine/index.js +28 -0
  31. package/dist/packages/core/src/env/workflow/index.js +132 -0
  32. package/dist/packages/core/src/env/workflow/nodes/index.js +19 -0
  33. package/dist/packages/core/src/env/workflow/service/index.js +13 -0
  34. package/dist/packages/core/src/env/workflow/storage/index.js +27 -0
  35. package/dist/packages/core/src/env/workflow/tools/index.js +159 -0
  36. package/dist/packages/core/src/env/workflow/types/index.js +94 -0
  37. package/dist/packages/core/src/env/workflow/utils/index.js +637 -0
  38. package/dist/packages/core/src/index.js +398 -0
  39. package/dist/shared/@ai-setting/roy-agent-core-04fm8177.js +393 -0
  40. package/dist/shared/@ai-setting/roy-agent-core-04qgbjbe.js +172 -0
  41. package/dist/shared/@ai-setting/roy-agent-core-084qqd7t.js +11 -0
  42. package/dist/shared/@ai-setting/roy-agent-core-0gekht4e.js +1130 -0
  43. package/dist/shared/@ai-setting/roy-agent-core-0hdry23r.js +419 -0
  44. package/dist/shared/{chunk-ze20rksg.js → @ai-setting/roy-agent-core-0sgn3de4.js} +2 -2
  45. package/dist/shared/@ai-setting/roy-agent-core-12x57kf1.js +286 -0
  46. package/dist/shared/@ai-setting/roy-agent-core-1f3xrrm6.js +393 -0
  47. package/dist/shared/{chunk-q9j99fsm.js → @ai-setting/roy-agent-core-1k28kg7h.js} +6 -6
  48. package/dist/shared/{chunk-2b5kbhx3.js → @ai-setting/roy-agent-core-1z1zv5g8.js} +9 -117
  49. package/dist/shared/@ai-setting/roy-agent-core-2hqxnaf3.js +851 -0
  50. package/dist/shared/@ai-setting/roy-agent-core-3dfq8awb.js +587 -0
  51. package/dist/shared/@ai-setting/roy-agent-core-3takar0s.js +93 -0
  52. package/dist/shared/@ai-setting/roy-agent-core-3tnb2005.js +117 -0
  53. package/dist/shared/@ai-setting/roy-agent-core-4vmcvkav.js +14 -0
  54. package/dist/shared/{chunk-25x2pdtp.js → @ai-setting/roy-agent-core-4ws8atva.js} +2 -2
  55. package/dist/shared/@ai-setting/roy-agent-core-5fbp24se.js +603 -0
  56. package/dist/shared/@ai-setting/roy-agent-core-5my94ywp.js +66 -0
  57. package/dist/shared/{chunk-rncy3rtd.js → @ai-setting/roy-agent-core-6j0zcmwk.js} +128 -1122
  58. package/dist/shared/@ai-setting/roy-agent-core-6w4pmxc7.js +266 -0
  59. package/dist/shared/{chunk-yqmx37vm.js → @ai-setting/roy-agent-core-7vrk3add.js} +2 -2
  60. package/dist/shared/@ai-setting/roy-agent-core-8dvbn7tw.js +64 -0
  61. package/dist/shared/@ai-setting/roy-agent-core-8mbmrwzs.js +171 -0
  62. package/dist/shared/@ai-setting/roy-agent-core-8wzz66qe.js +620 -0
  63. package/dist/shared/@ai-setting/roy-agent-core-9ykq91jc.js +762 -0
  64. package/dist/shared/@ai-setting/roy-agent-core-dde19zke.js +1305 -0
  65. package/dist/shared/@ai-setting/roy-agent-core-f7g67gce.js +913 -0
  66. package/dist/shared/@ai-setting/roy-agent-core-fq5mtxsy.js +341 -0
  67. package/dist/shared/@ai-setting/roy-agent-core-fvd9g6k8.js +1205 -0
  68. package/dist/shared/@ai-setting/roy-agent-core-gv1hrn3x.js +378 -0
  69. package/dist/shared/@ai-setting/roy-agent-core-gy0wp5h7.js +213 -0
  70. package/dist/shared/{chunk-mf5xqbdh.js → @ai-setting/roy-agent-core-hyza1gm7.js} +3 -2
  71. package/dist/shared/{chunk-1qwabsm0.js → @ai-setting/roy-agent-core-j8zx62zr.js} +2 -2
  72. package/dist/shared/@ai-setting/roy-agent-core-jb2exr0d.js +442 -0
  73. package/dist/shared/@ai-setting/roy-agent-core-jv3b7v9w.js +57 -0
  74. package/dist/shared/@ai-setting/roy-agent-core-k1rxf9ya.js +513 -0
  75. package/dist/shared/@ai-setting/roy-agent-core-kydc9nwb.js +60 -0
  76. package/dist/shared/@ai-setting/roy-agent-core-m2x48hw6.js +97 -0
  77. package/dist/shared/@ai-setting/roy-agent-core-m6y668cc.js +377 -0
  78. package/dist/shared/{chunk-1aakcfp1.js → @ai-setting/roy-agent-core-nczzf0ms.js} +3 -3
  79. package/dist/shared/@ai-setting/roy-agent-core-nfj6knp5.js +36 -0
  80. package/dist/shared/@ai-setting/roy-agent-core-ntrp979d.js +204 -0
  81. package/dist/shared/@ai-setting/roy-agent-core-pd7g8z5v.js +1387 -0
  82. package/dist/shared/@ai-setting/roy-agent-core-pzk1syce.js +14 -0
  83. package/dist/shared/@ai-setting/roy-agent-core-q50tg9m2.js +862 -0
  84. package/dist/shared/{chunk-9qzt1v1p.js → @ai-setting/roy-agent-core-qg9tcaph.js} +3 -2
  85. package/dist/shared/{chunk-91bas8w5.js → @ai-setting/roy-agent-core-qhyerewk.js} +5 -5
  86. package/dist/shared/{chunk-1pf5mfgd.js → @ai-setting/roy-agent-core-qxybm159.js} +3 -3
  87. package/dist/shared/{chunk-g6j5n3gv.js → @ai-setting/roy-agent-core-rh9dpkpw.js} +10 -10
  88. package/dist/shared/{chunk-0q6s9wm6.js → @ai-setting/roy-agent-core-rr9p1g43.js} +7 -51
  89. package/dist/shared/@ai-setting/roy-agent-core-sbzvpfn7.js +284 -0
  90. package/dist/shared/@ai-setting/roy-agent-core-t22nqt4d.js +788 -0
  91. package/dist/shared/{chunk-t1rh6jtm.js → @ai-setting/roy-agent-core-tkr5ynkh.js} +8 -13
  92. package/dist/shared/@ai-setting/roy-agent-core-v4aabsf0.js +303 -0
  93. package/dist/shared/@ai-setting/roy-agent-core-w75rafhy.js +202 -0
  94. package/dist/shared/@ai-setting/roy-agent-core-w76hqkmg.js +584 -0
  95. package/dist/shared/@ai-setting/roy-agent-core-yfbgwes2.js +408 -0
  96. package/dist/shared/{chunk-a9qmy3sc.js → @ai-setting/roy-agent-core-yn761yve.js} +7 -4
  97. package/dist/shared/@ai-setting/roy-agent-core-yrzmn4m1.js +492 -0
  98. package/dist/shared/@ai-setting/roy-agent-core-yt8wdh2w.js +206 -0
  99. package/package.json +8 -7
  100. package/dist/index.d.ts +0 -7825
  101. package/dist/index.js +0 -16551
  102. package/dist/shared/chunk-hs7tbmje.js +0 -24
  103. /package/dist/shared/{chunk-wbkh7wat.js → @ai-setting/roy-agent-core-fs0mn2jk.js} +0 -0
@@ -0,0 +1,1305 @@
1
+ import {
2
+ ContextError,
3
+ ErrorCodes
4
+ } from "./roy-agent-core-3takar0s.js";
5
+ import {
6
+ TracedAs,
7
+ init_decorator
8
+ } from "./roy-agent-core-04qgbjbe.js";
9
+ import {
10
+ envKeyToConfigKey,
11
+ toEnvKey
12
+ } from "./roy-agent-core-jv3b7v9w.js";
13
+ import {
14
+ BaseComponent
15
+ } from "./roy-agent-core-m2x48hw6.js";
16
+ import {
17
+ LLMHookPoints,
18
+ globalHookManager
19
+ } from "./roy-agent-core-w75rafhy.js";
20
+ import {
21
+ createLogger,
22
+ init_logger
23
+ } from "./roy-agent-core-yn761yve.js";
24
+ import {
25
+ __legacyDecorateClassTS,
26
+ __require
27
+ } from "./roy-agent-core-fs0mn2jk.js";
28
+
29
+ // packages/core/src/env/llm/types.ts
30
+ import { z } from "zod";
31
+ var ProviderCapabilitiesSchema = z.object({
32
+ reasoning: z.boolean().optional(),
33
+ toolcall: z.boolean().optional(),
34
+ interleaved: z.object({
35
+ field: z.string()
36
+ }).optional(),
37
+ thinkingInText: z.object({
38
+ enabled: z.boolean().optional(),
39
+ tags: z.array(z.string()).optional(),
40
+ removeFromOutput: z.boolean().optional()
41
+ }).optional()
42
+ });
43
+ var ModelLimitsSchema = z.object({
44
+ contextWindow: z.number().int().positive(),
45
+ compactionThreshold: z.number().min(0).max(1).optional(),
46
+ maxOutputTokens: z.number().int().positive().optional()
47
+ });
48
+ var ProviderConfigSchema = z.object({
49
+ provider: z.string(),
50
+ name: z.string().optional(),
51
+ description: z.string().optional(),
52
+ apiKey: z.string(),
53
+ baseURL: z.string().optional(),
54
+ models: z.array(z.string()).optional(),
55
+ defaultModel: z.string().optional(),
56
+ temperature: z.number().min(0).max(2).optional(),
57
+ maxTokens: z.number().int().positive().optional(),
58
+ capabilities: ProviderCapabilitiesSchema.optional(),
59
+ limits: z.record(z.string(), ModelLimitsSchema).optional(),
60
+ providerOptions: z.record(z.unknown()).optional(),
61
+ options: z.record(z.unknown()).optional()
62
+ });
63
+ var LLMDefaultConfigSchema = z.object({
64
+ temperature: z.number().min(0).max(2).optional(),
65
+ maxTokens: z.number().int().positive().optional()
66
+ });
67
+ var LLMConfigSchema = z.object({
68
+ default: LLMDefaultConfigSchema.optional(),
69
+ defaultModel: z.string().optional(),
70
+ providers: z.record(z.string(), ProviderConfigSchema),
71
+ defaultProvider: z.string(),
72
+ temperature: z.number().min(0).max(2).default(0.7),
73
+ maxTokens: z.number().int().positive().optional(),
74
+ topP: z.number().min(0).max(1).optional(),
75
+ stream: z.boolean().default(true),
76
+ options: z.record(z.unknown()).optional()
77
+ });
78
+ // packages/core/src/env/llm/provider.ts
79
+ class ProviderManager {
80
+ providers = new Map;
81
+ async initialize(config) {
82
+ this.providers.clear();
83
+ for (const [id, providerConfig] of Object.entries(config.providers)) {
84
+ const resolvedConfig = await this.resolveProviderConfig(providerConfig);
85
+ const provider = this.createProvider(id, resolvedConfig);
86
+ this.providers.set(id, provider);
87
+ }
88
+ }
89
+ getProvider(id) {
90
+ return this.providers.get(id);
91
+ }
92
+ listProviders() {
93
+ return Array.from(this.providers.values());
94
+ }
95
+ async resolveProviderConfig(config) {
96
+ return {
97
+ ...config,
98
+ apiKey: await this.resolveEnvVar(config.apiKey),
99
+ baseURL: config.baseURL ? await this.resolveEnvVar(config.baseURL) : undefined
100
+ };
101
+ }
102
+ async resolveEnvVar(value) {
103
+ const envVarPattern = /\$\{([^}]+)\}/g;
104
+ const matches = [...value.matchAll(envVarPattern)];
105
+ if (matches.length === 0) {
106
+ return value;
107
+ }
108
+ let result = value;
109
+ for (const match of matches) {
110
+ const varName = match[1];
111
+ const envValue = process.env[varName];
112
+ if (envValue === undefined) {
113
+ throw new Error(`Environment variable ${varName} is not set`);
114
+ }
115
+ result = result.replace(match[0], envValue);
116
+ }
117
+ return result;
118
+ }
119
+ createProvider(id, config) {
120
+ return {
121
+ id,
122
+ provider: null,
123
+ models: config.models || []
124
+ };
125
+ }
126
+ createAIProvider(id, config, createFn) {
127
+ const providerInstance = createFn(config.apiKey, config.baseURL);
128
+ return {
129
+ id,
130
+ provider: providerInstance,
131
+ models: config.models || []
132
+ };
133
+ }
134
+ }
135
+ // packages/core/src/env/llm/transform.ts
136
+ class LLMTransform {
137
+ normalizeMessages(messages, providerType) {
138
+ return messages.map((msg) => {
139
+ switch (providerType) {
140
+ case "anthropic":
141
+ return this.normalizeForAnthropic(msg);
142
+ case "openai":
143
+ case "openai-compatible":
144
+ default:
145
+ return this.normalizeForOpenAI(msg);
146
+ }
147
+ });
148
+ }
149
+ normalizeForOpenAI(msg) {
150
+ return {
151
+ role: msg.role,
152
+ content: msg.content,
153
+ toolCalls: msg.toolCalls,
154
+ toolCallId: msg.toolCallId
155
+ };
156
+ }
157
+ normalizeForAnthropic(msg) {
158
+ if (msg.role === "tool") {
159
+ return {
160
+ role: "user",
161
+ content: msg.content,
162
+ toolCallId: msg.toolCallId
163
+ };
164
+ }
165
+ return msg;
166
+ }
167
+ extractToolSchema(tool) {
168
+ return {
169
+ name: tool.name,
170
+ description: tool.description,
171
+ parameters: tool.parameters
172
+ };
173
+ }
174
+ zodToJsonSchema(schema) {
175
+ return this.extractZodSchema(schema);
176
+ }
177
+ extractZodSchema(schema) {
178
+ const def = schema._def;
179
+ if (!def)
180
+ return {};
181
+ const typeName = def.typeName || "";
182
+ const type = def.type || "";
183
+ const isV3 = typeName.startsWith("Zod");
184
+ const isV4 = !isV3 && type !== "";
185
+ if (isV3 && typeName === "ZodObject" || isV4 && type === "object") {
186
+ let shape;
187
+ if (isV3) {
188
+ const shapeFn = def.shape;
189
+ shape = shapeFn ? shapeFn() : undefined;
190
+ } else {
191
+ shape = def.shape;
192
+ }
193
+ const properties = {};
194
+ const required = [];
195
+ if (shape) {
196
+ for (const [key, value] of Object.entries(shape)) {
197
+ properties[key] = this.extractZodSchema(value);
198
+ let isOptional = false;
199
+ if (isV3) {
200
+ const zodType = value;
201
+ isOptional = typeof zodType.isOptional === "function" ? zodType.isOptional() : false;
202
+ } else {
203
+ const innerDef = value._def;
204
+ isOptional = innerDef?.defaultValue !== undefined;
205
+ }
206
+ if (!isOptional) {
207
+ required.push(key);
208
+ }
209
+ }
210
+ }
211
+ return {
212
+ type: "object",
213
+ properties,
214
+ ...required.length > 0 ? { required } : {}
215
+ };
216
+ }
217
+ if (isV3 && typeName === "ZodEnum" || isV4 && type === "enum") {
218
+ const zodV3Enum = def;
219
+ const zodV4Enum = def;
220
+ const values = zodV3Enum.values || Object.values(zodV4Enum.entries || {});
221
+ return {
222
+ enum: values
223
+ };
224
+ }
225
+ if (isV3 && typeName === "ZodNativeEnum") {
226
+ const enumDef = def;
227
+ const values = Object.values(enumDef.values || {});
228
+ return {
229
+ enum: values
230
+ };
231
+ }
232
+ if (isV3 && typeName === "ZodString" || isV4 && type === "string") {
233
+ return { type: "string" };
234
+ }
235
+ if (isV3 && (typeName === "ZodNumber" || typeName === "ZodBigInt") || isV4 && (type === "number" || type === "bigint")) {
236
+ return { type: "number" };
237
+ }
238
+ if (isV3 && typeName === "ZodBoolean" || isV4 && type === "boolean") {
239
+ return { type: "boolean" };
240
+ }
241
+ if (isV3 && typeName === "ZodArray" || isV4 && type === "array") {
242
+ if (isV3) {
243
+ const itemsType = def.type;
244
+ if (itemsType) {
245
+ return {
246
+ type: "array",
247
+ items: this.extractZodSchema(itemsType)
248
+ };
249
+ }
250
+ }
251
+ const shape = def.shape;
252
+ if (shape) {
253
+ const itemKey = Object.keys(shape)[0];
254
+ const items = this.extractZodSchema(shape[itemKey]);
255
+ return {
256
+ type: "array",
257
+ items
258
+ };
259
+ }
260
+ return {
261
+ type: "array",
262
+ items: {}
263
+ };
264
+ }
265
+ if (isV3 && typeName === "ZodOptional" || isV4 && type === "optional") {
266
+ if (isV3) {
267
+ const innerType = def.innerType;
268
+ if (innerType) {
269
+ return this.extractZodSchema(innerType);
270
+ }
271
+ }
272
+ const shape = def.shape;
273
+ if (shape) {
274
+ const innerKey = Object.keys(shape).find((k) => k !== "undefinedType");
275
+ if (innerKey) {
276
+ return this.extractZodSchema(shape[innerKey]);
277
+ }
278
+ }
279
+ return {};
280
+ }
281
+ if (isV3 && typeName === "ZodNullable") {
282
+ const innerType = def.innerType;
283
+ if (innerType) {
284
+ return this.extractZodSchema(innerType);
285
+ }
286
+ }
287
+ return {};
288
+ }
289
+ formatToolResult(result) {
290
+ return {
291
+ role: "tool",
292
+ tool_call_id: result.toolCallId,
293
+ content: result.result,
294
+ ...result.isError ? { isError: true } : {}
295
+ };
296
+ }
297
+ parseToolArguments(args) {
298
+ if (!args || args.trim() === "") {
299
+ return {};
300
+ }
301
+ try {
302
+ return JSON.parse(args);
303
+ } catch {
304
+ return {};
305
+ }
306
+ }
307
+ serializeToolArguments(args) {
308
+ return JSON.stringify(args);
309
+ }
310
+ }
311
+ // packages/core/src/env/llm/invoke.ts
312
+ init_logger();
313
+ import { randomUUID } from "crypto";
314
+ import { streamText, jsonSchema } from "ai";
315
+ import { createOpenAI } from "@ai-sdk/openai";
316
+ import { createAnthropic } from "@ai-sdk/anthropic";
317
+ import { createGoogleGenerativeAI } from "@ai-sdk/google";
318
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
319
+ import { zodToJsonSchema } from "zod-to-json-schema";
320
+ var logger = createLogger("llm:invoke");
321
+ var MAX_RETRIES = 3;
322
+ function parseModelString(model) {
323
+ if (!model) {
324
+ return { providerId: "openai", modelId: "gpt-4o" };
325
+ }
326
+ const parts = model.split("/");
327
+ if (parts.length >= 2) {
328
+ return { providerId: parts[0], modelId: parts.slice(1).join("/") };
329
+ }
330
+ return { providerId: "openai", modelId: model };
331
+ }
332
+ function extractUsageInfo(usage) {
333
+ if (!usage)
334
+ return;
335
+ if (usage.inputTokens && typeof usage.inputTokens === "object") {
336
+ return {
337
+ promptTokens: usage.inputTokens.total ?? 0,
338
+ completionTokens: usage.outputTokens?.total ?? 0,
339
+ totalTokens: usage.totalTokens ?? 0
340
+ };
341
+ }
342
+ if (typeof usage.promptTokens === "number") {
343
+ return {
344
+ promptTokens: usage.promptTokens,
345
+ completionTokens: usage.completionTokens ?? 0,
346
+ totalTokens: usage.totalTokens ?? 0
347
+ };
348
+ }
349
+ if (usage.inputTokenDetails || usage.outputTokenDetails) {
350
+ return {
351
+ promptTokens: usage.inputTokenDetails?.tokens ?? 0,
352
+ completionTokens: usage.outputTokenDetails?.tokens ?? 0,
353
+ totalTokens: usage.totalTokens ?? 0
354
+ };
355
+ }
356
+ if (usage.raw && typeof usage.raw.total_tokens === "number") {
357
+ return {
358
+ promptTokens: 0,
359
+ completionTokens: 0,
360
+ totalTokens: usage.raw.total_tokens
361
+ };
362
+ }
363
+ return;
364
+ }
365
+ function convertToSDKMessages(messages) {
366
+ return messages.map((msg) => {
367
+ if (msg.role === "assistant" && msg.toolCalls && msg.toolCalls.length > 0) {
368
+ const toolCallParts = msg.toolCalls.map((tc) => {
369
+ let input = {};
370
+ if (tc.function?.arguments) {
371
+ if (typeof tc.function.arguments === "string") {
372
+ try {
373
+ input = JSON.parse(tc.function.arguments);
374
+ } catch {
375
+ input = tc.function.arguments;
376
+ }
377
+ } else {
378
+ input = tc.function.arguments;
379
+ }
380
+ } else if (tc.arguments) {
381
+ if (typeof tc.arguments === "string") {
382
+ try {
383
+ input = JSON.parse(tc.arguments);
384
+ } catch {
385
+ input = tc.arguments;
386
+ }
387
+ } else {
388
+ input = tc.arguments;
389
+ }
390
+ }
391
+ return {
392
+ type: "tool-call",
393
+ toolCallId: tc.id,
394
+ toolName: tc.function?.name || tc.name || "unknown",
395
+ input
396
+ };
397
+ });
398
+ return {
399
+ role: "assistant",
400
+ content: toolCallParts
401
+ };
402
+ }
403
+ if (msg.role === "tool") {
404
+ if (!msg.toolCallId) {
405
+ logger.warn("Tool message missing toolCallId", { msg });
406
+ }
407
+ let outputValue = "";
408
+ const content = msg.content;
409
+ if (typeof content === "string") {
410
+ outputValue = content;
411
+ } else if (Array.isArray(content)) {
412
+ const toolResultPart = content.find((p) => p?.type === "tool-result");
413
+ if (toolResultPart) {
414
+ outputValue = typeof toolResultPart.output === "string" ? toolResultPart.output : JSON.stringify(toolResultPart.output);
415
+ } else {
416
+ outputValue = JSON.stringify(content);
417
+ }
418
+ } else {
419
+ outputValue = JSON.stringify(content);
420
+ }
421
+ const converted = {
422
+ role: "tool",
423
+ content: [{
424
+ type: "tool-result",
425
+ toolCallId: msg.toolCallId || "unknown",
426
+ toolName: msg.name || "unknown",
427
+ output: {
428
+ type: "text",
429
+ value: outputValue
430
+ }
431
+ }]
432
+ };
433
+ return converted;
434
+ }
435
+ return msg;
436
+ });
437
+ }
438
+ function convertToolsToSDK(tools) {
439
+ const result = {};
440
+ for (const tool of tools) {
441
+ const jsonSchemaObj = extractToolSchema(tool.parameters);
442
+ result[tool.name] = {
443
+ description: tool.description || "",
444
+ inputSchema: jsonSchema(jsonSchemaObj)
445
+ };
446
+ }
447
+ return result;
448
+ }
449
+ function extractToolSchema(parameters) {
450
+ if (parameters && typeof parameters === "object" && "_def" in parameters) {
451
+ const zodSchema = parameters;
452
+ const schema = zodToJsonSchema(zodSchema, "zod");
453
+ if ("$ref" in schema && schema.definitions) {
454
+ const def = schema.definitions.zod;
455
+ if (def && def.type === "object" && def.properties) {
456
+ return {
457
+ type: "object",
458
+ properties: def.properties,
459
+ required: def.required,
460
+ additionalProperties: true
461
+ };
462
+ }
463
+ }
464
+ return schema;
465
+ }
466
+ return parameters;
467
+ }
468
+ function generateProviderOptions(providerType, options) {
469
+ const result = {
470
+ providerOptions: {}
471
+ };
472
+ if (options.temperature !== undefined) {
473
+ result.temperature = options.temperature;
474
+ }
475
+ if (options.maxTokens !== undefined) {
476
+ result.maxTokens = options.maxTokens;
477
+ }
478
+ switch (providerType) {
479
+ case "anthropic":
480
+ break;
481
+ case "openai-compatible":
482
+ result.providerOptions.includeUsage = true;
483
+ break;
484
+ }
485
+ return result;
486
+ }
487
+ function createEnvEventEmitter(env, context) {
488
+ if (!env) {
489
+ return null;
490
+ }
491
+ return (event) => {
492
+ try {
493
+ env.pushEnvEvent({
494
+ id: randomUUID(),
495
+ type: `llm.${event.type}`,
496
+ timestamp: Date.now(),
497
+ metadata: {
498
+ source: "llm.invoke",
499
+ sessionId: context?.sessionId,
500
+ messageId: context?.messageId
501
+ },
502
+ payload: event
503
+ });
504
+ } catch (err) {
505
+ logger.warn("Failed to push env event", { error: String(err), eventType: event.type });
506
+ }
507
+ };
508
+ }
509
+ function processThinkingStream(textDelta, config, state) {
510
+ if (!config.enabled || !textDelta) {
511
+ return {
512
+ cleanedText: textDelta,
513
+ isThinkingTagOpen: state.isOpen,
514
+ currentThinkingContent: state.content,
515
+ reasoningEvents: []
516
+ };
517
+ }
518
+ const tags = config.tags || ["thinking"];
519
+ let remainingText = textDelta;
520
+ const reasoningEvents = [];
521
+ let isOpen = state.isOpen;
522
+ let currentContent = state.content;
523
+ for (const tag of tags) {
524
+ const openTag = `<${tag}>`;
525
+ const closeTag = `</${tag}>`;
526
+ let text = remainingText;
527
+ let result = "";
528
+ const openIndex = text.toLowerCase().indexOf(openTag.toLowerCase());
529
+ const closeIndex = text.toLowerCase().indexOf(closeTag.toLowerCase());
530
+ if (openIndex !== -1 && (closeIndex === -1 || openIndex < closeIndex)) {
531
+ const beforeOpen = text.substring(0, openIndex);
532
+ const afterOpen = text.substring(openIndex + openTag.length);
533
+ if (!isOpen) {
534
+ isOpen = true;
535
+ currentContent = "";
536
+ reasoningEvents.push("");
537
+ }
538
+ result += beforeOpen;
539
+ const innerCloseIndex = afterOpen.toLowerCase().indexOf(closeTag.toLowerCase());
540
+ if (innerCloseIndex !== -1) {
541
+ const thinkingContent = afterOpen.substring(0, innerCloseIndex);
542
+ const afterClose = afterOpen.substring(innerCloseIndex + closeTag.length);
543
+ currentContent += thinkingContent;
544
+ reasoningEvents.push(currentContent);
545
+ isOpen = false;
546
+ currentContent = "";
547
+ result += afterClose;
548
+ } else {
549
+ currentContent += afterOpen;
550
+ reasoningEvents.push(currentContent);
551
+ result += "";
552
+ }
553
+ remainingText = result;
554
+ } else if (closeIndex !== -1) {
555
+ const beforeClose = text.substring(0, closeIndex);
556
+ const afterClose = text.substring(closeIndex + closeTag.length);
557
+ if (isOpen) {
558
+ currentContent += beforeClose;
559
+ reasoningEvents.push(currentContent);
560
+ isOpen = false;
561
+ currentContent = "";
562
+ result = afterClose;
563
+ } else {
564
+ result = text;
565
+ }
566
+ remainingText = result;
567
+ }
568
+ }
569
+ return {
570
+ cleanedText: remainingText,
571
+ isThinkingTagOpen: isOpen,
572
+ currentThinkingContent: currentContent,
573
+ reasoningEvents
574
+ };
575
+ }
576
+ async function invoke(config, options, ctx) {
577
+ try {
578
+ const emitToEnv = createEnvEventEmitter(options.env, options.context);
579
+ const { providerId, modelId } = parseModelString(options.model || config.model);
580
+ const provider = createProviderInstance(providerId, config.apiKey, config.baseURL);
581
+ if (!provider) {
582
+ throw new Error(`Failed to create provider for ${providerId}`);
583
+ }
584
+ const messages = convertToSDKMessages(options.messages);
585
+ const toolCallIds = new Set;
586
+ const assistantToolCalls = [];
587
+ const toolResultIds = [];
588
+ for (const msg of messages) {
589
+ if (msg.role === "assistant") {
590
+ const assistantContent = Array.isArray(msg.content) ? msg.content : [];
591
+ for (const part of assistantContent) {
592
+ if (part && typeof part === "object" && part.type === "tool-call") {
593
+ const tc = part.toolCall || part;
594
+ assistantToolCalls.push({ id: tc.id, name: tc.name || tc.function && tc.function.name });
595
+ toolCallIds.add(tc.id);
596
+ }
597
+ }
598
+ }
599
+ if (msg.role === "tool") {
600
+ const toolContent = Array.isArray(msg.content) ? msg.content : [];
601
+ for (const part of toolContent) {
602
+ if (part && typeof part === "object" && part.type === "tool-result") {
603
+ toolResultIds.push(part.toolCallId);
604
+ }
605
+ }
606
+ }
607
+ }
608
+ const missingToolResults = assistantToolCalls.filter((tc) => !toolResultIds.includes(tc.id));
609
+ const orphanedToolResults = toolResultIds.filter((id) => !toolCallIds.has(id));
610
+ if (assistantToolCalls.length > 0 || toolResultIds.length > 0) {
611
+ logger.debug("[invoke] ToolCallId matching analysis:", {
612
+ assistantToolCalls,
613
+ toolResultIds,
614
+ missingToolResults: missingToolResults.length > 0 ? missingToolResults : "none",
615
+ orphanedToolResults: orphanedToolResults.length > 0 ? orphanedToolResults : "none"
616
+ });
617
+ }
618
+ const tools = options.tools && options.tools.length > 0 ? convertToolsToSDK(options.tools) : undefined;
619
+ const providerOptions = generateProviderOptions(providerId, {
620
+ temperature: options.temperature,
621
+ maxTokens: options.maxTokens
622
+ });
623
+ const model = `${providerId}/${modelId}`;
624
+ if (emitToEnv) {
625
+ emitToEnv({ type: "start", metadata: { model } });
626
+ }
627
+ const streamTextOptions = {
628
+ model: provider.languageModel(modelId),
629
+ messages,
630
+ tools,
631
+ temperature: providerOptions.temperature,
632
+ maxTokens: providerOptions.maxTokens,
633
+ abortSignal: ctx.abort,
634
+ maxRetries: MAX_RETRIES,
635
+ streamOptions: {
636
+ includeUsage: true
637
+ },
638
+ allowSystemInMessages: true
639
+ };
640
+ const result = await streamText(streamTextOptions);
641
+ let fullContent = "";
642
+ let reasoningContent = "";
643
+ const toolCalls = [];
644
+ let usageInfo;
645
+ let isThinkingTagOpen = false;
646
+ let currentThinkingContent = "";
647
+ for await (const part of result.fullStream) {
648
+ const streamPart = part;
649
+ switch (streamPart.type) {
650
+ case "text-delta":
651
+ const textDelta = streamPart.text;
652
+ const thinkingConfig = config.options?.thinkingInText;
653
+ if (thinkingConfig?.enabled) {
654
+ const thinkingResult = processThinkingStream(textDelta, thinkingConfig, {
655
+ isOpen: isThinkingTagOpen,
656
+ content: currentThinkingContent
657
+ });
658
+ isThinkingTagOpen = thinkingResult.isThinkingTagOpen;
659
+ currentThinkingContent = thinkingResult.currentThinkingContent;
660
+ fullContent += thinkingResult.cleanedText;
661
+ for (const reasoningDelta2 of thinkingResult.reasoningEvents) {
662
+ reasoningContent = reasoningDelta2;
663
+ if (emitToEnv) {
664
+ emitToEnv({ type: "reasoning", content: reasoningContent });
665
+ }
666
+ }
667
+ if (emitToEnv) {
668
+ emitToEnv({ type: "text", content: fullContent, delta: thinkingResult.cleanedText });
669
+ }
670
+ } else {
671
+ fullContent += textDelta;
672
+ if (emitToEnv) {
673
+ emitToEnv({ type: "text", content: fullContent, delta: textDelta });
674
+ }
675
+ }
676
+ break;
677
+ case "reasoning-delta":
678
+ const reasoningDelta = streamPart.text;
679
+ reasoningContent += reasoningDelta;
680
+ if (emitToEnv) {
681
+ emitToEnv({ type: "reasoning", content: reasoningContent });
682
+ }
683
+ break;
684
+ case "tool-call":
685
+ const toolInput = streamPart.input;
686
+ const toolCallId = streamPart.toolCallId;
687
+ const toolName = streamPart.toolName;
688
+ toolCalls.push({
689
+ id: toolCallId,
690
+ name: toolName,
691
+ args: toolInput
692
+ });
693
+ if (emitToEnv) {
694
+ emitToEnv({
695
+ type: "tool_call",
696
+ toolCall: {
697
+ id: toolCallId,
698
+ name: toolName,
699
+ arguments: JSON.stringify(toolInput)
700
+ }
701
+ });
702
+ }
703
+ break;
704
+ case "finish-step":
705
+ const stepUsage = extractUsageInfo(streamPart.usage);
706
+ if (stepUsage) {
707
+ usageInfo = stepUsage;
708
+ }
709
+ break;
710
+ case "error":
711
+ throw streamPart.error;
712
+ case "finish":
713
+ usageInfo = extractUsageInfo(streamPart.totalUsage);
714
+ if (!usageInfo && streamPart.usage) {
715
+ usageInfo = extractUsageInfo(streamPart.usage);
716
+ }
717
+ break;
718
+ }
719
+ }
720
+ if (emitToEnv) {
721
+ emitToEnv({
722
+ type: "completed",
723
+ content: fullContent,
724
+ metadata: {
725
+ model,
726
+ usage: usageInfo
727
+ }
728
+ });
729
+ }
730
+ if (toolCalls.length > 0) {
731
+ const firstToolCall = toolCalls[0];
732
+ return {
733
+ toolCallId: firstToolCall.id,
734
+ result: JSON.stringify({
735
+ content: fullContent,
736
+ reasoning: reasoningContent || undefined,
737
+ tool_calls: toolCalls.map((tc) => ({
738
+ id: tc.id,
739
+ function: {
740
+ name: tc.name,
741
+ arguments: JSON.stringify(tc.args)
742
+ }
743
+ }))
744
+ })
745
+ };
746
+ }
747
+ return {
748
+ toolCallId: "invoke-" + Date.now(),
749
+ result: JSON.stringify({
750
+ content: fullContent,
751
+ reasoning: reasoningContent || undefined,
752
+ usage: usageInfo,
753
+ model
754
+ })
755
+ };
756
+ } catch (error) {
757
+ logger.error("Error during invocation", {
758
+ error: error instanceof Error ? error.message : String(error),
759
+ stack: error instanceof Error ? error.stack : undefined
760
+ });
761
+ return {
762
+ toolCallId: "error-" + Date.now(),
763
+ result: error instanceof Error ? error.message : String(error),
764
+ isError: true
765
+ };
766
+ }
767
+ }
768
+ function createProviderInstance(providerId, apiKey, baseURL) {
769
+ try {
770
+ if (providerId === "openai") {
771
+ const openai = createOpenAI({
772
+ apiKey,
773
+ baseURL
774
+ });
775
+ return openai;
776
+ }
777
+ if (providerId === "anthropic") {
778
+ const anthropic = createAnthropic({
779
+ apiKey
780
+ });
781
+ return anthropic;
782
+ }
783
+ if (providerId === "google") {
784
+ const google = createGoogleGenerativeAI({
785
+ apiKey
786
+ });
787
+ return google;
788
+ }
789
+ const defaultProvider = createOpenAICompatible({
790
+ name: providerId,
791
+ apiKey,
792
+ baseURL: baseURL || "",
793
+ includeUsage: true
794
+ });
795
+ return defaultProvider;
796
+ } catch (error) {
797
+ logger.error(`Failed to create provider ${providerId}`, { error: String(error) });
798
+ return null;
799
+ }
800
+ }
801
+ async function invokeNonStream(config, options, ctx) {
802
+ const { providerId, modelId } = parseModelString(options.model || config.model);
803
+ const provider = createProviderInstance(providerId, config.apiKey, config.baseURL);
804
+ if (!provider) {
805
+ throw new Error(`Failed to create provider for ${providerId}`);
806
+ }
807
+ const messages = convertToSDKMessages(options.messages);
808
+ const tools = options.tools && options.tools.length > 0 ? convertToolsToSDK(options.tools) : undefined;
809
+ const providerOptions = generateProviderOptions(providerId, {
810
+ temperature: options.temperature,
811
+ maxTokens: options.maxTokens
812
+ });
813
+ const { generateText } = await import("ai");
814
+ const genTextFn = generateText;
815
+ const result = await genTextFn({
816
+ model: provider.languageModel(modelId),
817
+ messages,
818
+ tools,
819
+ temperature: providerOptions.temperature,
820
+ maxTokens: providerOptions.maxTokens,
821
+ abortSignal: ctx.abort,
822
+ allowSystemInMessages: true
823
+ });
824
+ const usage = result.usage;
825
+ const usageInfo = usage ? {
826
+ promptTokens: usage.promptTokens ?? 0,
827
+ completionTokens: usage.completionTokens ?? 0,
828
+ totalTokens: usage.totalTokens ?? 0
829
+ } : undefined;
830
+ if (options.env) {
831
+ options.env.pushEnvEvent({
832
+ id: randomUUID(),
833
+ type: "llm.completed",
834
+ timestamp: Date.now(),
835
+ metadata: {
836
+ source: "llm.invokeNonStream",
837
+ sessionId: options.context?.sessionId,
838
+ messageId: options.context?.messageId
839
+ },
840
+ payload: {
841
+ type: "completed",
842
+ content: result.text,
843
+ metadata: {
844
+ model: `${providerId}/${modelId}`,
845
+ usage: usageInfo
846
+ }
847
+ }
848
+ });
849
+ }
850
+ return {
851
+ content: result.text,
852
+ finishReason: result.finishReason === "stop" ? "stop" : "tool-calls",
853
+ model: `${providerId}/${modelId}`,
854
+ usage: usageInfo
855
+ };
856
+ }
857
+ function createInvokeConfig(model, apiKey, baseURL) {
858
+ return {
859
+ model,
860
+ apiKey,
861
+ baseURL
862
+ };
863
+ }
864
+ // packages/core/src/env/llm/hooks.ts
865
+ class LLMHookManager {
866
+ registrations = [];
867
+ register(type, handler, name) {
868
+ const registration = {
869
+ type,
870
+ name
871
+ };
872
+ switch (type) {
873
+ case "before-invoke":
874
+ registration.beforeInvoke = handler;
875
+ break;
876
+ case "after-invoke":
877
+ registration.afterInvoke = handler;
878
+ break;
879
+ case "stream":
880
+ registration.stream = handler;
881
+ break;
882
+ }
883
+ this.registrations.push(registration);
884
+ this.registerToGlobal(registration);
885
+ }
886
+ registerToGlobal(reg) {
887
+ const hookName = `llm:${reg.name || `anon-${reg.type}-${this.registrations.indexOf(reg)}`}`;
888
+ if (reg.beforeInvoke) {
889
+ globalHookManager.register(LLMHookPoints.BEFORE_INVOKE, {
890
+ name: hookName,
891
+ priority: 0,
892
+ execute: async (ctx) => {
893
+ await reg.beforeInvoke(ctx.data);
894
+ }
895
+ });
896
+ }
897
+ if (reg.afterInvoke) {
898
+ globalHookManager.register(LLMHookPoints.AFTER_INVOKE, {
899
+ name: hookName,
900
+ priority: 0,
901
+ execute: async (ctx) => {
902
+ const { request, providerId, model, metadata, result } = ctx.data;
903
+ await reg.afterInvoke({ request, providerId, model, metadata }, result);
904
+ }
905
+ });
906
+ }
907
+ if (reg.stream) {
908
+ globalHookManager.register(LLMHookPoints.ON_STREAM, {
909
+ name: hookName,
910
+ priority: 0,
911
+ execute: async (ctx) => {
912
+ const { request, providerId, model, metadata, event } = ctx.data;
913
+ await reg.stream({ request, providerId, model, metadata }, event);
914
+ }
915
+ });
916
+ }
917
+ }
918
+ unregister(hook) {
919
+ const index = this.registrations.findIndex((h) => {
920
+ return h.beforeInvoke === hook || h.afterInvoke === hook || h.stream === hook;
921
+ });
922
+ if (index !== -1) {
923
+ const reg = this.registrations[index];
924
+ this.unregisterFromGlobal(reg);
925
+ this.registrations.splice(index, 1);
926
+ }
927
+ }
928
+ unregisterFromGlobal(reg) {
929
+ const hookName = `llm:${reg.name || `anon-${reg.type}`}`;
930
+ globalHookManager.unregister(LLMHookPoints.BEFORE_INVOKE, hookName);
931
+ globalHookManager.unregister(LLMHookPoints.AFTER_INVOKE, hookName);
932
+ globalHookManager.unregister(LLMHookPoints.ON_STREAM, hookName);
933
+ }
934
+ unregisterByName(name) {
935
+ const hookName = `llm:${name}`;
936
+ globalHookManager.unregister(LLMHookPoints.BEFORE_INVOKE, hookName);
937
+ globalHookManager.unregister(LLMHookPoints.AFTER_INVOKE, hookName);
938
+ globalHookManager.unregister(LLMHookPoints.ON_STREAM, hookName);
939
+ this.registrations = this.registrations.filter((h) => h.name !== name);
940
+ }
941
+ unregisterByType(type) {
942
+ const filtered = this.registrations.filter((h) => h.type === type);
943
+ for (const reg of filtered) {
944
+ this.unregisterFromGlobal(reg);
945
+ }
946
+ this.registrations = this.registrations.filter((h) => h.type !== type);
947
+ }
948
+ clear() {
949
+ for (const reg of this.registrations) {
950
+ this.unregisterFromGlobal(reg);
951
+ }
952
+ this.registrations = [];
953
+ }
954
+ getHooks() {
955
+ return [...this.registrations];
956
+ }
957
+ getHooksByType(type) {
958
+ return this.registrations.filter((h) => h.type === type);
959
+ }
960
+ }
961
+
962
+ class LLMHooks {
963
+ hookManager = new LLMHookManager;
964
+ register(type, handler, name) {
965
+ this.hookManager.register(type, handler, name);
966
+ }
967
+ unregister(hook) {
968
+ this.hookManager.unregister(hook);
969
+ }
970
+ unregisterByName(name) {
971
+ this.hookManager.unregisterByName(name);
972
+ }
973
+ unregisterByType(type) {
974
+ this.hookManager.unregisterByType(type);
975
+ }
976
+ clear() {
977
+ this.hookManager.clear();
978
+ }
979
+ getHooks() {
980
+ return this.hookManager.getHooks();
981
+ }
982
+ getHooksByType(type) {
983
+ return this.hookManager.getHooksByType(type);
984
+ }
985
+ async executeBeforeInvoke(context) {
986
+ await globalHookManager.execute(LLMHookPoints.BEFORE_INVOKE, context);
987
+ }
988
+ async executeAfterInvoke(context, result) {
989
+ await globalHookManager.execute(LLMHookPoints.AFTER_INVOKE, { ...context, result });
990
+ }
991
+ async executeStream(context, event) {
992
+ await globalHookManager.execute(LLMHookPoints.ON_STREAM, { ...context, event });
993
+ }
994
+ }
995
+ // packages/core/src/env/llm/llm.ts
996
+ init_logger();
997
+ init_decorator();
998
+ var logger2 = createLogger("llm");
999
+
1000
+ class LLMComponent extends BaseComponent {
1001
+ name = "llm";
1002
+ version = "2.0.0";
1003
+ configComponent;
1004
+ configWatcher;
1005
+ constructor() {
1006
+ super();
1007
+ }
1008
+ async init(config) {
1009
+ await super.init(config);
1010
+ const options = config.options;
1011
+ if (!options?.configComponent) {
1012
+ throw new Error("ConfigComponent is required for LLMComponent initialization");
1013
+ }
1014
+ this.configComponent = options.configComponent;
1015
+ await this.registerConfig(options);
1016
+ this.setStatus("running");
1017
+ }
1018
+ async registerConfig(options) {
1019
+ const configComponent = options.configComponent;
1020
+ if (!configComponent)
1021
+ return;
1022
+ const { configPath, envPrefix, config } = options;
1023
+ const prefix = envPrefix !== undefined ? envPrefix : "LLM";
1024
+ const llmKeys = [
1025
+ "llm.defaultModel",
1026
+ "llm.defaultProvider",
1027
+ "llm.temperature",
1028
+ "llm.maxTokens",
1029
+ "llm.topP",
1030
+ "llm.stream",
1031
+ "llm.providers",
1032
+ "llm.limits",
1033
+ "llm.capabilities"
1034
+ ];
1035
+ let fileSource = null;
1036
+ if (configPath) {
1037
+ configComponent.registerSource({
1038
+ type: "file",
1039
+ relativePath: configPath,
1040
+ optional: true,
1041
+ watch: false
1042
+ });
1043
+ configComponent.ensureSourcesCreated?.();
1044
+ const sources = configComponent.getSources?.() || [];
1045
+ fileSource = sources.find((s) => s.name === "file");
1046
+ if (fileSource) {
1047
+ for (const key of llmKeys) {
1048
+ const value = fileSource.read?.(key);
1049
+ if (value !== undefined) {
1050
+ await configComponent.set(key, value);
1051
+ }
1052
+ }
1053
+ }
1054
+ }
1055
+ configComponent.registerSource({
1056
+ type: "env",
1057
+ envPrefix: prefix,
1058
+ priority: 20,
1059
+ watch: false
1060
+ });
1061
+ configComponent.ensureSourcesCreated?.();
1062
+ const sourcesAfterEnv = configComponent.getSources?.() || [];
1063
+ const envSource = sourcesAfterEnv.find((s) => s.name === "env");
1064
+ if (envSource) {
1065
+ for (const key of llmKeys) {
1066
+ const value = envSource.read?.(key);
1067
+ if (value !== undefined) {
1068
+ await configComponent.set(key, value);
1069
+ }
1070
+ }
1071
+ }
1072
+ for (const key of llmKeys) {
1073
+ const envKey = toEnvKey(key, prefix);
1074
+ const value = process.env[envKey];
1075
+ if (value !== undefined) {
1076
+ await configComponent.set(key, value);
1077
+ }
1078
+ }
1079
+ const loadedKeys = new Set(llmKeys);
1080
+ for (const envKey of Object.keys(process.env)) {
1081
+ const configKey = envKeyToConfigKey(envKey, prefix, "llm");
1082
+ if (!configKey)
1083
+ continue;
1084
+ if (loadedKeys.has(configKey))
1085
+ continue;
1086
+ loadedKeys.add(configKey);
1087
+ const value = process.env[envKey];
1088
+ if (value !== undefined) {
1089
+ await configComponent.set(configKey, value);
1090
+ }
1091
+ }
1092
+ if (config) {
1093
+ const flatConfig = this.flattenConfig(config);
1094
+ for (const [key, value] of Object.entries(flatConfig)) {
1095
+ await configComponent.set(key, value);
1096
+ }
1097
+ }
1098
+ this.registerConfigWatcher(configComponent);
1099
+ }
1100
+ flattenConfig(obj, prefix = "llm") {
1101
+ const result = {};
1102
+ for (const [key, value] of Object.entries(obj)) {
1103
+ const fullKey = `${prefix}.${key}`;
1104
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1105
+ Object.assign(result, this.flattenConfig(value, fullKey));
1106
+ } else {
1107
+ result[fullKey] = value;
1108
+ }
1109
+ }
1110
+ return result;
1111
+ }
1112
+ registerConfigWatcher(configComponent) {
1113
+ if (typeof configComponent.watch !== "function") {
1114
+ logger2.debug("ConfigComponent does not support watch, hot reload disabled");
1115
+ return;
1116
+ }
1117
+ this.configWatcher = configComponent.watch("llm.*", (event) => {
1118
+ this.onConfigChange(event);
1119
+ });
1120
+ logger2.debug("Config hot reload watcher registered for llm.*");
1121
+ }
1122
+ onConfigChange(event) {
1123
+ logger2.info(`LLM config changed: ${event.key}`);
1124
+ if (event.key === "llm.providers" || event.key.startsWith("llm.providers.")) {
1125
+ logger2.info(`LLM provider config changed, will use new config on next call`);
1126
+ } else if (event.key === "llm.defaultModel") {
1127
+ logger2.info(`LLM default model changed to: ${event.newValue}`);
1128
+ } else if (event.key === "llm.defaultProvider") {
1129
+ logger2.info(`LLM default provider changed to: ${event.newValue}`);
1130
+ } else {
1131
+ logger2.debug(`LLM config updated: ${event.key}`);
1132
+ }
1133
+ }
1134
+ async onStart() {
1135
+ if (this._status === "stopped") {
1136
+ this.setStatus("running");
1137
+ }
1138
+ }
1139
+ async onStop() {
1140
+ this.configWatcher?.();
1141
+ this.configWatcher = undefined;
1142
+ this.setStatus("stopped");
1143
+ }
1144
+ getLLMConfig(key, defaultValue) {
1145
+ if (this.configComponent) {
1146
+ const value = this.configComponent.get(key);
1147
+ if (value !== undefined) {
1148
+ return value;
1149
+ }
1150
+ }
1151
+ return defaultValue;
1152
+ }
1153
+ resolveRequest(request) {
1154
+ const defaultModel = this.getLLMConfig("llm.defaultModel", "gpt-4o");
1155
+ const defaultProvider = this.getLLMConfig("llm.defaultProvider", "openai");
1156
+ const defaultTemperature = this.getLLMConfig("llm.temperature", 0.7);
1157
+ const defaultMaxTokens = this.getLLMConfig("llm.maxTokens", 4096);
1158
+ const defaultTopP = this.getLLMConfig("llm.topP", 1);
1159
+ const model = request.model || defaultModel;
1160
+ const providerId = request.providerId || defaultProvider;
1161
+ const apiKey = this.getApiKey(providerId);
1162
+ if (!apiKey) {
1163
+ throw new Error(`API key not found for provider ${providerId}. Set providers.${providerId}.apiKey in config, or use \${env://...} protocol in config file.`);
1164
+ }
1165
+ const messages = request.messages.map((msg) => ({
1166
+ role: msg.role,
1167
+ content: msg.content,
1168
+ name: msg.name,
1169
+ toolCallId: msg.toolCallId,
1170
+ toolCalls: msg.toolCalls
1171
+ }));
1172
+ return {
1173
+ providerId,
1174
+ model,
1175
+ invokeConfig: {
1176
+ model: `${providerId}/${model}`,
1177
+ apiKey,
1178
+ baseURL: this.getProvider(providerId)?.baseURL
1179
+ },
1180
+ messages,
1181
+ temperature: request.temperature ?? defaultTemperature,
1182
+ maxTokens: request.maxTokens ?? defaultMaxTokens,
1183
+ topP: request.topP ?? defaultTopP,
1184
+ abortSignal: request.abortSignal
1185
+ };
1186
+ }
1187
+ async invoke(request) {
1188
+ const startTime = Date.now();
1189
+ if (this._status !== "running") {
1190
+ throw new Error("LLMComponent is not running");
1191
+ }
1192
+ const ctx = this.resolveRequest(request);
1193
+ let output = {
1194
+ content: "",
1195
+ reasoning: undefined,
1196
+ finishReason: "stop"
1197
+ };
1198
+ let finishUsage;
1199
+ const result = await invoke(ctx.invokeConfig, {
1200
+ messages: ctx.messages,
1201
+ model: ctx.invokeConfig.model,
1202
+ temperature: ctx.temperature,
1203
+ maxTokens: ctx.maxTokens,
1204
+ tools: request.tools,
1205
+ env: this.env,
1206
+ context: {
1207
+ sessionId: request.context?.sessionId,
1208
+ messageId: request.context?.messageId
1209
+ }
1210
+ }, { abort: ctx.abortSignal });
1211
+ if (result.isError) {
1212
+ throw new Error(result.result);
1213
+ }
1214
+ try {
1215
+ const parsed = JSON.parse(result.result);
1216
+ output.content = parsed.content || "";
1217
+ output.reasoning = parsed.reasoning || undefined;
1218
+ output.finishReason = parsed.tool_calls?.length ? "tool-calls" : "stop";
1219
+ output.toolCalls = parsed.tool_calls || [];
1220
+ if (parsed.usage) {
1221
+ finishUsage = {
1222
+ promptTokens: parsed.usage.promptTokens ?? parsed.usage.inputTokens ?? 0,
1223
+ completionTokens: parsed.usage.completionTokens ?? parsed.usage.outputTokens ?? 0,
1224
+ totalTokens: parsed.usage.totalTokens ?? 0
1225
+ };
1226
+ }
1227
+ output.usage = finishUsage;
1228
+ } catch {
1229
+ output.content = result.result;
1230
+ output.finishReason = "stop";
1231
+ }
1232
+ const latencyMs = Date.now() - startTime;
1233
+ if (!request.skipThresholdCheck) {
1234
+ const sessionId = request.context?.sessionId;
1235
+ const contextError = this.checkContextThreshold(finishUsage, ctx.providerId, ctx.model, sessionId);
1236
+ if (contextError) {
1237
+ contextError.llmOutput = {
1238
+ content: output.content,
1239
+ reasoning: output.reasoning,
1240
+ toolCalls: output.toolCalls,
1241
+ usage: output.usage
1242
+ };
1243
+ throw contextError;
1244
+ }
1245
+ }
1246
+ return {
1247
+ output,
1248
+ providerId: ctx.providerId,
1249
+ model: ctx.model,
1250
+ latencyMs
1251
+ };
1252
+ }
1253
+ getApiKey(providerId) {
1254
+ const providers = this.getLLMConfig("llm.providers", {});
1255
+ return providers?.[providerId]?.apiKey;
1256
+ }
1257
+ getProvider(id) {
1258
+ const providers = this.getLLMConfig("llm.providers", {});
1259
+ return providers?.[id];
1260
+ }
1261
+ listProviders() {
1262
+ const providers = this.getLLMConfig("llm.providers", {});
1263
+ return Object.keys(providers || {});
1264
+ }
1265
+ getModelLimits(providerId, modelId) {
1266
+ const provider = this.getProvider(providerId);
1267
+ if (!provider?.limits)
1268
+ return;
1269
+ const targetModel = modelId || provider.defaultModel;
1270
+ if (!targetModel)
1271
+ return;
1272
+ return provider.limits[targetModel];
1273
+ }
1274
+ getContextThresholdConfig(providerId, modelId) {
1275
+ const defaults = {
1276
+ contextWindow: 128000,
1277
+ thresholdRatio: 0.9
1278
+ };
1279
+ const limits = this.getModelLimits(providerId, modelId);
1280
+ if (!limits)
1281
+ return defaults;
1282
+ return {
1283
+ contextWindow: limits.contextWindow || defaults.contextWindow,
1284
+ thresholdRatio: limits.compactionThreshold ?? defaults.thresholdRatio
1285
+ };
1286
+ }
1287
+ checkContextThreshold(usage, providerId, modelId, sessionId) {
1288
+ if (!usage)
1289
+ return;
1290
+ const config = this.getContextThresholdConfig(providerId, modelId);
1291
+ const threshold = config.contextWindow * config.thresholdRatio;
1292
+ if (usage.totalTokens >= threshold) {
1293
+ return new ContextError(`Context threshold exceeded: ${usage.totalTokens}/${config.contextWindow} (${(usage.totalTokens / config.contextWindow * 100).toFixed(1)}%)`, ErrorCodes.CONTEXT_THRESHOLD_EXCEEDED, sessionId, {
1294
+ promptTokens: usage.promptTokens ?? 0,
1295
+ completionTokens: usage.completionTokens ?? 0,
1296
+ totalTokens: usage.totalTokens
1297
+ }, config.contextWindow);
1298
+ }
1299
+ return;
1300
+ }
1301
+ }
1302
+ __legacyDecorateClassTS([
1303
+ TracedAs("llm.component.invoke", { recordParams: true, recordResult: true, log: true })
1304
+ ], LLMComponent.prototype, "invoke", null);
1305
+ export { ProviderCapabilitiesSchema, ModelLimitsSchema, ProviderConfigSchema, LLMDefaultConfigSchema, LLMConfigSchema, ProviderManager, LLMTransform, parseModelString, invoke, invokeNonStream, createInvokeConfig, LLMHooks, LLMComponent };