skyloom 1.12.0 → 1.13.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 (135) hide show
  1. package/.github/workflows/ci.yml +36 -36
  2. package/README.md +142 -46
  3. package/config/default.yaml +43 -47
  4. package/config/models.yaml +155 -155
  5. package/config/providers.yaml +39 -39
  6. package/config/skills/api_integrator/SKILL.md +15 -15
  7. package/config/skills/arch_designer/SKILL.md +13 -13
  8. package/config/skills/ci_cd_manager/SKILL.md +14 -14
  9. package/config/skills/code_analysis/SKILL.md +13 -13
  10. package/config/skills/code_generator/SKILL.md +12 -12
  11. package/config/skills/code_reviewer/SKILL.md +13 -13
  12. package/config/skills/content_writer/SKILL.md +14 -14
  13. package/config/skills/data_transformer/SKILL.md +15 -15
  14. package/config/skills/document_analysis/SKILL.md +13 -13
  15. package/config/skills/emotional_companion/SKILL.md +15 -15
  16. package/config/skills/performance_checker/SKILL.md +14 -14
  17. package/config/skills/security_auditor/SKILL.md +14 -14
  18. package/config/skills/self_evolve/SKILL.md +13 -13
  19. package/config/skills/sys_operator/SKILL.md +15 -15
  20. package/config/skills/task_planner/SKILL.md +14 -14
  21. package/config/skills/web_research/SKILL.md +14 -14
  22. package/config/skills/workflow_designer/SKILL.md +13 -13
  23. package/dist/agents/dew.js +52 -52
  24. package/dist/agents/fair.js +84 -84
  25. package/dist/agents/fog.js +30 -30
  26. package/dist/agents/frost.js +32 -32
  27. package/dist/agents/rain.js +32 -32
  28. package/dist/agents/snow.js +68 -68
  29. package/dist/cli/main.js +103 -51
  30. package/dist/cli/main.js.map +1 -1
  31. package/dist/cli/tui.d.ts.map +1 -1
  32. package/dist/cli/tui.js +8 -1
  33. package/dist/cli/tui.js.map +1 -1
  34. package/dist/core/agent/task.d.ts +58 -0
  35. package/dist/core/agent/task.d.ts.map +1 -0
  36. package/dist/core/agent/task.js +83 -0
  37. package/dist/core/agent/task.js.map +1 -0
  38. package/dist/core/agent.d.ts +2 -45
  39. package/dist/core/agent.d.ts.map +1 -1
  40. package/dist/core/agent.js +61 -145
  41. package/dist/core/agent.js.map +1 -1
  42. package/dist/core/agent_helpers.d.ts +10 -0
  43. package/dist/core/agent_helpers.d.ts.map +1 -1
  44. package/dist/core/agent_helpers.js +39 -0
  45. package/dist/core/agent_helpers.js.map +1 -1
  46. package/dist/core/catalog.d.ts +71 -0
  47. package/dist/core/catalog.d.ts.map +1 -0
  48. package/dist/core/catalog.js +176 -0
  49. package/dist/core/catalog.js.map +1 -0
  50. package/dist/core/config.d.ts +8 -0
  51. package/dist/core/config.d.ts.map +1 -1
  52. package/dist/core/config.js +12 -4
  53. package/dist/core/config.js.map +1 -1
  54. package/dist/core/factory.js +16 -16
  55. package/dist/core/llm.d.ts +7 -0
  56. package/dist/core/llm.d.ts.map +1 -1
  57. package/dist/core/llm.js +139 -7
  58. package/dist/core/llm.js.map +1 -1
  59. package/dist/core/longdoc.js +5 -5
  60. package/dist/core/memory.d.ts.map +1 -1
  61. package/dist/core/memory.js +69 -62
  62. package/dist/core/memory.js.map +1 -1
  63. package/dist/core/theme.d.ts +46 -0
  64. package/dist/core/theme.d.ts.map +1 -0
  65. package/dist/core/theme.js +42 -0
  66. package/dist/core/theme.js.map +1 -0
  67. package/dist/web/server.js +542 -519
  68. package/dist/web/server.js.map +1 -1
  69. package/docs/AESTHETIC_DESIGN.md +144 -0
  70. package/docs/OPTIMIZATION_PLAN.md +178 -0
  71. package/package.json +60 -60
  72. package/scripts/install.js +48 -48
  73. package/scripts/link.js +10 -10
  74. package/setup.bat +79 -79
  75. package/skill-test-ty2fOA/test.md +10 -10
  76. package/src/agents/dew.ts +70 -70
  77. package/src/agents/fair.ts +102 -102
  78. package/src/agents/fog.ts +48 -48
  79. package/src/agents/frost.ts +50 -50
  80. package/src/agents/rain.ts +50 -50
  81. package/src/agents/snow.ts +239 -239
  82. package/src/cli/main.ts +425 -372
  83. package/src/cli/mode.ts +58 -58
  84. package/src/cli/tui.ts +272 -269
  85. package/src/core/agent/task.ts +100 -0
  86. package/src/core/agent.ts +1446 -1549
  87. package/src/core/agent_helpers.ts +496 -461
  88. package/src/core/arbitrate.ts +162 -162
  89. package/src/core/catalog.ts +178 -0
  90. package/src/core/checkpoint.ts +94 -94
  91. package/src/core/config.ts +20 -4
  92. package/src/core/estimate.ts +104 -104
  93. package/src/core/evolve.ts +191 -191
  94. package/src/core/factory.ts +627 -627
  95. package/src/core/filter.ts +103 -103
  96. package/src/core/graph.ts +156 -156
  97. package/src/core/icons.ts +53 -53
  98. package/src/core/index.ts +37 -37
  99. package/src/core/learn.ts +146 -146
  100. package/src/core/llm.ts +108 -5
  101. package/src/core/longdoc.ts +155 -155
  102. package/src/core/mcp_server.ts +176 -176
  103. package/src/core/memory.ts +1178 -1171
  104. package/src/core/profile.ts +255 -255
  105. package/src/core/router.ts +124 -124
  106. package/src/core/sandbox.ts +142 -142
  107. package/src/core/security.ts +243 -243
  108. package/src/core/skill.ts +342 -342
  109. package/src/core/theme.ts +65 -0
  110. package/src/core/tool_router.ts +193 -193
  111. package/src/core/vector.ts +152 -152
  112. package/src/core/workspace.ts +150 -150
  113. package/src/plugins/loader.ts +66 -66
  114. package/src/skills/loader.ts +46 -46
  115. package/src/sql.js.d.ts +29 -29
  116. package/src/tools/builtin.ts +380 -380
  117. package/src/tools/computer.ts +269 -269
  118. package/src/tools/delegate.ts +49 -49
  119. package/src/web/server.ts +660 -634
  120. package/src/web/tts.ts +93 -93
  121. package/tests/agent_helpers.test.ts +48 -0
  122. package/tests/bus.test.ts +121 -121
  123. package/tests/catalog.test.ts +86 -0
  124. package/tests/config.test.ts +41 -0
  125. package/tests/icons.test.ts +45 -45
  126. package/tests/memory.test.ts +147 -0
  127. package/tests/router.test.ts +86 -86
  128. package/tests/schemas.test.ts +51 -51
  129. package/tests/semantic.test.ts +83 -83
  130. package/tests/setup.ts +10 -10
  131. package/tests/skill.test.ts +172 -172
  132. package/tests/task.test.ts +60 -0
  133. package/tests/tool.test.ts +108 -108
  134. package/tests/tool_router.test.ts +71 -71
  135. package/vitest.config.ts +17 -17
package/src/core/index.ts CHANGED
@@ -1,37 +1,37 @@
1
- /**
2
- * Skyloom Core Module Exports
3
- */
4
-
5
- export * from './constants';
6
- export * from './schemas';
7
- export * from './logger';
8
- export * from './config';
9
- export * from './tool';
10
- export * from './circuit_breaker';
11
- export * from './bus';
12
- export * from './cache';
13
- export * from './memory';
14
- export * from './middleware';
15
- export * from './llm';
16
- export * from './mcp';
17
- export { matchPipeline, buildTasksFromPipeline, listPipelines, getPipelineByName, matchAllPipelines, validateDAG, topologicalSort, type Pipeline, type PipelineStep } from './pipelines';
18
- export * from './semantic';
19
- export * from './icons';
20
- export * from './checkpoint';
21
- export * from './workspace';
22
- export * from './profile';
23
- export * from './tool_router';
24
- export * from './agent_helpers';
25
- export * from './skill';
26
- export * from './router';
27
- export * from './agent';
28
- export * from './factory';
29
- export * from './security';
30
- export * from './learn';
31
- export * from './longdoc';
32
- export * from './filter';
33
- export * from './estimate';
34
- export * from './arbitrate';
35
-
36
- // Version — read from package.json
37
- export const VERSION = (() => { try { return require('../../package.json').version; } catch { return '1.6.0'; } })();
1
+ /**
2
+ * Skyloom Core Module Exports
3
+ */
4
+
5
+ export * from './constants';
6
+ export * from './schemas';
7
+ export * from './logger';
8
+ export * from './config';
9
+ export * from './tool';
10
+ export * from './circuit_breaker';
11
+ export * from './bus';
12
+ export * from './cache';
13
+ export * from './memory';
14
+ export * from './middleware';
15
+ export * from './llm';
16
+ export * from './mcp';
17
+ export { matchPipeline, buildTasksFromPipeline, listPipelines, getPipelineByName, matchAllPipelines, validateDAG, topologicalSort, type Pipeline, type PipelineStep } from './pipelines';
18
+ export * from './semantic';
19
+ export * from './icons';
20
+ export * from './checkpoint';
21
+ export * from './workspace';
22
+ export * from './profile';
23
+ export * from './tool_router';
24
+ export * from './agent_helpers';
25
+ export * from './skill';
26
+ export * from './router';
27
+ export * from './agent';
28
+ export * from './factory';
29
+ export * from './security';
30
+ export * from './learn';
31
+ export * from './longdoc';
32
+ export * from './filter';
33
+ export * from './estimate';
34
+ export * from './arbitrate';
35
+
36
+ // Version — read from package.json
37
+ export const VERSION = (() => { try { return require('../../package.json').version; } catch { return '1.6.0'; } })();
package/src/core/learn.ts CHANGED
@@ -1,146 +1,146 @@
1
- /**
2
- * 持续学习模块 — post-task review + experience recording.
3
- *
4
- * After each task, the agent writes a structured review.
5
- * Failed attempts are indexed for similarity search to avoid repetition.
6
- */
7
-
8
- import * as fs from "fs";
9
- import * as path from "path";
10
- import { USER_CONFIG_DIR } from "./config";
11
- import { getLogger } from "./logger";
12
-
13
- const log = getLogger("learn");
14
-
15
- /* ── Data types ── */
16
- export interface TaskReview {
17
- ts: string;
18
- agent: string;
19
- goal: string;
20
- success: boolean;
21
- durationMs: number;
22
- toolCalls: string[];
23
- errorMsg?: string;
24
- rootCause?: string;
25
- improvement?: string;
26
- }
27
-
28
- export interface ExperienceEntry {
29
- id: string;
30
- pattern: string; // What went wrong (key for similarity search)
31
- solution: string; // What fixed it
32
- frequency: number; // How often this pattern repeats
33
- lastSeen: string;
34
- }
35
-
36
- /* ── Persistence ── */
37
- const reviewDir = path.join(USER_CONFIG_DIR, "reviews");
38
- const expFile = path.join(USER_CONFIG_DIR, "experiences.json");
39
- const reviewDir_ = reviewDir; // for closure
40
-
41
- function ensureDir() { if (!fs.existsSync(reviewDir_)) fs.mkdirSync(reviewDir_, { recursive: true }); }
42
-
43
- /* ═══════════════════════════════════════
44
- Task Review Recording
45
- ═══════════════════════════════════════ */
46
- export function recordReview(review: TaskReview): void {
47
- ensureDir();
48
- const file = path.join(reviewDir_, `${review.ts.slice(0, 10)}_${review.agent}.jsonl`);
49
- const line = JSON.stringify(review);
50
- fs.appendFileSync(file, line + "\n");
51
- log.debug("review_recorded", { agent: review.agent, success: review.success });
52
-
53
- // If failed, also record as experience
54
- if (!review.success && review.errorMsg) {
55
- recordExperience(review.errorMsg, review.rootCause || "unknown", review.improvement || "no improvement noted");
56
- }
57
- }
58
-
59
- /* ═══════════════════════════════════════
60
- Experience Recording (for failure patterns)
61
- ═══════════════════════════════════════ */
62
- function loadExperiences(): ExperienceEntry[] {
63
- try {
64
- if (fs.existsSync(expFile)) return JSON.parse(fs.readFileSync(expFile, "utf-8"));
65
- } catch { /* ignore */ }
66
- return [];
67
- }
68
-
69
- function saveExperiences(entries: ExperienceEntry[]): void {
70
- ensureDir();
71
- fs.writeFileSync(expFile, JSON.stringify(entries, null, 2), "utf-8");
72
- }
73
-
74
- export function recordExperience(errorPattern: string, rootCause: string, solution: string): void {
75
- const entries = loadExperiences();
76
- const normalized = errorPattern.toLowerCase().slice(0, 200);
77
-
78
- // Check for existing similar pattern (simple substring match)
79
- const existing = entries.find(e => e.pattern.toLowerCase().includes(normalized.slice(0, 50)) || normalized.includes(e.pattern.toLowerCase().slice(0, 50)));
80
- if (existing) {
81
- existing.frequency++;
82
- existing.lastSeen = new Date().toISOString();
83
- if (solution && solution !== "no improvement noted") existing.solution = solution;
84
- } else {
85
- entries.push({
86
- id: Math.random().toString(36).slice(2, 10),
87
- pattern: errorPattern.slice(0, 200),
88
- solution,
89
- frequency: 1,
90
- lastSeen: new Date().toISOString(),
91
- });
92
- }
93
-
94
- // Keep top 100 experiences, sorted by frequency
95
- entries.sort((a, b) => b.frequency - a.frequency);
96
- if (entries.length > 100) entries.splice(100);
97
- saveExperiences(entries);
98
- }
99
-
100
- /* ═══════════════════════════════════════
101
- Query experiences
102
- ═══════════════════════════════════════ */
103
- export function queryExperiences(problem: string, limit: number = 3): ExperienceEntry[] {
104
- const entries = loadExperiences();
105
- const lower = problem.toLowerCase();
106
- return entries
107
- .filter(e => {
108
- const plow = e.pattern.toLowerCase();
109
- // Simple token overlap scoring
110
- const tokens = lower.split(/\s+/).filter(t => t.length > 2);
111
- const matches = tokens.filter(t => plow.includes(t));
112
- return matches.length >= 2;
113
- })
114
- .sort((a, b) => b.frequency - a.frequency)
115
- .slice(0, limit);
116
- }
117
-
118
- /* ═══════════════════════════════════════
119
- Format experiences for system prompt injection
120
- ═══════════════════════════════════════ */
121
- export function formatExperiencesForPrompt(problem: string): string {
122
- const exps = queryExperiences(problem);
123
- if (!exps.length) return "";
124
- const lines = ["## 历史教训(从经验库检索)", "以下是与当前任务相关的过往失败案例,请避免重复:"];
125
- for (const e of exps) {
126
- lines.push(`- **模式**: ${e.pattern.slice(0, 120)}`);
127
- lines.push(` **解决**: ${e.solution.slice(0, 200)} (出现 ${e.frequency} 次)`);
128
- }
129
- return lines.join("\n");
130
- }
131
-
132
- /* ═══════════════════════════════════════
133
- Generate a structured review after task completion
134
- ═══════════════════════════════════════ */
135
- export function generateReview(
136
- agent: string, goal: string, success: boolean, durationMs: number,
137
- toolCalls: string[], errorMsg?: string
138
- ): TaskReview {
139
- return {
140
- ts: new Date().toISOString(),
141
- agent, goal, success, durationMs, toolCalls,
142
- errorMsg,
143
- rootCause: errorMsg ? "auto-detected failure" : undefined,
144
- improvement: errorMsg ? "review error and adjust approach" : undefined,
145
- };
146
- }
1
+ /**
2
+ * 持续学习模块 — post-task review + experience recording.
3
+ *
4
+ * After each task, the agent writes a structured review.
5
+ * Failed attempts are indexed for similarity search to avoid repetition.
6
+ */
7
+
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import { USER_CONFIG_DIR } from "./config";
11
+ import { getLogger } from "./logger";
12
+
13
+ const log = getLogger("learn");
14
+
15
+ /* ── Data types ── */
16
+ export interface TaskReview {
17
+ ts: string;
18
+ agent: string;
19
+ goal: string;
20
+ success: boolean;
21
+ durationMs: number;
22
+ toolCalls: string[];
23
+ errorMsg?: string;
24
+ rootCause?: string;
25
+ improvement?: string;
26
+ }
27
+
28
+ export interface ExperienceEntry {
29
+ id: string;
30
+ pattern: string; // What went wrong (key for similarity search)
31
+ solution: string; // What fixed it
32
+ frequency: number; // How often this pattern repeats
33
+ lastSeen: string;
34
+ }
35
+
36
+ /* ── Persistence ── */
37
+ const reviewDir = path.join(USER_CONFIG_DIR, "reviews");
38
+ const expFile = path.join(USER_CONFIG_DIR, "experiences.json");
39
+ const reviewDir_ = reviewDir; // for closure
40
+
41
+ function ensureDir() { if (!fs.existsSync(reviewDir_)) fs.mkdirSync(reviewDir_, { recursive: true }); }
42
+
43
+ /* ═══════════════════════════════════════
44
+ Task Review Recording
45
+ ═══════════════════════════════════════ */
46
+ export function recordReview(review: TaskReview): void {
47
+ ensureDir();
48
+ const file = path.join(reviewDir_, `${review.ts.slice(0, 10)}_${review.agent}.jsonl`);
49
+ const line = JSON.stringify(review);
50
+ fs.appendFileSync(file, line + "\n");
51
+ log.debug("review_recorded", { agent: review.agent, success: review.success });
52
+
53
+ // If failed, also record as experience
54
+ if (!review.success && review.errorMsg) {
55
+ recordExperience(review.errorMsg, review.rootCause || "unknown", review.improvement || "no improvement noted");
56
+ }
57
+ }
58
+
59
+ /* ═══════════════════════════════════════
60
+ Experience Recording (for failure patterns)
61
+ ═══════════════════════════════════════ */
62
+ function loadExperiences(): ExperienceEntry[] {
63
+ try {
64
+ if (fs.existsSync(expFile)) return JSON.parse(fs.readFileSync(expFile, "utf-8"));
65
+ } catch { /* ignore */ }
66
+ return [];
67
+ }
68
+
69
+ function saveExperiences(entries: ExperienceEntry[]): void {
70
+ ensureDir();
71
+ fs.writeFileSync(expFile, JSON.stringify(entries, null, 2), "utf-8");
72
+ }
73
+
74
+ export function recordExperience(errorPattern: string, rootCause: string, solution: string): void {
75
+ const entries = loadExperiences();
76
+ const normalized = errorPattern.toLowerCase().slice(0, 200);
77
+
78
+ // Check for existing similar pattern (simple substring match)
79
+ const existing = entries.find(e => e.pattern.toLowerCase().includes(normalized.slice(0, 50)) || normalized.includes(e.pattern.toLowerCase().slice(0, 50)));
80
+ if (existing) {
81
+ existing.frequency++;
82
+ existing.lastSeen = new Date().toISOString();
83
+ if (solution && solution !== "no improvement noted") existing.solution = solution;
84
+ } else {
85
+ entries.push({
86
+ id: Math.random().toString(36).slice(2, 10),
87
+ pattern: errorPattern.slice(0, 200),
88
+ solution,
89
+ frequency: 1,
90
+ lastSeen: new Date().toISOString(),
91
+ });
92
+ }
93
+
94
+ // Keep top 100 experiences, sorted by frequency
95
+ entries.sort((a, b) => b.frequency - a.frequency);
96
+ if (entries.length > 100) entries.splice(100);
97
+ saveExperiences(entries);
98
+ }
99
+
100
+ /* ═══════════════════════════════════════
101
+ Query experiences
102
+ ═══════════════════════════════════════ */
103
+ export function queryExperiences(problem: string, limit: number = 3): ExperienceEntry[] {
104
+ const entries = loadExperiences();
105
+ const lower = problem.toLowerCase();
106
+ return entries
107
+ .filter(e => {
108
+ const plow = e.pattern.toLowerCase();
109
+ // Simple token overlap scoring
110
+ const tokens = lower.split(/\s+/).filter(t => t.length > 2);
111
+ const matches = tokens.filter(t => plow.includes(t));
112
+ return matches.length >= 2;
113
+ })
114
+ .sort((a, b) => b.frequency - a.frequency)
115
+ .slice(0, limit);
116
+ }
117
+
118
+ /* ═══════════════════════════════════════
119
+ Format experiences for system prompt injection
120
+ ═══════════════════════════════════════ */
121
+ export function formatExperiencesForPrompt(problem: string): string {
122
+ const exps = queryExperiences(problem);
123
+ if (!exps.length) return "";
124
+ const lines = ["## 历史教训(从经验库检索)", "以下是与当前任务相关的过往失败案例,请避免重复:"];
125
+ for (const e of exps) {
126
+ lines.push(`- **模式**: ${e.pattern.slice(0, 120)}`);
127
+ lines.push(` **解决**: ${e.solution.slice(0, 200)} (出现 ${e.frequency} 次)`);
128
+ }
129
+ return lines.join("\n");
130
+ }
131
+
132
+ /* ═══════════════════════════════════════
133
+ Generate a structured review after task completion
134
+ ═══════════════════════════════════════ */
135
+ export function generateReview(
136
+ agent: string, goal: string, success: boolean, durationMs: number,
137
+ toolCalls: string[], errorMsg?: string
138
+ ): TaskReview {
139
+ return {
140
+ ts: new Date().toISOString(),
141
+ agent, goal, success, durationMs, toolCalls,
142
+ errorMsg,
143
+ rootCause: errorMsg ? "auto-detected failure" : undefined,
144
+ improvement: errorMsg ? "review error and adjust approach" : undefined,
145
+ };
146
+ }
package/src/core/llm.ts CHANGED
@@ -499,7 +499,10 @@ export class LLMClient {
499
499
  return String(agentCfg.model);
500
500
  }
501
501
  }
502
- return this.config.llm?.defaultModel || "gpt-4o";
502
+ // Honor the user's configured default (set by the /setup wizard). YAML uses
503
+ // snake_case; the legacy camelCase read is kept as a last resort.
504
+ const c: any = this.config;
505
+ return c.default_model || c.llm?.default_model || c.llm?.defaultModel || "gpt-4o";
503
506
  }
504
507
 
505
508
  /**
@@ -792,13 +795,113 @@ export class LLMClient {
792
795
  yield response.content;
793
796
  }
794
797
 
798
+ /**
799
+ * Real SSE token streaming for OpenAI-compatible providers (openai, deepseek,
800
+ * groq, openrouter, mistral, xai, ollama). Content + reasoning deltas are
801
+ * yielded as they arrive; tool-call deltas are accumulated by index and
802
+ * emitted once complete. Usage comes from the final `stream_options` chunk.
803
+ */
804
+ private async *callOpenAIStream(
805
+ m: string, messages: Record<string, unknown>[], tools?: string[], temp?: number, maxTok?: number
806
+ ): AsyncGenerator<StreamEvent> {
807
+ const apiKey = this.getApiKey(m);
808
+ const baseUrl = this.getBaseUrl(m);
809
+ const body: Record<string, unknown> = {
810
+ model: m, messages, temperature: temp ?? 0.7, max_tokens: maxTok ?? 4096,
811
+ stream: true, stream_options: { include_usage: true },
812
+ };
813
+ if (tools?.length) {
814
+ const defs = tools.map(t => this._toolRegistry.get(t)).filter(Boolean) as any[];
815
+ if (defs.length) body.tools = defs.map(t => ({ type: "function", function: { name: t.name, description: t.description, parameters: this.paramsToSchema(t.parameters || []) } }));
816
+ }
817
+ const resp = await fetch(baseUrl + "/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + apiKey }, body: JSON.stringify(body) });
818
+ if (!resp.ok || !resp.body) { const e: any = new Error("API " + resp.status + ": " + ((await resp.text()).slice(0, 200))); e.status_code = resp.status; throw e; }
819
+
820
+ const reader = (resp.body as any).getReader();
821
+ const decoder = new TextDecoder();
822
+ let buf = "";
823
+ const toolAcc = new Map<number, { id: string; name: string; args: string }>();
824
+ let usage: UsageStats = { promptTokens: 0, completionTokens: 0 };
825
+ let reasoning = "";
826
+
827
+ while (true) {
828
+ const { done, value } = await reader.read();
829
+ if (done) break;
830
+ buf += decoder.decode(value, { stream: true });
831
+ const lines = buf.split("\n");
832
+ buf = lines.pop() || "";
833
+ for (const line of lines) {
834
+ const t = line.trim();
835
+ if (!t.startsWith("data:")) continue;
836
+ const data = t.slice(5).trim();
837
+ if (data === "[DONE]") continue;
838
+ let json: any; try { json = JSON.parse(data); } catch { continue; }
839
+ if (json.usage) usage = { promptTokens: json.usage.prompt_tokens || 0, completionTokens: json.usage.completion_tokens || 0 };
840
+ const delta = json.choices?.[0]?.delta;
841
+ if (!delta) continue;
842
+ if (delta.content) yield { type: "content", text: delta.content };
843
+ if (delta.reasoning_content) { reasoning += delta.reasoning_content; yield { type: "reasoning", text: delta.reasoning_content }; }
844
+ if (Array.isArray(delta.tool_calls)) {
845
+ for (const tc of delta.tool_calls) {
846
+ const idx = tc.index ?? 0;
847
+ const acc = toolAcc.get(idx) || { id: "", name: "", args: "" };
848
+ if (tc.id) acc.id = tc.id;
849
+ if (tc.function?.name) acc.name = tc.function.name;
850
+ if (tc.function?.arguments) acc.args += tc.function.arguments;
851
+ toolAcc.set(idx, acc);
852
+ }
853
+ }
854
+ }
855
+ }
856
+ for (const acc of toolAcc.values()) {
857
+ if (acc.name) yield { type: "tool_call", toolCall: { id: acc.id || ("call_" + acc.name), type: "function", function: { name: acc.name, arguments: acc.args || "{}" } } };
858
+ }
859
+ yield { type: "done", usage, reasoningContent: reasoning || undefined };
860
+ }
861
+
795
862
  async *streamWithTools(
796
863
  messages: Record<string, unknown>[], agentName?: string, tools?: string[],
797
864
  _toolRegistry?: ToolRegistry, overrides?: Record<string, unknown>
798
865
  ): AsyncGenerator<StreamEvent> {
799
- const response = await this.complete(messages, agentName, tools, false, overrides);
800
- if (response.content) yield { type: "content", text: response.content };
801
- for (const tc of response.toolCalls || []) yield { type: "tool_call", toolCall: tc };
802
- yield { type: "done", usage: response.usage, reasoningContent: response.reasoningContent };
866
+ this.checkBudget();
867
+ const ov = overrides || {};
868
+ const model: string = typeof ov.model === "string" ? ov.model : this.getModel(agentName);
869
+ const temperature = (ov.temperature as number) ?? 0.7;
870
+ const maxTokens = (ov.maxTokens as number) ?? 4096;
871
+ const isAnthropic = model.includes("claude") || model.startsWith("anthropic/");
872
+
873
+ // Blocking fallback used for Anthropic (different wire format) and on
874
+ // failures before any content has streamed (preserves fallback chain + retry).
875
+ const blockingFallback = async function* (this: LLMClient): AsyncGenerator<StreamEvent> {
876
+ const response = await this.complete(messages, agentName, tools, false, overrides);
877
+ if (response.content) yield { type: "content", text: response.content };
878
+ for (const tc of response.toolCalls || []) yield { type: "tool_call", toolCall: tc };
879
+ yield { type: "done", usage: response.usage, reasoningContent: response.reasoningContent };
880
+ }.bind(this);
881
+
882
+ if (isAnthropic) { yield* blockingFallback(); return; }
883
+
884
+ let started = false;
885
+ let usage: UsageStats = { promptTokens: 0, completionTokens: 0 };
886
+ try {
887
+ for await (const ev of this.callOpenAIStream(model, messages, tools, temperature, maxTokens)) {
888
+ if (ev.type === "content" || ev.type === "tool_call") started = true;
889
+ if (ev.type === "done" && ev.usage) usage = ev.usage;
890
+ yield ev;
891
+ }
892
+ } catch (e: any) {
893
+ if (started) { yield { type: "error", text: String(e?.message || e) }; yield { type: "done", usage }; return; }
894
+ this.log?.warn("stream_failed_fallback", { model, error: String(e?.message || e) });
895
+ yield* blockingFallback();
896
+ return;
897
+ }
898
+
899
+ // Usage + cost bookkeeping (mirrors completeWithRetry).
900
+ const name = agentName || "default";
901
+ if (!this.usageStats.has(name)) this.usageStats.set(name, { prompt_tokens: 0, completion_tokens: 0, calls: 0, cost: 0 });
902
+ const s = this.usageStats.get(name)!;
903
+ s.prompt_tokens += usage.promptTokens; s.completion_tokens += usage.completionTokens; s.calls += 1;
904
+ const cost = estimateCost(model, usage.promptTokens, usage.completionTokens);
905
+ s.cost += cost; this.totalCost += cost;
803
906
  }
804
907
  }