@ai-setting/roy-agent-core 1.5.52 → 1.5.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/env/agent/index.js +2 -1
- package/dist/env/index.js +6 -5
- package/dist/env/llm/index.js +4 -2
- package/dist/env/task/delegate/index.js +1 -1
- package/dist/env/task/index.js +2 -2
- package/dist/env/tool/built-in/index.js +1 -1
- package/dist/env/tool/index.js +2 -2
- package/dist/env/workflow/engine/index.js +1 -1
- package/dist/env/workflow/index.js +2 -2
- package/dist/index.js +15 -13
- package/dist/shared/@ai-setting/{roy-agent-core-smwwze1m.js → roy-agent-core-0vt0trev.js} +1 -1
- package/dist/shared/@ai-setting/roy-agent-core-4ch3ghj6.js +610 -0
- package/dist/shared/@ai-setting/{roy-agent-core-ysvh8er9.js → roy-agent-core-bwrzwq5x.js} +10 -0
- package/dist/shared/@ai-setting/{roy-agent-core-wbqmmavh.js → roy-agent-core-fwq0hs6e.js} +1 -1
- package/dist/shared/@ai-setting/{roy-agent-core-4mw6rs37.js → roy-agent-core-g7qhnsz3.js} +28 -3
- package/dist/shared/@ai-setting/{roy-agent-core-ct95gkee.js → roy-agent-core-hv713d36.js} +13 -586
- package/dist/shared/@ai-setting/{roy-agent-core-rmndq0sb.js → roy-agent-core-jkhhsa3t.js} +13 -6
- package/dist/shared/@ai-setting/{roy-agent-core-vehgmfj1.js → roy-agent-core-nfa6fc3a.js} +2 -2
- package/package.json +1 -1
- /package/dist/shared/@ai-setting/{roy-agent-core-4hk6ey73.js → roy-agent-core-nt1q2g91.js} +0 -0
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
invoke
|
|
3
|
+
} from "./roy-agent-core-4ch3ghj6.js";
|
|
1
4
|
import {
|
|
2
5
|
ContextError,
|
|
3
6
|
ErrorCodes
|
|
@@ -23,8 +26,7 @@ import {
|
|
|
23
26
|
init_logger
|
|
24
27
|
} from "./roy-agent-core-10n2jh7p.js";
|
|
25
28
|
import {
|
|
26
|
-
__legacyDecorateClassTS
|
|
27
|
-
__require
|
|
29
|
+
__legacyDecorateClassTS
|
|
28
30
|
} from "./roy-agent-core-fs0mn2jk.js";
|
|
29
31
|
|
|
30
32
|
// src/env/llm/types.ts
|
|
@@ -309,581 +311,6 @@ class LLMTransform {
|
|
|
309
311
|
return JSON.stringify(args);
|
|
310
312
|
}
|
|
311
313
|
}
|
|
312
|
-
// src/env/llm/invoke.ts
|
|
313
|
-
init_logger();
|
|
314
|
-
import { randomUUID } from "crypto";
|
|
315
|
-
import { streamText, jsonSchema } from "ai";
|
|
316
|
-
import { createOpenAI } from "@ai-sdk/openai";
|
|
317
|
-
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
318
|
-
import { createGoogleGenerativeAI } from "@ai-sdk/google";
|
|
319
|
-
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
320
|
-
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
321
|
-
var logger = createLogger("llm:invoke");
|
|
322
|
-
var MAX_RETRIES = 3;
|
|
323
|
-
function parseModelString(model) {
|
|
324
|
-
if (!model) {
|
|
325
|
-
return { providerId: "openai", modelId: "gpt-4o" };
|
|
326
|
-
}
|
|
327
|
-
const parts = model.split("/");
|
|
328
|
-
if (parts.length >= 2) {
|
|
329
|
-
return { providerId: parts[0], modelId: parts.slice(1).join("/") };
|
|
330
|
-
}
|
|
331
|
-
return { providerId: "openai", modelId: model };
|
|
332
|
-
}
|
|
333
|
-
function extractUsageInfo(usage) {
|
|
334
|
-
if (!usage)
|
|
335
|
-
return;
|
|
336
|
-
if (usage.inputTokens && typeof usage.inputTokens === "object") {
|
|
337
|
-
return {
|
|
338
|
-
promptTokens: usage.inputTokens.total ?? 0,
|
|
339
|
-
completionTokens: usage.outputTokens?.total ?? 0,
|
|
340
|
-
totalTokens: usage.totalTokens ?? 0
|
|
341
|
-
};
|
|
342
|
-
}
|
|
343
|
-
if (typeof usage.promptTokens === "number") {
|
|
344
|
-
return {
|
|
345
|
-
promptTokens: usage.promptTokens,
|
|
346
|
-
completionTokens: usage.completionTokens ?? 0,
|
|
347
|
-
totalTokens: usage.totalTokens ?? 0
|
|
348
|
-
};
|
|
349
|
-
}
|
|
350
|
-
if (usage.inputTokenDetails || usage.outputTokenDetails) {
|
|
351
|
-
return {
|
|
352
|
-
promptTokens: usage.inputTokenDetails?.tokens ?? 0,
|
|
353
|
-
completionTokens: usage.outputTokenDetails?.tokens ?? 0,
|
|
354
|
-
totalTokens: usage.totalTokens ?? 0
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
if (usage.raw && typeof usage.raw.total_tokens === "number") {
|
|
358
|
-
return {
|
|
359
|
-
promptTokens: 0,
|
|
360
|
-
completionTokens: 0,
|
|
361
|
-
totalTokens: usage.raw.total_tokens
|
|
362
|
-
};
|
|
363
|
-
}
|
|
364
|
-
return;
|
|
365
|
-
}
|
|
366
|
-
function convertToSDKMessages(messages) {
|
|
367
|
-
return messages.map((msg) => {
|
|
368
|
-
if (msg.role === "assistant" && msg.toolCalls && msg.toolCalls.length > 0) {
|
|
369
|
-
const toolCallParts = msg.toolCalls.map((tc) => {
|
|
370
|
-
let input = {};
|
|
371
|
-
if (tc.function?.arguments) {
|
|
372
|
-
if (typeof tc.function.arguments === "string") {
|
|
373
|
-
try {
|
|
374
|
-
const parsed = JSON.parse(tc.function.arguments);
|
|
375
|
-
input = typeof parsed === "string" ? { _raw: parsed } : parsed;
|
|
376
|
-
} catch {
|
|
377
|
-
input = { _raw: tc.function.arguments };
|
|
378
|
-
}
|
|
379
|
-
} else {
|
|
380
|
-
input = tc.function.arguments;
|
|
381
|
-
}
|
|
382
|
-
} else if (tc.arguments) {
|
|
383
|
-
if (typeof tc.arguments === "string") {
|
|
384
|
-
try {
|
|
385
|
-
const parsed = JSON.parse(tc.arguments);
|
|
386
|
-
input = typeof parsed === "string" ? { _raw: parsed } : parsed;
|
|
387
|
-
} catch {
|
|
388
|
-
input = { _raw: tc.arguments };
|
|
389
|
-
}
|
|
390
|
-
} else {
|
|
391
|
-
input = tc.arguments;
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
return {
|
|
395
|
-
type: "tool-call",
|
|
396
|
-
toolCallId: tc.id,
|
|
397
|
-
toolName: tc.function?.name || tc.name || "unknown",
|
|
398
|
-
input
|
|
399
|
-
};
|
|
400
|
-
});
|
|
401
|
-
return {
|
|
402
|
-
role: "assistant",
|
|
403
|
-
content: toolCallParts
|
|
404
|
-
};
|
|
405
|
-
}
|
|
406
|
-
if (msg.role === "tool") {
|
|
407
|
-
if (!msg.toolCallId) {
|
|
408
|
-
logger.warn("Tool message missing toolCallId", { msg });
|
|
409
|
-
}
|
|
410
|
-
let outputValue = "";
|
|
411
|
-
const content = msg.content;
|
|
412
|
-
if (typeof content === "string") {
|
|
413
|
-
outputValue = content;
|
|
414
|
-
} else if (Array.isArray(content)) {
|
|
415
|
-
const toolResultPart = content.find((p) => p?.type === "tool-result");
|
|
416
|
-
if (toolResultPart) {
|
|
417
|
-
outputValue = typeof toolResultPart.output === "string" ? toolResultPart.output : JSON.stringify(toolResultPart.output);
|
|
418
|
-
} else {
|
|
419
|
-
outputValue = JSON.stringify(content);
|
|
420
|
-
}
|
|
421
|
-
} else {
|
|
422
|
-
outputValue = JSON.stringify(content);
|
|
423
|
-
}
|
|
424
|
-
const converted = {
|
|
425
|
-
role: "tool",
|
|
426
|
-
content: [{
|
|
427
|
-
type: "tool-result",
|
|
428
|
-
toolCallId: msg.toolCallId || "unknown",
|
|
429
|
-
toolName: msg.name || "unknown",
|
|
430
|
-
output: {
|
|
431
|
-
type: "text",
|
|
432
|
-
value: outputValue
|
|
433
|
-
}
|
|
434
|
-
}]
|
|
435
|
-
};
|
|
436
|
-
return converted;
|
|
437
|
-
}
|
|
438
|
-
return msg;
|
|
439
|
-
});
|
|
440
|
-
}
|
|
441
|
-
function convertToolsToSDK(tools) {
|
|
442
|
-
const result = {};
|
|
443
|
-
for (const tool of tools) {
|
|
444
|
-
const jsonSchemaObj = extractToolSchema(tool.parameters);
|
|
445
|
-
result[tool.name] = {
|
|
446
|
-
description: tool.description || "",
|
|
447
|
-
inputSchema: jsonSchema(jsonSchemaObj)
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
return result;
|
|
451
|
-
}
|
|
452
|
-
function extractToolSchema(parameters) {
|
|
453
|
-
if (parameters && typeof parameters === "object" && "_def" in parameters) {
|
|
454
|
-
const zodSchema = parameters;
|
|
455
|
-
const schema = zodToJsonSchema(zodSchema, "zod");
|
|
456
|
-
if ("$ref" in schema && schema.definitions) {
|
|
457
|
-
const def = schema.definitions.zod;
|
|
458
|
-
if (def && def.type === "object" && def.properties) {
|
|
459
|
-
return {
|
|
460
|
-
type: "object",
|
|
461
|
-
properties: def.properties,
|
|
462
|
-
required: def.required,
|
|
463
|
-
additionalProperties: true
|
|
464
|
-
};
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
return schema;
|
|
468
|
-
}
|
|
469
|
-
return parameters;
|
|
470
|
-
}
|
|
471
|
-
function generateProviderOptions(providerType, options) {
|
|
472
|
-
const result = {
|
|
473
|
-
providerOptions: {}
|
|
474
|
-
};
|
|
475
|
-
if (options.temperature !== undefined) {
|
|
476
|
-
result.temperature = options.temperature;
|
|
477
|
-
}
|
|
478
|
-
if (options.maxTokens !== undefined) {
|
|
479
|
-
result.maxTokens = options.maxTokens;
|
|
480
|
-
}
|
|
481
|
-
switch (providerType) {
|
|
482
|
-
case "anthropic":
|
|
483
|
-
break;
|
|
484
|
-
case "openai-compatible":
|
|
485
|
-
result.providerOptions.includeUsage = true;
|
|
486
|
-
break;
|
|
487
|
-
}
|
|
488
|
-
return result;
|
|
489
|
-
}
|
|
490
|
-
function createEnvEventEmitter(env, context) {
|
|
491
|
-
if (!env) {
|
|
492
|
-
logger.warn("[invoke] createEnvEventEmitter: env is null/undefined, streaming events will be disabled");
|
|
493
|
-
return null;
|
|
494
|
-
}
|
|
495
|
-
return (event) => {
|
|
496
|
-
try {
|
|
497
|
-
const fullType = `llm.${event.type}`;
|
|
498
|
-
logger.info(`[invoke] Pushing LLM event: ${fullType}`, {
|
|
499
|
-
hasPayload: !!event,
|
|
500
|
-
payloadType: typeof event
|
|
501
|
-
});
|
|
502
|
-
env.pushEnvEvent({
|
|
503
|
-
id: randomUUID(),
|
|
504
|
-
type: fullType,
|
|
505
|
-
timestamp: Date.now(),
|
|
506
|
-
metadata: {
|
|
507
|
-
source: "llm.invoke",
|
|
508
|
-
sessionId: context?.sessionId,
|
|
509
|
-
messageId: context?.messageId
|
|
510
|
-
},
|
|
511
|
-
payload: event
|
|
512
|
-
});
|
|
513
|
-
logger.info(`[invoke] LLM event pushed successfully: ${fullType}`);
|
|
514
|
-
} catch (err) {
|
|
515
|
-
logger.warn("Failed to push env event", { error: String(err), eventType: event.type });
|
|
516
|
-
}
|
|
517
|
-
};
|
|
518
|
-
}
|
|
519
|
-
function getStreamPartText(part) {
|
|
520
|
-
const value = part.text ?? part.delta ?? part.textDelta;
|
|
521
|
-
return typeof value === "string" ? value : "";
|
|
522
|
-
}
|
|
523
|
-
function processThinkingStream(textDelta, config, state) {
|
|
524
|
-
if (!config.enabled || !textDelta) {
|
|
525
|
-
return {
|
|
526
|
-
cleanedText: textDelta,
|
|
527
|
-
isThinkingTagOpen: state.isOpen,
|
|
528
|
-
currentThinkingContent: state.content,
|
|
529
|
-
reasoningEvents: []
|
|
530
|
-
};
|
|
531
|
-
}
|
|
532
|
-
const tags = config.tags || ["thinking"];
|
|
533
|
-
let remainingText = textDelta;
|
|
534
|
-
const reasoningEvents2 = [];
|
|
535
|
-
let isOpen2 = state.isOpen;
|
|
536
|
-
let currentContent2 = state.content;
|
|
537
|
-
for (const tag of tags) {
|
|
538
|
-
const openTag = `<${tag}>`;
|
|
539
|
-
const closeTag = `</${tag}>`;
|
|
540
|
-
let text = remainingText;
|
|
541
|
-
let result = "";
|
|
542
|
-
const openIndex = text.toLowerCase().indexOf(openTag.toLowerCase());
|
|
543
|
-
const closeIndex = text.toLowerCase().indexOf(closeTag.toLowerCase());
|
|
544
|
-
if (openIndex !== -1 && (closeIndex === -1 || openIndex < closeIndex)) {
|
|
545
|
-
const beforeOpen = text.substring(0, openIndex);
|
|
546
|
-
const afterOpen = text.substring(openIndex + openTag.length);
|
|
547
|
-
if (!isOpen2) {
|
|
548
|
-
isOpen2 = true;
|
|
549
|
-
currentContent2 = "";
|
|
550
|
-
reasoningEvents2.push("");
|
|
551
|
-
}
|
|
552
|
-
result += beforeOpen;
|
|
553
|
-
const innerCloseIndex = afterOpen.toLowerCase().indexOf(closeTag.toLowerCase());
|
|
554
|
-
if (innerCloseIndex !== -1) {
|
|
555
|
-
const thinkingContent = afterOpen.substring(0, innerCloseIndex);
|
|
556
|
-
const afterClose = afterOpen.substring(innerCloseIndex + closeTag.length);
|
|
557
|
-
currentContent2 += thinkingContent;
|
|
558
|
-
reasoningEvents2.push(currentContent2);
|
|
559
|
-
isOpen2 = false;
|
|
560
|
-
currentContent2 = "";
|
|
561
|
-
result += afterClose;
|
|
562
|
-
} else {
|
|
563
|
-
currentContent2 += afterOpen;
|
|
564
|
-
reasoningEvents2.push(currentContent2);
|
|
565
|
-
result += "";
|
|
566
|
-
}
|
|
567
|
-
remainingText = result;
|
|
568
|
-
} else if (closeIndex !== -1) {
|
|
569
|
-
const beforeClose = text.substring(0, closeIndex);
|
|
570
|
-
const afterClose = text.substring(closeIndex + closeTag.length);
|
|
571
|
-
if (isOpen2) {
|
|
572
|
-
currentContent2 += beforeClose;
|
|
573
|
-
reasoningEvents2.push(currentContent2);
|
|
574
|
-
isOpen2 = false;
|
|
575
|
-
currentContent2 = "";
|
|
576
|
-
result = afterClose;
|
|
577
|
-
} else {
|
|
578
|
-
result = text;
|
|
579
|
-
}
|
|
580
|
-
remainingText = result;
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
if (isOpen2 && remainingText === textDelta) {
|
|
584
|
-
currentContent2 += remainingText;
|
|
585
|
-
reasoningEvents2.push(currentContent2);
|
|
586
|
-
remainingText = "";
|
|
587
|
-
}
|
|
588
|
-
return {
|
|
589
|
-
cleanedText: remainingText,
|
|
590
|
-
isThinkingTagOpen: isOpen2,
|
|
591
|
-
currentThinkingContent: currentContent2,
|
|
592
|
-
reasoningEvents: reasoningEvents2
|
|
593
|
-
};
|
|
594
|
-
}
|
|
595
|
-
async function invoke(config, options, ctx) {
|
|
596
|
-
try {
|
|
597
|
-
const emitToEnv = createEnvEventEmitter(options.env, options.context);
|
|
598
|
-
logger.info("[invoke] Created event emitter, env available:", !!options.env, "context:", options.context);
|
|
599
|
-
const { providerId, modelId } = parseModelString(options.model || config.model);
|
|
600
|
-
const provider = createProviderInstance(providerId, config.apiKey, config.baseURL);
|
|
601
|
-
if (!provider) {
|
|
602
|
-
throw new Error(`Failed to create provider for ${providerId}`);
|
|
603
|
-
}
|
|
604
|
-
const messages = convertToSDKMessages(options.messages);
|
|
605
|
-
const toolCallIds = new Set;
|
|
606
|
-
const assistantToolCalls = [];
|
|
607
|
-
const toolResultIds = [];
|
|
608
|
-
for (const msg of messages) {
|
|
609
|
-
if (msg.role === "assistant") {
|
|
610
|
-
const assistantContent = Array.isArray(msg.content) ? msg.content : [];
|
|
611
|
-
for (const part of assistantContent) {
|
|
612
|
-
if (part && typeof part === "object" && part.type === "tool-call") {
|
|
613
|
-
const tc = part.toolCall || part;
|
|
614
|
-
assistantToolCalls.push({ id: tc.id, name: tc.name || tc.function && tc.function.name });
|
|
615
|
-
toolCallIds.add(tc.id);
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
if (msg.role === "tool") {
|
|
620
|
-
const toolContent = Array.isArray(msg.content) ? msg.content : [];
|
|
621
|
-
for (const part of toolContent) {
|
|
622
|
-
if (part && typeof part === "object" && part.type === "tool-result") {
|
|
623
|
-
toolResultIds.push(part.toolCallId);
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
const missingToolResults = assistantToolCalls.filter((tc) => !toolResultIds.includes(tc.id));
|
|
629
|
-
const orphanedToolResults = toolResultIds.filter((id) => !toolCallIds.has(id));
|
|
630
|
-
if (assistantToolCalls.length > 0 || toolResultIds.length > 0) {
|
|
631
|
-
logger.debug("[invoke] ToolCallId matching analysis:", {
|
|
632
|
-
assistantToolCalls,
|
|
633
|
-
toolResultIds,
|
|
634
|
-
missingToolResults: missingToolResults.length > 0 ? missingToolResults : "none",
|
|
635
|
-
orphanedToolResults: orphanedToolResults.length > 0 ? orphanedToolResults : "none"
|
|
636
|
-
});
|
|
637
|
-
}
|
|
638
|
-
const tools = options.tools && options.tools.length > 0 ? convertToolsToSDK(options.tools) : undefined;
|
|
639
|
-
const providerOptions = generateProviderOptions(providerId, {
|
|
640
|
-
temperature: options.temperature,
|
|
641
|
-
maxTokens: options.maxTokens
|
|
642
|
-
});
|
|
643
|
-
const model = `${providerId}/${modelId}`;
|
|
644
|
-
if (emitToEnv) {
|
|
645
|
-
logger.info("[invoke] Emitting llm.start event");
|
|
646
|
-
emitToEnv({ type: "start", metadata: { model } });
|
|
647
|
-
} else {
|
|
648
|
-
logger.warn("[invoke] emitToEnv is null, skipping llm.start event");
|
|
649
|
-
}
|
|
650
|
-
const streamTextOptions = {
|
|
651
|
-
model: provider.languageModel(modelId),
|
|
652
|
-
messages,
|
|
653
|
-
tools,
|
|
654
|
-
temperature: providerOptions.temperature,
|
|
655
|
-
maxTokens: providerOptions.maxTokens,
|
|
656
|
-
abortSignal: ctx.abort,
|
|
657
|
-
maxRetries: MAX_RETRIES,
|
|
658
|
-
streamOptions: {
|
|
659
|
-
includeUsage: true
|
|
660
|
-
},
|
|
661
|
-
allowSystemInMessages: true
|
|
662
|
-
};
|
|
663
|
-
const result = await streamText(streamTextOptions);
|
|
664
|
-
let fullContent = "";
|
|
665
|
-
let reasoningContent = "";
|
|
666
|
-
const toolCalls = [];
|
|
667
|
-
let usageInfo;
|
|
668
|
-
let isThinkingTagOpen = false;
|
|
669
|
-
let currentThinkingContent = "";
|
|
670
|
-
for await (const part of result.fullStream) {
|
|
671
|
-
const streamPart = part;
|
|
672
|
-
switch (streamPart.type) {
|
|
673
|
-
case "text-delta": {
|
|
674
|
-
const textDelta = getStreamPartText(streamPart);
|
|
675
|
-
if (!textDelta)
|
|
676
|
-
break;
|
|
677
|
-
const thinkingConfig = config.options?.thinkingInText;
|
|
678
|
-
if (thinkingConfig?.enabled) {
|
|
679
|
-
const thinkingResult = processThinkingStream(textDelta, thinkingConfig, {
|
|
680
|
-
isOpen: isThinkingTagOpen,
|
|
681
|
-
content: currentThinkingContent
|
|
682
|
-
});
|
|
683
|
-
isThinkingTagOpen = thinkingResult.isThinkingTagOpen;
|
|
684
|
-
currentThinkingContent = thinkingResult.currentThinkingContent;
|
|
685
|
-
fullContent += thinkingResult.cleanedText;
|
|
686
|
-
for (const reasoningSnapshot of thinkingResult.reasoningEvents) {
|
|
687
|
-
const delta = reasoningSnapshot.slice(reasoningContent.length);
|
|
688
|
-
reasoningContent = reasoningSnapshot;
|
|
689
|
-
if (emitToEnv && delta) {
|
|
690
|
-
emitToEnv({ type: "reasoning", content: reasoningContent, delta });
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
if (emitToEnv && thinkingResult.cleanedText) {
|
|
694
|
-
emitToEnv({ type: "text", content: fullContent, delta: thinkingResult.cleanedText });
|
|
695
|
-
}
|
|
696
|
-
} else {
|
|
697
|
-
fullContent += textDelta;
|
|
698
|
-
if (emitToEnv) {
|
|
699
|
-
emitToEnv({ type: "text", content: fullContent, delta: textDelta });
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
break;
|
|
703
|
-
}
|
|
704
|
-
case "reasoning-delta": {
|
|
705
|
-
const reasoningDelta = getStreamPartText(streamPart);
|
|
706
|
-
if (!reasoningDelta)
|
|
707
|
-
break;
|
|
708
|
-
reasoningContent += reasoningDelta;
|
|
709
|
-
if (emitToEnv) {
|
|
710
|
-
emitToEnv({ type: "reasoning", content: reasoningContent, delta: reasoningDelta });
|
|
711
|
-
}
|
|
712
|
-
break;
|
|
713
|
-
}
|
|
714
|
-
case "reasoning-end":
|
|
715
|
-
break;
|
|
716
|
-
case "tool-call": {
|
|
717
|
-
const toolInput = streamPart.input;
|
|
718
|
-
const toolCallId = streamPart.toolCallId ?? streamPart.id;
|
|
719
|
-
const toolName = streamPart.toolName;
|
|
720
|
-
toolCalls.push({
|
|
721
|
-
id: toolCallId,
|
|
722
|
-
name: toolName,
|
|
723
|
-
args: toolInput
|
|
724
|
-
});
|
|
725
|
-
break;
|
|
726
|
-
}
|
|
727
|
-
case "finish-step":
|
|
728
|
-
const stepUsage = extractUsageInfo(streamPart.usage);
|
|
729
|
-
if (stepUsage) {
|
|
730
|
-
usageInfo = stepUsage;
|
|
731
|
-
}
|
|
732
|
-
break;
|
|
733
|
-
case "error":
|
|
734
|
-
throw streamPart.error;
|
|
735
|
-
case "finish":
|
|
736
|
-
usageInfo = extractUsageInfo(streamPart.totalUsage);
|
|
737
|
-
if (!usageInfo && streamPart.usage) {
|
|
738
|
-
usageInfo = extractUsageInfo(streamPart.usage);
|
|
739
|
-
}
|
|
740
|
-
break;
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
if (emitToEnv) {
|
|
744
|
-
emitToEnv({
|
|
745
|
-
type: "completed",
|
|
746
|
-
content: fullContent,
|
|
747
|
-
metadata: {
|
|
748
|
-
model,
|
|
749
|
-
usage: usageInfo
|
|
750
|
-
}
|
|
751
|
-
});
|
|
752
|
-
}
|
|
753
|
-
if (toolCalls.length > 0) {
|
|
754
|
-
const firstToolCall = toolCalls[0];
|
|
755
|
-
return {
|
|
756
|
-
toolCallId: firstToolCall.id,
|
|
757
|
-
result: JSON.stringify({
|
|
758
|
-
content: fullContent,
|
|
759
|
-
reasoning: reasoningContent || undefined,
|
|
760
|
-
tool_calls: toolCalls.map((tc) => ({
|
|
761
|
-
id: tc.id,
|
|
762
|
-
function: {
|
|
763
|
-
name: tc.name,
|
|
764
|
-
arguments: JSON.stringify(tc.args)
|
|
765
|
-
}
|
|
766
|
-
}))
|
|
767
|
-
})
|
|
768
|
-
};
|
|
769
|
-
}
|
|
770
|
-
return {
|
|
771
|
-
toolCallId: "invoke-" + Date.now(),
|
|
772
|
-
result: JSON.stringify({
|
|
773
|
-
content: fullContent,
|
|
774
|
-
reasoning: reasoningContent || undefined,
|
|
775
|
-
usage: usageInfo,
|
|
776
|
-
model
|
|
777
|
-
})
|
|
778
|
-
};
|
|
779
|
-
} catch (error) {
|
|
780
|
-
logger.error("Error during invocation", {
|
|
781
|
-
error: error instanceof Error ? error.message : String(error),
|
|
782
|
-
stack: error instanceof Error ? error.stack : undefined
|
|
783
|
-
});
|
|
784
|
-
return {
|
|
785
|
-
toolCallId: "error-" + Date.now(),
|
|
786
|
-
result: error instanceof Error ? error.message : String(error),
|
|
787
|
-
isError: true
|
|
788
|
-
};
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
function createProviderInstance(providerId, apiKey, baseURL) {
|
|
792
|
-
try {
|
|
793
|
-
if (providerId === "openai") {
|
|
794
|
-
const openai = createOpenAI({
|
|
795
|
-
apiKey,
|
|
796
|
-
baseURL
|
|
797
|
-
});
|
|
798
|
-
return openai;
|
|
799
|
-
}
|
|
800
|
-
if (providerId === "anthropic") {
|
|
801
|
-
const anthropic = createAnthropic({
|
|
802
|
-
apiKey
|
|
803
|
-
});
|
|
804
|
-
return anthropic;
|
|
805
|
-
}
|
|
806
|
-
if (providerId === "google") {
|
|
807
|
-
const google = createGoogleGenerativeAI({
|
|
808
|
-
apiKey
|
|
809
|
-
});
|
|
810
|
-
return google;
|
|
811
|
-
}
|
|
812
|
-
const defaultProvider = createOpenAICompatible({
|
|
813
|
-
name: providerId,
|
|
814
|
-
apiKey,
|
|
815
|
-
baseURL: baseURL || "",
|
|
816
|
-
includeUsage: true
|
|
817
|
-
});
|
|
818
|
-
return defaultProvider;
|
|
819
|
-
} catch (error) {
|
|
820
|
-
logger.error(`Failed to create provider ${providerId}`, { error: String(error) });
|
|
821
|
-
return null;
|
|
822
|
-
}
|
|
823
|
-
}
|
|
824
|
-
async function invokeNonStream(config, options, ctx) {
|
|
825
|
-
const { providerId, modelId } = parseModelString(options.model || config.model);
|
|
826
|
-
const provider = createProviderInstance(providerId, config.apiKey, config.baseURL);
|
|
827
|
-
if (!provider) {
|
|
828
|
-
throw new Error(`Failed to create provider for ${providerId}`);
|
|
829
|
-
}
|
|
830
|
-
const messages = convertToSDKMessages(options.messages);
|
|
831
|
-
const tools = options.tools && options.tools.length > 0 ? convertToolsToSDK(options.tools) : undefined;
|
|
832
|
-
const providerOptions = generateProviderOptions(providerId, {
|
|
833
|
-
temperature: options.temperature,
|
|
834
|
-
maxTokens: options.maxTokens
|
|
835
|
-
});
|
|
836
|
-
const { generateText } = await import("ai");
|
|
837
|
-
const genTextFn = generateText;
|
|
838
|
-
const result = await genTextFn({
|
|
839
|
-
model: provider.languageModel(modelId),
|
|
840
|
-
messages,
|
|
841
|
-
tools,
|
|
842
|
-
temperature: providerOptions.temperature,
|
|
843
|
-
maxTokens: providerOptions.maxTokens,
|
|
844
|
-
abortSignal: ctx.abort,
|
|
845
|
-
allowSystemInMessages: true
|
|
846
|
-
});
|
|
847
|
-
const usage = result.usage;
|
|
848
|
-
const usageInfo = usage ? {
|
|
849
|
-
promptTokens: usage.promptTokens ?? 0,
|
|
850
|
-
completionTokens: usage.completionTokens ?? 0,
|
|
851
|
-
totalTokens: usage.totalTokens ?? 0
|
|
852
|
-
} : undefined;
|
|
853
|
-
if (options.env) {
|
|
854
|
-
options.env.pushEnvEvent({
|
|
855
|
-
id: randomUUID(),
|
|
856
|
-
type: "llm.completed",
|
|
857
|
-
timestamp: Date.now(),
|
|
858
|
-
metadata: {
|
|
859
|
-
source: "llm.invokeNonStream",
|
|
860
|
-
sessionId: options.context?.sessionId,
|
|
861
|
-
messageId: options.context?.messageId
|
|
862
|
-
},
|
|
863
|
-
payload: {
|
|
864
|
-
type: "completed",
|
|
865
|
-
content: result.text,
|
|
866
|
-
metadata: {
|
|
867
|
-
model: `${providerId}/${modelId}`,
|
|
868
|
-
usage: usageInfo
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
});
|
|
872
|
-
}
|
|
873
|
-
return {
|
|
874
|
-
content: result.text,
|
|
875
|
-
finishReason: result.finishReason === "stop" ? "stop" : "tool-calls",
|
|
876
|
-
model: `${providerId}/${modelId}`,
|
|
877
|
-
usage: usageInfo
|
|
878
|
-
};
|
|
879
|
-
}
|
|
880
|
-
function createInvokeConfig(model, apiKey, baseURL) {
|
|
881
|
-
return {
|
|
882
|
-
model,
|
|
883
|
-
apiKey,
|
|
884
|
-
baseURL
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
314
|
// src/env/llm/hooks.ts
|
|
888
315
|
init_global_hook_manager();
|
|
889
316
|
|
|
@@ -1020,7 +447,7 @@ class LLMHooks {
|
|
|
1020
447
|
// src/env/llm/llm.ts
|
|
1021
448
|
init_logger();
|
|
1022
449
|
init_decorator();
|
|
1023
|
-
var
|
|
450
|
+
var logger = createLogger("llm");
|
|
1024
451
|
|
|
1025
452
|
class LLMComponent extends BaseComponent {
|
|
1026
453
|
name = "llm";
|
|
@@ -1136,24 +563,24 @@ class LLMComponent extends BaseComponent {
|
|
|
1136
563
|
}
|
|
1137
564
|
registerConfigWatcher(configComponent) {
|
|
1138
565
|
if (typeof configComponent.watch !== "function") {
|
|
1139
|
-
|
|
566
|
+
logger.debug("ConfigComponent does not support watch, hot reload disabled");
|
|
1140
567
|
return;
|
|
1141
568
|
}
|
|
1142
569
|
this.configWatcher = configComponent.watch("llm.*", (event) => {
|
|
1143
570
|
this.onConfigChange(event);
|
|
1144
571
|
});
|
|
1145
|
-
|
|
572
|
+
logger.debug("Config hot reload watcher registered for llm.*");
|
|
1146
573
|
}
|
|
1147
574
|
onConfigChange(event) {
|
|
1148
|
-
|
|
575
|
+
logger.info(`LLM config changed: ${event.key}`);
|
|
1149
576
|
if (event.key === "llm.providers" || event.key.startsWith("llm.providers.")) {
|
|
1150
|
-
|
|
577
|
+
logger.info(`LLM provider config changed, will use new config on next call`);
|
|
1151
578
|
} else if (event.key === "llm.defaultModel") {
|
|
1152
|
-
|
|
579
|
+
logger.info(`LLM default model changed to: ${event.newValue}`);
|
|
1153
580
|
} else if (event.key === "llm.defaultProvider") {
|
|
1154
|
-
|
|
581
|
+
logger.info(`LLM default provider changed to: ${event.newValue}`);
|
|
1155
582
|
} else {
|
|
1156
|
-
|
|
583
|
+
logger.debug(`LLM config updated: ${event.key}`);
|
|
1157
584
|
}
|
|
1158
585
|
}
|
|
1159
586
|
async onStart() {
|
|
@@ -1338,4 +765,4 @@ class LLMComponent extends BaseComponent {
|
|
|
1338
765
|
__legacyDecorateClassTS([
|
|
1339
766
|
TracedAs("llm.component.invoke", { recordParams: true, recordResult: true, log: true })
|
|
1340
767
|
], LLMComponent.prototype, "invoke", null);
|
|
1341
|
-
export { ProviderCapabilitiesSchema, ModelLimitsSchema, ProviderConfigSchema, LLMDefaultConfigSchema, LLMConfigSchema, ProviderManager, LLMTransform,
|
|
768
|
+
export { ProviderCapabilitiesSchema, ModelLimitsSchema, ProviderConfigSchema, LLMDefaultConfigSchema, LLMConfigSchema, ProviderManager, LLMTransform, LLMHooks, LLMComponent };
|
|
@@ -2434,16 +2434,23 @@ var init_engine = __esm(() => {
|
|
|
2434
2434
|
if (!sessionState) {
|
|
2435
2435
|
throw new Error(`Session not found: ${sessionId}`);
|
|
2436
2436
|
}
|
|
2437
|
-
const timeoutMs = timeout ??
|
|
2437
|
+
const timeoutMs = timeout ?? 1200000;
|
|
2438
|
+
let timer;
|
|
2438
2439
|
const timeoutPromise = new Promise((_, reject) => {
|
|
2439
|
-
setTimeout(() => {
|
|
2440
|
+
timer = setTimeout(() => {
|
|
2440
2441
|
reject(new Error(`Workflow execution timeout: ${timeoutMs}ms`));
|
|
2441
2442
|
}, timeoutMs);
|
|
2442
2443
|
});
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2444
|
+
try {
|
|
2445
|
+
return await Promise.race([
|
|
2446
|
+
sessionState.completedPromise,
|
|
2447
|
+
timeoutPromise
|
|
2448
|
+
]);
|
|
2449
|
+
} finally {
|
|
2450
|
+
if (timer) {
|
|
2451
|
+
clearTimeout(timer);
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2447
2454
|
}
|
|
2448
2455
|
async getSessionMetadata(sessionId) {
|
|
2449
2456
|
if (!this.sessionComponent) {
|
|
@@ -206,12 +206,12 @@ var DelegateToolParameters = z.object({
|
|
|
206
206
|
prompt: z.string().describe("The task for the agent to perform"),
|
|
207
207
|
subagent_type: z.string().describe("The type of specialized agent to use for this task").default("general"),
|
|
208
208
|
background: z.boolean().describe("Whether to run the task in background. If true, returns immediately and notifies when complete (default: false)").default(false),
|
|
209
|
-
timeout: z.number().describe("Task timeout in milliseconds. Default:
|
|
209
|
+
timeout: z.number().describe("Task timeout in milliseconds. Default: 1800000 (30 minutes). If set, task will be terminated after timeout.").optional(),
|
|
210
210
|
cleanup: z.enum(["delete", "keep"]).describe("Whether to delete sub session after completion. 'delete' removes the session, 'keep' retains it (default: keep)").default("keep").optional(),
|
|
211
211
|
task_id: z.number().describe("Optional task ID to associate with this delegate task, for tracking in operation records").optional(),
|
|
212
212
|
reason: z.string().describe("Brief reason for calling this tool (max 30 chars, e.g., 'Delegate refactor task')").optional()
|
|
213
213
|
});
|
|
214
|
-
var DEFAULT_TIMEOUT =
|
|
214
|
+
var DEFAULT_TIMEOUT = 1800000;
|
|
215
215
|
var PROGRESS_INTERVAL = 120000;
|
|
216
216
|
|
|
217
217
|
class BackgroundTaskManager {
|
package/package.json
CHANGED
|
File without changes
|