wide-cli 0.0.0-stage → 0.3.101126

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 (172) hide show
  1. package/.github/workflows/ci.yml +29 -0
  2. package/LICENSE +674 -0
  3. package/README.md +80 -2
  4. package/assets/logo.png +0 -0
  5. package/assets/wide-logo.png +0 -0
  6. package/bin/wide.js +17 -0
  7. package/dist/agent/context.d.ts +7 -0
  8. package/dist/agent/context.d.ts.map +1 -0
  9. package/dist/agent/context.js +38 -0
  10. package/dist/agent/context.js.map +1 -0
  11. package/dist/agent/index.d.ts +16 -0
  12. package/dist/agent/index.d.ts.map +1 -0
  13. package/dist/agent/index.js +138 -0
  14. package/dist/agent/index.js.map +1 -0
  15. package/dist/config/index.d.ts +29 -0
  16. package/dist/config/index.d.ts.map +1 -0
  17. package/dist/config/index.js +66 -0
  18. package/dist/config/index.js.map +1 -0
  19. package/dist/config/workspace.d.ts +7 -0
  20. package/dist/config/workspace.d.ts.map +1 -0
  21. package/dist/config/workspace.js +31 -0
  22. package/dist/config/workspace.js.map +1 -0
  23. package/dist/decision/index.d.ts +113 -0
  24. package/dist/decision/index.d.ts.map +1 -0
  25. package/dist/decision/index.js +485 -0
  26. package/dist/decision/index.js.map +1 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +167 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/providers/claude.d.ts +10 -0
  32. package/dist/providers/claude.d.ts.map +1 -0
  33. package/dist/providers/claude.js +147 -0
  34. package/dist/providers/claude.js.map +1 -0
  35. package/dist/providers/gemini.d.ts +10 -0
  36. package/dist/providers/gemini.d.ts.map +1 -0
  37. package/dist/providers/gemini.js +129 -0
  38. package/dist/providers/gemini.js.map +1 -0
  39. package/dist/providers/index.d.ts +4 -0
  40. package/dist/providers/index.d.ts.map +1 -0
  41. package/dist/providers/index.js +44 -0
  42. package/dist/providers/index.js.map +1 -0
  43. package/dist/providers/ollama.d.ts +10 -0
  44. package/dist/providers/ollama.d.ts.map +1 -0
  45. package/dist/providers/ollama.js +94 -0
  46. package/dist/providers/ollama.js.map +1 -0
  47. package/dist/providers/openai.d.ts +11 -0
  48. package/dist/providers/openai.d.ts.map +1 -0
  49. package/dist/providers/openai.js +142 -0
  50. package/dist/providers/openai.js.map +1 -0
  51. package/dist/providers/types.d.ts +22 -0
  52. package/dist/providers/types.d.ts.map +1 -0
  53. package/dist/providers/types.js +2 -0
  54. package/dist/providers/types.js.map +1 -0
  55. package/dist/repl/index.d.ts +2 -0
  56. package/dist/repl/index.d.ts.map +1 -0
  57. package/dist/repl/index.js +94 -0
  58. package/dist/repl/index.js.map +1 -0
  59. package/dist/security/fuzzer.d.ts +20 -0
  60. package/dist/security/fuzzer.d.ts.map +1 -0
  61. package/dist/security/fuzzer.js +109 -0
  62. package/dist/security/fuzzer.js.map +1 -0
  63. package/dist/security/loader.d.ts +17 -0
  64. package/dist/security/loader.d.ts.map +1 -0
  65. package/dist/security/loader.js +126 -0
  66. package/dist/security/loader.js.map +1 -0
  67. package/dist/security/payloads.d.ts +9 -0
  68. package/dist/security/payloads.d.ts.map +1 -0
  69. package/dist/security/payloads.js +88 -0
  70. package/dist/security/payloads.js.map +1 -0
  71. package/dist/security/rules.d.ts +14 -0
  72. package/dist/security/rules.d.ts.map +1 -0
  73. package/dist/security/rules.js +288 -0
  74. package/dist/security/rules.js.map +1 -0
  75. package/dist/security/scanner.d.ts +29 -0
  76. package/dist/security/scanner.d.ts.map +1 -0
  77. package/dist/security/scanner.js +136 -0
  78. package/dist/security/scanner.js.map +1 -0
  79. package/dist/tools/browser.d.ts +47 -0
  80. package/dist/tools/browser.d.ts.map +1 -0
  81. package/dist/tools/browser.js +441 -0
  82. package/dist/tools/browser.js.map +1 -0
  83. package/dist/tools/fs.d.ts +5 -0
  84. package/dist/tools/fs.d.ts.map +1 -0
  85. package/dist/tools/fs.js +131 -0
  86. package/dist/tools/fs.js.map +1 -0
  87. package/dist/tools/git.d.ts +3 -0
  88. package/dist/tools/git.d.ts.map +1 -0
  89. package/dist/tools/git.js +50 -0
  90. package/dist/tools/git.js.map +1 -0
  91. package/dist/tools/http.d.ts +3 -0
  92. package/dist/tools/http.d.ts.map +1 -0
  93. package/dist/tools/http.js +69 -0
  94. package/dist/tools/http.js.map +1 -0
  95. package/dist/tools/index.d.ts +5 -0
  96. package/dist/tools/index.d.ts.map +1 -0
  97. package/dist/tools/index.js +50 -0
  98. package/dist/tools/index.js.map +1 -0
  99. package/dist/tools/search.d.ts +4 -0
  100. package/dist/tools/search.d.ts.map +1 -0
  101. package/dist/tools/search.js +109 -0
  102. package/dist/tools/search.js.map +1 -0
  103. package/dist/tools/security.d.ts +5 -0
  104. package/dist/tools/security.d.ts.map +1 -0
  105. package/dist/tools/security.js +129 -0
  106. package/dist/tools/security.js.map +1 -0
  107. package/dist/tools/shell.d.ts +3 -0
  108. package/dist/tools/shell.d.ts.map +1 -0
  109. package/dist/tools/shell.js +50 -0
  110. package/dist/tools/shell.js.map +1 -0
  111. package/dist/tools/types.d.ts +33 -0
  112. package/dist/tools/types.d.ts.map +1 -0
  113. package/dist/tools/types.js +2 -0
  114. package/dist/tools/types.js.map +1 -0
  115. package/dist/ui/banner.d.ts +2 -0
  116. package/dist/ui/banner.d.ts.map +1 -0
  117. package/dist/ui/banner.js +14 -0
  118. package/dist/ui/banner.js.map +1 -0
  119. package/dist/ui/colors.d.ts +18 -0
  120. package/dist/ui/colors.d.ts.map +1 -0
  121. package/dist/ui/colors.js +19 -0
  122. package/dist/ui/colors.js.map +1 -0
  123. package/dist/ui/diff.d.ts +2 -0
  124. package/dist/ui/diff.d.ts.map +1 -0
  125. package/dist/ui/diff.js +26 -0
  126. package/dist/ui/diff.js.map +1 -0
  127. package/dist/ui/markdown.d.ts +2 -0
  128. package/dist/ui/markdown.d.ts.map +1 -0
  129. package/dist/ui/markdown.js +32 -0
  130. package/dist/ui/markdown.js.map +1 -0
  131. package/dist/ui/spinner.d.ts +12 -0
  132. package/dist/ui/spinner.d.ts.map +1 -0
  133. package/dist/ui/spinner.js +46 -0
  134. package/dist/ui/spinner.js.map +1 -0
  135. package/package.json +50 -4
  136. package/src/agent/context.ts +44 -0
  137. package/src/agent/index.ts +166 -0
  138. package/src/config/index.ts +88 -0
  139. package/src/config/workspace.ts +39 -0
  140. package/src/decision/index.ts +528 -0
  141. package/src/index.ts +180 -0
  142. package/src/providers/claude.ts +163 -0
  143. package/src/providers/gemini.ts +147 -0
  144. package/src/providers/index.ts +52 -0
  145. package/src/providers/ollama.ts +108 -0
  146. package/src/providers/openai.ts +159 -0
  147. package/src/providers/types.ts +29 -0
  148. package/src/repl/index.ts +100 -0
  149. package/src/security/fuzzer.ts +140 -0
  150. package/src/security/loader.ts +129 -0
  151. package/src/security/payloads.ts +95 -0
  152. package/src/security/rules.ts +300 -0
  153. package/src/security/scanner.ts +180 -0
  154. package/src/tools/browser.ts +528 -0
  155. package/src/tools/fs.ts +143 -0
  156. package/src/tools/git.ts +51 -0
  157. package/src/tools/http.ts +77 -0
  158. package/src/tools/index.ts +64 -0
  159. package/src/tools/search.ts +109 -0
  160. package/src/tools/security.ts +140 -0
  161. package/src/tools/shell.ts +56 -0
  162. package/src/tools/types.ts +33 -0
  163. package/src/ui/banner.ts +17 -0
  164. package/src/ui/colors.ts +19 -0
  165. package/src/ui/diff.ts +24 -0
  166. package/src/ui/markdown.ts +34 -0
  167. package/src/ui/spinner.ts +53 -0
  168. package/tests/browser.test.mjs +71 -0
  169. package/tests/decision.test.mjs +68 -0
  170. package/tests/loader.test.mjs +24 -0
  171. package/tests/suite.test.mjs +61 -0
  172. package/tsconfig.json +20 -0
@@ -0,0 +1,163 @@
1
+ import type { LLMProvider, ChatMessage, ProviderResponse, ToolCall } from "./types.js";
2
+ import type { ToolDefinition } from "../tools/types.js";
3
+
4
+ export class ClaudeProvider implements LLMProvider {
5
+ public name = "claude";
6
+ private apiKey: string;
7
+ private model: string;
8
+
9
+ constructor(apiKey: string, model = "claude-3-7-sonnet-20250219") {
10
+ this.apiKey = apiKey;
11
+ this.model = model;
12
+ }
13
+
14
+ async chatStream(
15
+ messages: ChatMessage[],
16
+ tools: ToolDefinition[],
17
+ onChunk: (chunk: string) => void
18
+ ): Promise<ProviderResponse> {
19
+ if (!this.apiKey) {
20
+ throw new Error("Anthropic API key is not configured. Run 'wide config set-key claude <YOUR_KEY>' or set ANTHROPIC_API_KEY.");
21
+ }
22
+
23
+ const systemMsg = messages.find(m => m.role === "system");
24
+ const chatMsgs = messages.filter(m => m.role !== "system");
25
+
26
+ const anthropicMessages = chatMsgs.map(m => {
27
+ if (m.role === "tool") {
28
+ return {
29
+ role: "user",
30
+ content: [
31
+ {
32
+ type: "tool_result",
33
+ tool_use_id: m.toolCallId || "tool_call",
34
+ content: m.content
35
+ }
36
+ ]
37
+ };
38
+ }
39
+ if (m.role === "assistant" && m.toolCalls && m.toolCalls.length > 0) {
40
+ const contentBlocks: any[] = [];
41
+ if (m.content) {
42
+ contentBlocks.push({ type: "text", text: m.content });
43
+ }
44
+ for (const tc of m.toolCalls) {
45
+ contentBlocks.push({
46
+ type: "tool_use",
47
+ id: tc.id,
48
+ name: tc.name,
49
+ input: tc.arguments
50
+ });
51
+ }
52
+ return { role: "assistant", content: contentBlocks };
53
+ }
54
+ return { role: m.role, content: m.content };
55
+ });
56
+
57
+ const anthropicTools = tools.map(t => ({
58
+ name: t.name,
59
+ description: t.description,
60
+ input_schema: {
61
+ type: "object",
62
+ properties: t.parameters.properties,
63
+ required: t.parameters.required
64
+ }
65
+ }));
66
+
67
+ const body: any = {
68
+ model: this.model,
69
+ max_tokens: 4096,
70
+ messages: anthropicMessages,
71
+ stream: true
72
+ };
73
+
74
+ if (systemMsg) {
75
+ body.system = systemMsg.content;
76
+ }
77
+
78
+ if (anthropicTools.length > 0) {
79
+ body.tools = anthropicTools;
80
+ }
81
+
82
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
83
+ method: "POST",
84
+ headers: {
85
+ "Content-Type": "application/json",
86
+ "x-api-key": this.apiKey,
87
+ "anthropic-version": "2023-06-01"
88
+ },
89
+ body: JSON.stringify(body)
90
+ });
91
+
92
+ if (!res.ok) {
93
+ const errText = await res.text();
94
+ throw new Error(`Claude API error (${res.status}): ${errText}`);
95
+ }
96
+
97
+ const reader = res.body?.getReader();
98
+ if (!reader) throw new Error("Could not acquire stream reader from Claude response.");
99
+
100
+ const decoder = new TextDecoder();
101
+ let fullText = "";
102
+ const toolCallMap = new Map<number, { id: string; name: string; inputStr: string }>();
103
+ let buffer = "";
104
+
105
+ while (true) {
106
+ const { done, value } = await reader.read();
107
+ if (done) break;
108
+
109
+ buffer += decoder.decode(value, { stream: true });
110
+ const lines = buffer.split("\n");
111
+ buffer = lines.pop() || "";
112
+
113
+ for (const line of lines) {
114
+ if (!line.startsWith("data: ")) continue;
115
+ const jsonStr = line.slice(6).trim();
116
+ if (!jsonStr || jsonStr === "[DONE]") continue;
117
+
118
+ try {
119
+ const evt = JSON.parse(jsonStr);
120
+ if (evt.type === "content_block_start") {
121
+ if (evt.content_block?.type === "tool_use") {
122
+ toolCallMap.set(evt.index, {
123
+ id: evt.content_block.id,
124
+ name: evt.content_block.name,
125
+ inputStr: ""
126
+ });
127
+ }
128
+ } else if (evt.type === "content_block_delta") {
129
+ if (evt.delta?.type === "text_delta") {
130
+ fullText += evt.delta.text;
131
+ onChunk(evt.delta.text);
132
+ } else if (evt.delta?.type === "input_json_delta") {
133
+ const current = toolCallMap.get(evt.index);
134
+ if (current) {
135
+ current.inputStr += evt.delta.partial_json;
136
+ }
137
+ }
138
+ }
139
+ } catch {
140
+ }
141
+ }
142
+ }
143
+
144
+ const collectedToolCalls: ToolCall[] = [];
145
+ toolCallMap.forEach(v => {
146
+ let args = {};
147
+ try {
148
+ args = JSON.parse(v.inputStr || "{}");
149
+ } catch {
150
+ }
151
+ collectedToolCalls.push({
152
+ id: v.id,
153
+ name: v.name,
154
+ arguments: args
155
+ });
156
+ });
157
+
158
+ return {
159
+ content: fullText,
160
+ toolCalls: collectedToolCalls.length > 0 ? collectedToolCalls : undefined
161
+ };
162
+ }
163
+ }
@@ -0,0 +1,147 @@
1
+ import type { LLMProvider, ChatMessage, ProviderResponse, ToolCall } from "./types.js";
2
+ import type { ToolDefinition } from "../tools/types.js";
3
+
4
+ export class GeminiProvider implements LLMProvider {
5
+ public name = "gemini";
6
+ private apiKey: string;
7
+ private model: string;
8
+
9
+ constructor(apiKey: string, model = "gemini-2.5-flash") {
10
+ this.apiKey = apiKey;
11
+ this.model = model;
12
+ }
13
+
14
+ async chatStream(
15
+ messages: ChatMessage[],
16
+ tools: ToolDefinition[],
17
+ onChunk: (chunk: string) => void
18
+ ): Promise<ProviderResponse> {
19
+ if (!this.apiKey) {
20
+ throw new Error("Gemini API key is not configured. Run 'wide config set-key gemini <YOUR_KEY>' or set GEMINI_API_KEY.");
21
+ }
22
+
23
+ const systemMsg = messages.find(m => m.role === "system");
24
+ const chatMsgs = messages.filter(m => m.role !== "system");
25
+
26
+ const contents = chatMsgs.map(m => {
27
+ if (m.role === "user") {
28
+ return { role: "user", parts: [{ text: m.content }] };
29
+ }
30
+ if (m.role === "assistant") {
31
+ const parts: any[] = [];
32
+ if (m.content) parts.push({ text: m.content });
33
+ if (m.toolCalls && m.toolCalls.length > 0) {
34
+ for (const tc of m.toolCalls) {
35
+ parts.push({
36
+ functionCall: {
37
+ name: tc.name,
38
+ args: tc.arguments
39
+ }
40
+ });
41
+ }
42
+ }
43
+ return { role: "model", parts };
44
+ }
45
+ if (m.role === "tool") {
46
+ return {
47
+ role: "user",
48
+ parts: [{
49
+ functionResponse: {
50
+ name: m.name || "tool_result",
51
+ response: { output: m.content }
52
+ }
53
+ }]
54
+ };
55
+ }
56
+ return { role: "user", parts: [{ text: m.content }] };
57
+ });
58
+
59
+ const functionDeclarations = tools.map(t => ({
60
+ name: t.name,
61
+ description: t.description,
62
+ parameters: {
63
+ type: "OBJECT",
64
+ properties: t.parameters.properties,
65
+ required: t.parameters.required
66
+ }
67
+ }));
68
+
69
+ const body: any = {
70
+ contents,
71
+ generationConfig: {
72
+ temperature: 0.2,
73
+ }
74
+ };
75
+
76
+ if (systemMsg) {
77
+ body.systemInstruction = {
78
+ parts: [{ text: systemMsg.content }]
79
+ };
80
+ }
81
+
82
+ if (functionDeclarations.length > 0) {
83
+ body.tools = [{ functionDeclarations }];
84
+ }
85
+
86
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:streamGenerateContent?alt=sse&key=${this.apiKey}`;
87
+ const response = await fetch(url, {
88
+ method: "POST",
89
+ headers: { "Content-Type": "application/json" },
90
+ body: JSON.stringify(body)
91
+ });
92
+
93
+ if (!response.ok) {
94
+ const errText = await response.text();
95
+ throw new Error(`Gemini API error (${response.status}): ${errText}`);
96
+ }
97
+
98
+ const reader = response.body?.getReader();
99
+ if (!reader) throw new Error("Could not acquire stream reader from Gemini response.");
100
+
101
+ const decoder = new TextDecoder();
102
+ let fullText = "";
103
+ const collectedToolCalls: ToolCall[] = [];
104
+ let buffer = "";
105
+
106
+ while (true) {
107
+ const { done, value } = await reader.read();
108
+ if (done) break;
109
+
110
+ buffer += decoder.decode(value, { stream: true });
111
+ const lines = buffer.split("\n");
112
+ buffer = lines.pop() || "";
113
+
114
+ for (const line of lines) {
115
+ if (!line.startsWith("data: ")) continue;
116
+ const jsonStr = line.slice(6).trim();
117
+ if (!jsonStr) continue;
118
+
119
+ try {
120
+ const parsed = JSON.parse(jsonStr);
121
+ const candidate = parsed.candidates?.[0];
122
+ const parts = candidate?.content?.parts || [];
123
+
124
+ for (const part of parts) {
125
+ if (part.text) {
126
+ fullText += part.text;
127
+ onChunk(part.text);
128
+ }
129
+ if (part.functionCall) {
130
+ collectedToolCalls.push({
131
+ id: `call_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
132
+ name: part.functionCall.name,
133
+ arguments: part.functionCall.args || {}
134
+ });
135
+ }
136
+ }
137
+ } catch {
138
+ }
139
+ }
140
+ }
141
+
142
+ return {
143
+ content: fullText,
144
+ toolCalls: collectedToolCalls.length > 0 ? collectedToolCalls : undefined
145
+ };
146
+ }
147
+ }
@@ -0,0 +1,52 @@
1
+ import { configManager } from "../config/index.js";
2
+ import { GeminiProvider } from "./gemini.js";
3
+ import { OllamaProvider } from "./ollama.js";
4
+ import { ClaudeProvider } from "./claude.js";
5
+ import { OpenAICompatibleProvider } from "./openai.js";
6
+ import type { LLMProvider } from "./types.js";
7
+
8
+ export function createProvider(overrideProvider?: string, overrideModel?: string): LLMProvider {
9
+ const cfg = configManager.get();
10
+ const providerType = overrideProvider || cfg.provider;
11
+ const modelName = overrideModel || cfg.model;
12
+
13
+ if (providerType === "gemini") {
14
+ const key = configManager.getApiKey("gemini");
15
+ if (!key) {
16
+ throw new Error("Gemini API key is required. Run 'wide config set-key gemini <YOUR_KEY>' or set GEMINI_API_KEY.");
17
+ }
18
+ return new GeminiProvider(key, modelName || "gemini-2.5-flash");
19
+ }
20
+
21
+ if (providerType === "ollama") {
22
+ return new OllamaProvider(cfg.ollamaBaseUrl, modelName || "deepseek-r1:7b");
23
+ }
24
+
25
+ if (providerType === "claude") {
26
+ const key = configManager.getApiKey("claude");
27
+ if (!key) {
28
+ throw new Error("Claude API key is required. Run 'wide config set-key claude <YOUR_KEY>' or set ANTHROPIC_API_KEY.");
29
+ }
30
+ return new ClaudeProvider(key, modelName || "claude-3-7-sonnet-20250219");
31
+ }
32
+
33
+ if (providerType === "deepseek") {
34
+ const key = configManager.getApiKey("deepseek");
35
+ if (!key) {
36
+ throw new Error("DeepSeek API key is required. Run 'wide config set-key deepseek <YOUR_KEY>' or set DEEPSEEK_API_KEY.");
37
+ }
38
+ return new OpenAICompatibleProvider("deepseek", key, modelName || "deepseek-chat", "https://api.deepseek.com/v1");
39
+ }
40
+
41
+ if (providerType === "openai") {
42
+ const key = configManager.getApiKey("openai");
43
+ if (!key) {
44
+ throw new Error("OpenAI API key is required. Run 'wide config set-key openai <YOUR_KEY>' or set OPENAI_API_KEY.");
45
+ }
46
+ return new OpenAICompatibleProvider("openai", key, modelName || "gpt-4o", "https://api.openai.com/v1");
47
+ }
48
+
49
+ throw new Error(`Unsupported provider: '${providerType}'. Supported: gemini, ollama, claude, deepseek, openai.`);
50
+ }
51
+
52
+ export * from "./types.js";
@@ -0,0 +1,108 @@
1
+ import type { LLMProvider, ChatMessage, ProviderResponse, ToolCall } from "./types.js";
2
+ import type { ToolDefinition } from "../tools/types.js";
3
+
4
+ export class OllamaProvider implements LLMProvider {
5
+ public name = "ollama";
6
+ private baseUrl: string;
7
+ private model: string;
8
+
9
+ constructor(baseUrl = "http://localhost:11434", model = "deepseek-r1:7b") {
10
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
11
+ this.model = model;
12
+ }
13
+
14
+ async chatStream(
15
+ messages: ChatMessage[],
16
+ tools: ToolDefinition[],
17
+ onChunk: (chunk: string) => void
18
+ ): Promise<ProviderResponse> {
19
+ const formattedMessages = messages.map(m => {
20
+ if (m.role === "tool") {
21
+ return { role: "tool", content: m.content, name: m.name };
22
+ }
23
+ return { role: m.role, content: m.content };
24
+ });
25
+
26
+ const formattedTools = tools.map(t => ({
27
+ type: "function",
28
+ function: {
29
+ name: t.name,
30
+ description: t.description,
31
+ parameters: t.parameters
32
+ }
33
+ }));
34
+
35
+ const body: any = {
36
+ model: this.model,
37
+ messages: formattedMessages,
38
+ stream: true,
39
+ options: {
40
+ temperature: 0.2
41
+ }
42
+ };
43
+
44
+ if (formattedTools.length > 0) {
45
+ body.tools = formattedTools;
46
+ }
47
+
48
+ let response: Response;
49
+ try {
50
+ response = await fetch(`${this.baseUrl}/api/chat`, {
51
+ method: "POST",
52
+ headers: { "Content-Type": "application/json" },
53
+ body: JSON.stringify(body)
54
+ });
55
+ } catch (err: any) {
56
+ throw new Error(`Failed to connect to Ollama at ${this.baseUrl}: ${err.message}. Is Ollama running?`);
57
+ }
58
+
59
+ if (!response.ok) {
60
+ const errText = await response.text();
61
+ throw new Error(`Ollama error (${response.status}): ${errText}`);
62
+ }
63
+
64
+ const reader = response.body?.getReader();
65
+ if (!reader) throw new Error("Could not acquire stream reader from Ollama.");
66
+
67
+ const decoder = new TextDecoder();
68
+ let fullText = "";
69
+ const collectedToolCalls: ToolCall[] = [];
70
+ let buffer = "";
71
+
72
+ while (true) {
73
+ const { done, value } = await reader.read();
74
+ if (done) break;
75
+
76
+ buffer += decoder.decode(value, { stream: true });
77
+ const lines = buffer.split("\n");
78
+ buffer = lines.pop() || "";
79
+
80
+ for (const line of lines) {
81
+ if (!line.trim()) continue;
82
+ try {
83
+ const parsed = JSON.parse(line);
84
+ const msg = parsed.message;
85
+ if (msg?.content) {
86
+ fullText += msg.content;
87
+ onChunk(msg.content);
88
+ }
89
+ if (msg?.tool_calls) {
90
+ for (const tc of msg.tool_calls) {
91
+ collectedToolCalls.push({
92
+ id: `call_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
93
+ name: tc.function.name,
94
+ arguments: tc.function.arguments || {}
95
+ });
96
+ }
97
+ }
98
+ } catch {
99
+ }
100
+ }
101
+ }
102
+
103
+ return {
104
+ content: fullText,
105
+ toolCalls: collectedToolCalls.length > 0 ? collectedToolCalls : undefined
106
+ };
107
+ }
108
+ }
@@ -0,0 +1,159 @@
1
+ import type { LLMProvider, ChatMessage, ProviderResponse, ToolCall } from "./types.js";
2
+ import type { ToolDefinition } from "../tools/types.js";
3
+
4
+ export class OpenAICompatibleProvider implements LLMProvider {
5
+ public name: string;
6
+ private apiKey: string;
7
+ private model: string;
8
+ private baseUrl: string;
9
+
10
+ constructor(
11
+ name: string,
12
+ apiKey: string,
13
+ model: string,
14
+ baseUrl = "https://api.openai.com/v1"
15
+ ) {
16
+ this.name = name;
17
+ this.apiKey = apiKey;
18
+ this.model = model;
19
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
20
+ }
21
+
22
+ async chatStream(
23
+ messages: ChatMessage[],
24
+ tools: ToolDefinition[],
25
+ onChunk: (chunk: string) => void
26
+ ): Promise<ProviderResponse> {
27
+ if (!this.apiKey) {
28
+ throw new Error(`${this.name.toUpperCase()} API key is not configured. Run 'wide config set-key ${this.name} <YOUR_KEY>'.`);
29
+ }
30
+
31
+ const openAiMessages = messages.map(m => {
32
+ if (m.role === "tool") {
33
+ return {
34
+ role: "tool",
35
+ tool_call_id: m.toolCallId || "tool_call",
36
+ content: m.content
37
+ };
38
+ }
39
+ if (m.role === "assistant" && m.toolCalls && m.toolCalls.length > 0) {
40
+ return {
41
+ role: "assistant",
42
+ content: m.content || null,
43
+ tool_calls: m.toolCalls.map(tc => ({
44
+ id: tc.id,
45
+ type: "function",
46
+ function: {
47
+ name: tc.name,
48
+ arguments: JSON.stringify(tc.arguments)
49
+ }
50
+ }))
51
+ };
52
+ }
53
+ return { role: m.role, content: m.content };
54
+ });
55
+
56
+ const openAiTools = tools.map(t => ({
57
+ type: "function",
58
+ function: {
59
+ name: t.name,
60
+ description: t.description,
61
+ parameters: t.parameters
62
+ }
63
+ }));
64
+
65
+ const body: any = {
66
+ model: this.model,
67
+ messages: openAiMessages,
68
+ stream: true,
69
+ temperature: 0.2
70
+ };
71
+
72
+ if (openAiTools.length > 0) {
73
+ body.tools = openAiTools;
74
+ }
75
+
76
+ const res = await fetch(`${this.baseUrl}/chat/completions`, {
77
+ method: "POST",
78
+ headers: {
79
+ "Content-Type": "application/json",
80
+ "Authorization": `Bearer ${this.apiKey}`
81
+ },
82
+ body: JSON.stringify(body)
83
+ });
84
+
85
+ if (!res.ok) {
86
+ const errText = await res.text();
87
+ throw new Error(`${this.name} API error (${res.status}): ${errText}`);
88
+ }
89
+
90
+ const reader = res.body?.getReader();
91
+ if (!reader) throw new Error(`Could not acquire stream reader from ${this.name}.`);
92
+
93
+ const decoder = new TextDecoder();
94
+ let fullText = "";
95
+ const toolCallAccumulators = new Map<number, { id: string; name: string; argsStr: string }>();
96
+ let buffer = "";
97
+
98
+ while (true) {
99
+ const { done, value } = await reader.read();
100
+ if (done) break;
101
+
102
+ buffer += decoder.decode(value, { stream: true });
103
+ const lines = buffer.split("\n");
104
+ buffer = lines.pop() || "";
105
+
106
+ for (const line of lines) {
107
+ if (!line.startsWith("data: ")) continue;
108
+ const jsonStr = line.slice(6).trim();
109
+ if (!jsonStr || jsonStr === "[DONE]") continue;
110
+
111
+ try {
112
+ const parsed = JSON.parse(jsonStr);
113
+ const delta = parsed.choices?.[0]?.delta;
114
+ if (delta?.content) {
115
+ fullText += delta.content;
116
+ onChunk(delta.content);
117
+ }
118
+ if (delta?.tool_calls) {
119
+ for (const tc of delta.tool_calls) {
120
+ const idx = tc.index ?? 0;
121
+ if (!toolCallAccumulators.has(idx)) {
122
+ toolCallAccumulators.set(idx, {
123
+ id: tc.id || `call_${Date.now()}_${idx}`,
124
+ name: tc.function?.name || "",
125
+ argsStr: tc.function?.arguments || ""
126
+ });
127
+ } else {
128
+ const acc = toolCallAccumulators.get(idx)!;
129
+ if (tc.id) acc.id = tc.id;
130
+ if (tc.function?.name) acc.name += tc.function.name;
131
+ if (tc.function?.arguments) acc.argsStr += tc.function.arguments;
132
+ }
133
+ }
134
+ }
135
+ } catch {
136
+ }
137
+ }
138
+ }
139
+
140
+ const collectedToolCalls: ToolCall[] = [];
141
+ toolCallAccumulators.forEach(v => {
142
+ let args = {};
143
+ try {
144
+ args = JSON.parse(v.argsStr || "{}");
145
+ } catch {
146
+ }
147
+ collectedToolCalls.push({
148
+ id: v.id,
149
+ name: v.name,
150
+ arguments: args
151
+ });
152
+ });
153
+
154
+ return {
155
+ content: fullText,
156
+ toolCalls: collectedToolCalls.length > 0 ? collectedToolCalls : undefined
157
+ };
158
+ }
159
+ }
@@ -0,0 +1,29 @@
1
+ import type { ToolDefinition } from "../tools/types.js";
2
+
3
+ export interface ToolCall {
4
+ id: string;
5
+ name: string;
6
+ arguments: Record<string, any>;
7
+ }
8
+
9
+ export interface ChatMessage {
10
+ role: "system" | "user" | "assistant" | "tool";
11
+ content: string;
12
+ toolCalls?: ToolCall[];
13
+ toolCallId?: string;
14
+ name?: string;
15
+ }
16
+
17
+ export interface ProviderResponse {
18
+ content: string;
19
+ toolCalls?: ToolCall[];
20
+ }
21
+
22
+ export interface LLMProvider {
23
+ name: string;
24
+ chatStream(
25
+ messages: ChatMessage[],
26
+ tools: ToolDefinition[],
27
+ onChunk: (chunk: string) => void
28
+ ): Promise<ProviderResponse>;
29
+ }