@chatcops/core 0.4.0 → 0.6.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 (243) hide show
  1. package/dist/agent/chat.d.ts +13 -0
  2. package/dist/agent/chat.d.ts.map +1 -0
  3. package/dist/agent/chat.js +42 -0
  4. package/dist/agent/chat.js.map +1 -0
  5. package/dist/agent/errors.d.ts +14 -0
  6. package/dist/agent/errors.d.ts.map +1 -0
  7. package/dist/agent/errors.js +24 -0
  8. package/dist/agent/errors.js.map +1 -0
  9. package/dist/agent/index.d.ts +5 -0
  10. package/dist/agent/index.d.ts.map +1 -0
  11. package/dist/agent/index.js +5 -0
  12. package/dist/agent/index.js.map +1 -0
  13. package/dist/agent/run-turn.d.ts +79 -0
  14. package/dist/agent/run-turn.d.ts.map +1 -0
  15. package/dist/agent/run-turn.js +400 -0
  16. package/dist/agent/run-turn.js.map +1 -0
  17. package/dist/agent/tool-registry.d.ts +30 -0
  18. package/dist/agent/tool-registry.d.ts.map +1 -0
  19. package/dist/agent/tool-registry.js +66 -0
  20. package/dist/agent/tool-registry.js.map +1 -0
  21. package/dist/analytics/collector.d.ts +2 -0
  22. package/dist/analytics/collector.d.ts.map +1 -1
  23. package/dist/analytics/collector.js +16 -10
  24. package/dist/analytics/collector.js.map +1 -1
  25. package/dist/analytics/index.d.ts +2 -0
  26. package/dist/analytics/index.d.ts.map +1 -1
  27. package/dist/analytics/index.js +2 -0
  28. package/dist/analytics/index.js.map +1 -1
  29. package/dist/analytics/names.d.ts +21 -0
  30. package/dist/analytics/names.d.ts.map +1 -0
  31. package/dist/analytics/names.js +41 -0
  32. package/dist/analytics/names.js.map +1 -0
  33. package/dist/analytics/sink.d.ts +27 -0
  34. package/dist/analytics/sink.d.ts.map +1 -0
  35. package/dist/analytics/sink.js +109 -0
  36. package/dist/analytics/sink.js.map +1 -0
  37. package/dist/conversation/index.d.ts +1 -0
  38. package/dist/conversation/index.d.ts.map +1 -1
  39. package/dist/conversation/index.js.map +1 -1
  40. package/dist/conversation/manager.d.ts +65 -6
  41. package/dist/conversation/manager.d.ts.map +1 -1
  42. package/dist/conversation/manager.js +110 -34
  43. package/dist/conversation/manager.js.map +1 -1
  44. package/dist/conversation/store.d.ts +6 -5
  45. package/dist/conversation/store.d.ts.map +1 -1
  46. package/dist/conversation/store.js +4 -0
  47. package/dist/conversation/store.js.map +1 -1
  48. package/dist/index.d.ts +21 -4
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +16 -2
  51. package/dist/index.js.map +1 -1
  52. package/dist/knowledge/base.d.ts +8 -0
  53. package/dist/knowledge/base.d.ts.map +1 -1
  54. package/dist/knowledge/tokenize.d.ts.map +1 -1
  55. package/dist/knowledge/tokenize.js +4 -4
  56. package/dist/knowledge/tokenize.js.map +1 -1
  57. package/dist/limits/budget.d.ts +84 -0
  58. package/dist/limits/budget.d.ts.map +1 -0
  59. package/dist/limits/budget.js +114 -0
  60. package/dist/limits/budget.js.map +1 -0
  61. package/dist/limits/rate-limit.d.ts +53 -0
  62. package/dist/limits/rate-limit.d.ts.map +1 -0
  63. package/dist/limits/rate-limit.js +68 -0
  64. package/dist/limits/rate-limit.js.map +1 -0
  65. package/dist/logger.d.ts +36 -0
  66. package/dist/logger.d.ts.map +1 -0
  67. package/dist/logger.js +40 -0
  68. package/dist/logger.js.map +1 -0
  69. package/dist/parts.d.ts +9 -0
  70. package/dist/parts.d.ts.map +1 -0
  71. package/dist/parts.js +17 -0
  72. package/dist/parts.js.map +1 -0
  73. package/dist/protocol/ai-sdk.d.ts +27 -0
  74. package/dist/protocol/ai-sdk.d.ts.map +1 -0
  75. package/dist/protocol/ai-sdk.js +127 -0
  76. package/dist/protocol/ai-sdk.js.map +1 -0
  77. package/dist/protocol/errors.d.ts +10 -0
  78. package/dist/protocol/errors.d.ts.map +1 -0
  79. package/dist/protocol/errors.js +42 -0
  80. package/dist/protocol/errors.js.map +1 -0
  81. package/dist/protocol/index.d.ts +9 -0
  82. package/dist/protocol/index.d.ts.map +1 -0
  83. package/dist/protocol/index.js +6 -0
  84. package/dist/protocol/index.js.map +1 -0
  85. package/dist/protocol/legacy.d.ts +18 -0
  86. package/dist/protocol/legacy.d.ts.map +1 -0
  87. package/dist/protocol/legacy.js +41 -0
  88. package/dist/protocol/legacy.js.map +1 -0
  89. package/dist/protocol/sse.d.ts +10 -0
  90. package/dist/protocol/sse.d.ts.map +1 -0
  91. package/dist/protocol/sse.js +15 -0
  92. package/dist/protocol/sse.js.map +1 -0
  93. package/dist/protocol/v1.d.ts +140 -0
  94. package/dist/protocol/v1.d.ts.map +1 -0
  95. package/dist/protocol/v1.js +15 -0
  96. package/dist/protocol/v1.js.map +1 -0
  97. package/dist/providers/base.d.ts +13 -28
  98. package/dist/providers/base.d.ts.map +1 -1
  99. package/dist/providers/base.js +36 -47
  100. package/dist/providers/base.js.map +1 -1
  101. package/dist/providers/claude.d.ts +41 -6
  102. package/dist/providers/claude.d.ts.map +1 -1
  103. package/dist/providers/claude.js +223 -96
  104. package/dist/providers/claude.js.map +1 -1
  105. package/dist/providers/gemini.d.ts +18 -3
  106. package/dist/providers/gemini.d.ts.map +1 -1
  107. package/dist/providers/gemini.js +208 -91
  108. package/dist/providers/gemini.js.map +1 -1
  109. package/dist/providers/history.d.ts +52 -0
  110. package/dist/providers/history.d.ts.map +1 -0
  111. package/dist/providers/history.js +212 -0
  112. package/dist/providers/history.js.map +1 -0
  113. package/dist/providers/index.d.ts +5 -5
  114. package/dist/providers/index.d.ts.map +1 -1
  115. package/dist/providers/index.js +5 -4
  116. package/dist/providers/index.js.map +1 -1
  117. package/dist/providers/openai.d.ts +28 -6
  118. package/dist/providers/openai.d.ts.map +1 -1
  119. package/dist/providers/openai.js +213 -113
  120. package/dist/providers/openai.js.map +1 -1
  121. package/dist/providers/registry.d.ts +7 -0
  122. package/dist/providers/registry.d.ts.map +1 -0
  123. package/dist/providers/registry.js +12 -0
  124. package/dist/providers/registry.js.map +1 -0
  125. package/dist/providers/schema.d.ts +16 -0
  126. package/dist/providers/schema.d.ts.map +1 -0
  127. package/dist/providers/schema.js +80 -0
  128. package/dist/providers/schema.js.map +1 -0
  129. package/dist/providers/tool-execution.d.ts +13 -0
  130. package/dist/providers/tool-execution.d.ts.map +1 -1
  131. package/dist/providers/tool-execution.js +49 -13
  132. package/dist/providers/tool-execution.js.map +1 -1
  133. package/dist/providers/types.d.ts +89 -0
  134. package/dist/providers/types.d.ts.map +1 -0
  135. package/dist/providers/types.js +2 -0
  136. package/dist/providers/types.js.map +1 -0
  137. package/dist/retrieval/citations.d.ts +44 -0
  138. package/dist/retrieval/citations.d.ts.map +1 -0
  139. package/dist/retrieval/citations.js +97 -0
  140. package/dist/retrieval/citations.js.map +1 -0
  141. package/dist/retrieval/cohere-reranker.d.ts +13 -0
  142. package/dist/retrieval/cohere-reranker.d.ts.map +1 -0
  143. package/dist/retrieval/cohere-reranker.js +33 -0
  144. package/dist/retrieval/cohere-reranker.js.map +1 -0
  145. package/dist/retrieval/gemini-embedder.d.ts +26 -0
  146. package/dist/retrieval/gemini-embedder.d.ts.map +1 -0
  147. package/dist/retrieval/gemini-embedder.js +36 -0
  148. package/dist/retrieval/gemini-embedder.js.map +1 -0
  149. package/dist/retrieval/http.d.ts +20 -0
  150. package/dist/retrieval/http.d.ts.map +1 -0
  151. package/dist/retrieval/http.js +68 -0
  152. package/dist/retrieval/http.js.map +1 -0
  153. package/dist/retrieval/index.d.ts +14 -0
  154. package/dist/retrieval/index.d.ts.map +1 -0
  155. package/dist/retrieval/index.js +13 -0
  156. package/dist/retrieval/index.js.map +1 -0
  157. package/dist/retrieval/knowledge.d.ts +16 -0
  158. package/dist/retrieval/knowledge.d.ts.map +1 -0
  159. package/dist/retrieval/knowledge.js +21 -0
  160. package/dist/retrieval/knowledge.js.map +1 -0
  161. package/dist/retrieval/openai-embedder.d.ts +25 -0
  162. package/dist/retrieval/openai-embedder.d.ts.map +1 -0
  163. package/dist/retrieval/openai-embedder.js +30 -0
  164. package/dist/retrieval/openai-embedder.js.map +1 -0
  165. package/dist/retrieval/query.d.ts +8 -0
  166. package/dist/retrieval/query.d.ts.map +1 -0
  167. package/dist/retrieval/query.js +19 -0
  168. package/dist/retrieval/query.js.map +1 -0
  169. package/dist/retrieval/retrievers.d.ts +30 -0
  170. package/dist/retrieval/retrievers.d.ts.map +1 -0
  171. package/dist/retrieval/retrievers.js +89 -0
  172. package/dist/retrieval/retrievers.js.map +1 -0
  173. package/dist/retrieval/sources.d.ts +16 -0
  174. package/dist/retrieval/sources.d.ts.map +1 -0
  175. package/dist/retrieval/sources.js +37 -0
  176. package/dist/retrieval/sources.js.map +1 -0
  177. package/dist/retrieval/types.d.ts +50 -0
  178. package/dist/retrieval/types.d.ts.map +1 -0
  179. package/dist/retrieval/types.js +2 -0
  180. package/dist/retrieval/types.js.map +1 -0
  181. package/dist/retrieval/voyage-embedder.d.ts +33 -0
  182. package/dist/retrieval/voyage-embedder.d.ts.map +1 -0
  183. package/dist/retrieval/voyage-embedder.js +33 -0
  184. package/dist/retrieval/voyage-embedder.js.map +1 -0
  185. package/dist/retrieval/voyage-reranker.d.ts +13 -0
  186. package/dist/retrieval/voyage-reranker.d.ts.map +1 -0
  187. package/dist/retrieval/voyage-reranker.js +38 -0
  188. package/dist/retrieval/voyage-reranker.js.map +1 -0
  189. package/dist/retrieval/workers-ai-embedder.d.ts +21 -0
  190. package/dist/retrieval/workers-ai-embedder.d.ts.map +1 -0
  191. package/dist/retrieval/workers-ai-embedder.js +42 -0
  192. package/dist/retrieval/workers-ai-embedder.js.map +1 -0
  193. package/dist/retrieval/workers-ai-reranker.d.ts +11 -0
  194. package/dist/retrieval/workers-ai-reranker.d.ts.map +1 -0
  195. package/dist/retrieval/workers-ai-reranker.js +54 -0
  196. package/dist/retrieval/workers-ai-reranker.js.map +1 -0
  197. package/dist/storage/adapt.d.ts +15 -0
  198. package/dist/storage/adapt.d.ts.map +1 -0
  199. package/dist/storage/adapt.js +83 -0
  200. package/dist/storage/adapt.js.map +1 -0
  201. package/dist/storage/errors.d.ts +18 -0
  202. package/dist/storage/errors.d.ts.map +1 -0
  203. package/dist/storage/errors.js +28 -0
  204. package/dist/storage/errors.js.map +1 -0
  205. package/dist/storage/index.d.ts +6 -0
  206. package/dist/storage/index.d.ts.map +1 -0
  207. package/dist/storage/index.js +5 -0
  208. package/dist/storage/index.js.map +1 -0
  209. package/dist/storage/memory-vectors.d.ts +22 -0
  210. package/dist/storage/memory-vectors.d.ts.map +1 -0
  211. package/dist/storage/memory-vectors.js +140 -0
  212. package/dist/storage/memory-vectors.js.map +1 -0
  213. package/dist/storage/memory.d.ts +24 -0
  214. package/dist/storage/memory.d.ts.map +1 -0
  215. package/dist/storage/memory.js +265 -0
  216. package/dist/storage/memory.js.map +1 -0
  217. package/dist/storage/types.d.ts +188 -0
  218. package/dist/storage/types.d.ts.map +1 -0
  219. package/dist/storage/types.js +2 -0
  220. package/dist/storage/types.js.map +1 -0
  221. package/dist/testing/conformance.d.ts +30 -0
  222. package/dist/testing/conformance.d.ts.map +1 -0
  223. package/dist/testing/conformance.js +505 -0
  224. package/dist/testing/conformance.js.map +1 -0
  225. package/dist/testing/index.d.ts +3 -0
  226. package/dist/testing/index.d.ts.map +1 -0
  227. package/dist/testing/index.js +5 -0
  228. package/dist/testing/index.js.map +1 -0
  229. package/dist/testing/provider.d.ts +47 -0
  230. package/dist/testing/provider.d.ts.map +1 -0
  231. package/dist/testing/provider.js +83 -0
  232. package/dist/testing/provider.js.map +1 -0
  233. package/dist/tools/base.d.ts +14 -4
  234. package/dist/tools/base.d.ts.map +1 -1
  235. package/dist/tools/base.js +4 -2
  236. package/dist/tools/base.js.map +1 -1
  237. package/dist/tools/lead-capture.d.ts +4 -2
  238. package/dist/tools/lead-capture.d.ts.map +1 -1
  239. package/dist/tools/lead-capture.js +7 -2
  240. package/dist/tools/lead-capture.js.map +1 -1
  241. package/dist/types.d.ts +146 -7
  242. package/dist/types.d.ts.map +1 -1
  243. package/package.json +51 -3
@@ -1,12 +1,14 @@
1
1
  import OpenAI from 'openai';
2
- import { DEFAULT_MAX_TOKENS, normalizeHistory, toOpenAITools, warnOnce } from './base.js';
3
- import { MAX_TOOL_ROUNDS, executeToolCall, parseToolInput, serializeToolResult, toToolFailure, } from './tool-execution.js';
2
+ import { chatSyncViaTurn, chatViaTurn } from '../agent/chat.js';
3
+ import { joinSystem } from '../agent/run-turn.js';
4
+ import { DEFAULT_MAX_TOKENS, toOpenAITools, warnOnce } from './base.js';
5
+ import { consoleLogger } from '../logger.js';
6
+ import { normalizeTurns } from './history.js';
7
+ import { parseToolInput } from './tool-execution.js';
4
8
  const DEFAULT_MODEL = 'gpt-5-mini';
5
9
  const DEFAULT_EFFORT = 'low';
6
- let toolCallSequence = 0;
7
10
  function createToolCallId() {
8
- toolCallSequence += 1;
9
- return `tool_call_${toolCallSequence}`;
11
+ return `call_${crypto.randomUUID()}`;
10
12
  }
11
13
  /**
12
14
  * OpenAI reasoning models (o-series, GPT-5 and later) take `reasoning_effort`
@@ -18,152 +20,250 @@ export function isOpenAIReasoningModel(model, baseURL) {
18
20
  return false;
19
21
  return /^(o\d|gpt-5|gpt-6)/.test(model) && !model.includes('chat-latest');
20
22
  }
23
+ /**
24
+ * Stored history as OpenAI chat messages: the system prompt first, then for
25
+ * each step an assistant message with its `tool_calls`, followed by one
26
+ * `tool` message per result in call order. Reasoning isn't sent back; the
27
+ * chat completions API has no field for it.
28
+ */
29
+ export function toOpenAIStepMessages(systemPrompt, messages) {
30
+ const out = [{ role: 'system', content: systemPrompt }];
31
+ for (const turn of normalizeTurns(messages)) {
32
+ if (turn.role === 'user') {
33
+ for (const part of turn.parts) {
34
+ if (part.type === 'tool-result')
35
+ out.push(toToolMessage(part));
36
+ }
37
+ const text = turn.parts.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('\n\n');
38
+ if (text)
39
+ out.push({ role: 'user', content: text });
40
+ continue;
41
+ }
42
+ let text = '';
43
+ let calls = [];
44
+ const flush = () => {
45
+ if (text || calls.length) {
46
+ out.push({ role: 'assistant', content: text || null, ...(calls.length ? { tool_calls: calls } : {}) });
47
+ }
48
+ text = '';
49
+ calls = [];
50
+ };
51
+ for (const part of turn.parts) {
52
+ if (part.type === 'tool-result') {
53
+ flush();
54
+ out.push(toToolMessage(part));
55
+ }
56
+ else if (part.type === 'text') {
57
+ text += part.text;
58
+ }
59
+ else if (part.type === 'tool-call') {
60
+ calls.push({
61
+ id: part.toolCallId,
62
+ type: 'function',
63
+ function: {
64
+ name: part.toolName,
65
+ arguments: typeof part.input === 'string' ? part.input : JSON.stringify(part.input ?? {}),
66
+ },
67
+ });
68
+ }
69
+ }
70
+ flush();
71
+ }
72
+ return out;
73
+ }
74
+ function toToolMessage(part) {
75
+ return {
76
+ role: 'tool',
77
+ tool_call_id: part.toolCallId,
78
+ content: JSON.stringify(part.output ?? { success: false, message: part.error }),
79
+ };
80
+ }
81
+ /**
82
+ * Some OpenAI-compatible servers (Ollama among them) end a tool step with
83
+ * `stop` instead of `tool_calls`, so any finished step with calls counts.
84
+ */
85
+ function finishReason(reason, hasToolCalls, refused) {
86
+ if (refused)
87
+ return 'refusal';
88
+ if (reason === 'length')
89
+ return 'length';
90
+ if (reason === 'content_filter')
91
+ return 'content-filter';
92
+ if (hasToolCalls)
93
+ return 'tool-calls';
94
+ return 'stop';
95
+ }
96
+ function toUsage(usage) {
97
+ const cached = usage?.prompt_tokens_details?.cached_tokens ?? 0;
98
+ return {
99
+ inputTokens: usage?.prompt_tokens ?? 0,
100
+ outputTokens: usage?.completion_tokens ?? 0,
101
+ ...(cached ? { cacheReadTokens: cached } : {}),
102
+ };
103
+ }
104
+ function rejectsStreamOptions(error) {
105
+ const status = error?.status;
106
+ const message = error instanceof Error ? error.message : '';
107
+ return status === 400 && /stream_options|include_usage/.test(message);
108
+ }
21
109
  export class OpenAIProvider {
22
- name = 'openai';
110
+ name;
23
111
  client;
112
+ logger;
24
113
  model;
25
114
  reasoning;
26
115
  effort;
27
116
  maxTokensParam;
28
- constructor(config) {
117
+ supportsTools;
118
+ /** Set once a server rejects `stream_options`; usage isn't asked for after that. */
119
+ streamUsage = true;
120
+ constructor(config, options = {}) {
121
+ this.logger = config.logger ?? consoleLogger();
122
+ this.name = options.compatible ? 'openai-compatible' : 'openai';
123
+ if (options.compatible) {
124
+ if (!config.baseURL?.trim())
125
+ throw new Error('openai-compatible requires baseURL');
126
+ if (!config.model?.trim())
127
+ throw new Error('openai-compatible requires model');
128
+ }
129
+ else if (!config.apiKey?.trim()) {
130
+ throw new Error('openai requires apiKey');
131
+ }
29
132
  this.client = new OpenAI({
30
- apiKey: config.apiKey,
133
+ apiKey: config.apiKey || 'chatcops-local',
31
134
  ...(config.baseURL ? { baseURL: config.baseURL } : {}),
135
+ ...(config.headers ? { defaultHeaders: config.headers } : {}),
32
136
  ...(config.organization ? { organization: config.organization } : {}),
137
+ ...(config.fetch ? { fetch: config.fetch } : {}),
33
138
  });
34
139
  this.model = config.model ?? DEFAULT_MODEL;
35
140
  this.reasoning = isOpenAIReasoningModel(this.model, config.baseURL);
36
141
  this.effort = config.effort ?? DEFAULT_EFFORT;
37
- this.maxTokensParam = config.maxTokensParam ?? 'max_completion_tokens';
142
+ this.maxTokensParam = config.maxTokensParam ?? (options.compatible ? 'max_tokens' : 'max_completion_tokens');
143
+ this.supportsTools = config.supportsTools ?? true;
38
144
  }
39
145
  request(params, messages) {
146
+ if (!this.supportsTools && params.tools?.length) {
147
+ warnOnce(this.logger, `${this.name}-tools-${this.model}`, `${this.name} model ${this.model} has supportsTools: false, so configured tools are not sent.`);
148
+ }
40
149
  let temperature = params.temperature;
41
150
  if (temperature != null && this.reasoning) {
42
- warnOnce(`openai-temperature-${this.model}`, `${this.model} doesn't accept \`temperature\`, so it is not sent. Use \`effort\` to trade speed for depth.`);
151
+ warnOnce(this.logger, `openai-temperature-${this.model}`, `${this.model} doesn't accept \`temperature\`, so it is not sent. Use \`effort\` to trade speed for depth.`);
43
152
  temperature = undefined;
44
153
  }
45
154
  return {
46
155
  model: this.model,
47
156
  messages,
48
157
  [this.maxTokensParam]: params.maxTokens ?? DEFAULT_MAX_TOKENS,
49
- ...(params.tools?.length ? { tools: toOpenAITools(params.tools) } : {}),
158
+ ...(this.supportsTools && params.tools?.length ? { tools: toOpenAITools(params.tools) } : {}),
50
159
  ...(temperature != null ? { temperature } : {}),
51
160
  ...(this.reasoning ? { reasoning_effort: this.effort } : {}),
52
161
  };
53
162
  }
54
- toMessages(params) {
55
- return [
56
- { role: 'system', content: params.systemPrompt },
57
- ...normalizeHistory(params.messages).map((message) => ({
58
- role: message.role,
59
- content: message.content,
60
- })),
61
- ];
62
- }
63
- async *chat(params) {
64
- const messages = this.toMessages(params);
65
- let toolRounds = 0;
66
- while (true) {
67
- params.signal?.throwIfAborted();
68
- const stream = await this.client.chat.completions.create({ ...this.request(params, messages), stream: true }, { signal: params.signal });
69
- let finishReason = null;
70
- let assistantText = '';
71
- const toolCalls = new Map();
72
- for await (const chunk of stream) {
73
- const choice = chunk.choices[0];
74
- if (!choice)
75
- continue;
76
- finishReason = choice.finish_reason ?? finishReason;
77
- const deltaText = choice.delta?.content;
78
- if (deltaText) {
79
- assistantText += deltaText;
80
- yield deltaText;
81
- }
82
- for (const toolCallDelta of choice.delta?.tool_calls ?? []) {
83
- if (toolCallDelta.type && toolCallDelta.type !== 'function')
84
- continue;
85
- const existing = toolCalls.get(toolCallDelta.index) ?? {
86
- id: toolCallDelta.id ?? createToolCallId(),
87
- type: 'function',
88
- function: { name: '', arguments: '' },
89
- };
90
- if (toolCallDelta.id) {
91
- existing.id = toolCallDelta.id;
92
- }
93
- if (toolCallDelta.function?.name) {
94
- existing.function.name = toolCallDelta.function.name;
95
- }
96
- if (toolCallDelta.function?.arguments) {
97
- existing.function.arguments += toolCallDelta.function.arguments;
98
- }
99
- toolCalls.set(toolCallDelta.index, existing);
100
- }
101
- }
102
- const completedToolCalls = Array.from(toolCalls.entries())
103
- .sort(([left], [right]) => left - right)
104
- .map(([, toolCall]) => toolCall);
105
- if (finishReason === 'length') {
106
- console.warn('[chatcops] OpenAI reply cut off at the token limit. Raise `maxTokens` if this keeps happening.');
107
- }
108
- if (finishReason !== 'tool_calls' || completedToolCalls.length === 0) {
109
- return;
163
+ async openStream(params) {
164
+ const system = joinSystem(params.systemPrompt, params.systemContext);
165
+ const body = { ...this.request(params, toOpenAIStepMessages(system, params.messages)), stream: true };
166
+ if (this.streamUsage) {
167
+ try {
168
+ return await this.client.chat.completions.create({ ...body, stream_options: { include_usage: true } }, { signal: params.signal });
110
169
  }
111
- if (toolRounds >= MAX_TOOL_ROUNDS) {
112
- throw new Error(`Exceeded maximum tool rounds (${MAX_TOOL_ROUNDS}).`);
170
+ catch (error) {
171
+ if (!rejectsStreamOptions(error))
172
+ throw error;
173
+ this.streamUsage = false;
174
+ warnOnce(this.logger, `openai-stream-options-${this.model}`, "The server doesn't accept `stream_options`, so token usage isn't reported for this provider.");
113
175
  }
114
- toolRounds += 1;
115
- messages.push({
116
- role: 'assistant',
117
- content: assistantText || null,
118
- tool_calls: completedToolCalls,
119
- });
120
- messages.push(...await this.runTools(params, completedToolCalls));
121
176
  }
177
+ return this.client.chat.completions.create(body, { signal: params.signal });
122
178
  }
123
- async chatSync(params) {
124
- const messages = this.toMessages(params);
125
- let toolRounds = 0;
126
- while (true) {
127
- params.signal?.throwIfAborted();
128
- const response = await this.client.chat.completions.create(this.request(params, messages), { signal: params.signal });
129
- const choice = response.choices[0];
130
- const assistantMessage = choice?.message;
131
- const toolCalls = (assistantMessage?.tool_calls ?? []).filter((toolCall) => toolCall.type === 'function');
132
- if (choice?.finish_reason !== 'tool_calls' || toolCalls.length === 0) {
133
- return assistantMessage?.content ?? '';
179
+ /** One model request: streams text, then reports tool calls, usage and why it stopped. */
180
+ async *step(params) {
181
+ params.signal?.throwIfAborted();
182
+ const stream = await this.openStream(params);
183
+ let reason = null;
184
+ let usage;
185
+ let text = '';
186
+ let refusal = '';
187
+ const calls = new Map();
188
+ for await (const chunk of stream) {
189
+ // With include_usage, the last chunk carries usage and no choices.
190
+ if (chunk.usage)
191
+ usage = chunk.usage;
192
+ const choice = chunk.choices[0];
193
+ if (!choice)
194
+ continue;
195
+ reason = choice.finish_reason ?? reason;
196
+ const delta = choice.delta;
197
+ if (delta?.content) {
198
+ text += delta.content;
199
+ yield { type: 'text-delta', delta: delta.content };
134
200
  }
135
- if (toolRounds >= MAX_TOOL_ROUNDS) {
136
- throw new Error(`Exceeded maximum tool rounds (${MAX_TOOL_ROUNDS}).`);
201
+ if (delta?.refusal)
202
+ refusal += delta.refusal;
203
+ for (const callDelta of delta?.tool_calls ?? []) {
204
+ if (callDelta.type && callDelta.type !== 'function')
205
+ continue;
206
+ const call = calls.get(callDelta.index) ?? { id: '', synthetic: true, name: '', arguments: '' };
207
+ if (callDelta.id) {
208
+ call.id = callDelta.id;
209
+ call.synthetic = false;
210
+ }
211
+ if (callDelta.function?.name)
212
+ call.name = callDelta.function.name;
213
+ if (callDelta.function?.arguments)
214
+ call.arguments += callDelta.function.arguments;
215
+ calls.set(callDelta.index, call);
137
216
  }
138
- toolRounds += 1;
139
- messages.push({
140
- role: 'assistant',
141
- content: assistantMessage.content,
142
- tool_calls: toolCalls,
143
- });
144
- messages.push(...await this.runTools(params, toolCalls));
145
217
  }
146
- }
147
- /** Runs tool calls in parallel and returns the tool messages in call order. */
148
- async runTools(params, toolCalls) {
149
- return Promise.all(toolCalls.map(async (toolCall) => {
150
- let result;
218
+ // The SDK ends the stream quietly when it's aborted, so check here, or a
219
+ // cancelled reply would look like a finished empty one.
220
+ params.signal?.throwIfAborted();
221
+ const parts = [];
222
+ if (text)
223
+ parts.push({ type: 'text', text });
224
+ if (refusal)
225
+ parts.push({ type: 'text', text: refusal });
226
+ const ordered = [...calls.entries()].sort(([a], [b]) => a - b).map(([, call]) => call);
227
+ const events = [];
228
+ for (const call of ordered) {
229
+ const id = call.synthetic ? createToolCallId() : call.id;
230
+ let input = {};
231
+ let inputError;
151
232
  try {
152
- result = await executeToolCall(params, {
153
- id: toolCall.id,
154
- name: toolCall.function.name,
155
- input: parseToolInput(toolCall.function.arguments),
156
- });
233
+ input = parseToolInput(call.arguments);
157
234
  }
158
235
  catch (error) {
159
- result = toToolFailure(error);
236
+ inputError = error instanceof Error ? error.message : 'Tool arguments must be valid JSON.';
160
237
  }
161
- return {
162
- role: 'tool',
163
- tool_call_id: toolCall.id,
164
- content: JSON.stringify(serializeToolResult(result)),
165
- };
166
- }));
238
+ parts.push({
239
+ type: 'tool-call',
240
+ toolCallId: id,
241
+ toolName: call.name,
242
+ // Keep what the model sent when it isn't JSON, so it can see its mistake.
243
+ input: inputError ? call.arguments : input,
244
+ executor: 'server',
245
+ state: inputError ? 'error' : 'pending',
246
+ });
247
+ events.push({ type: 'tool-call', call: { id, name: call.name, input }, ...(inputError ? { inputError } : {}) });
248
+ }
249
+ yield* events;
250
+ yield {
251
+ type: 'finish',
252
+ reason: finishReason(reason, ordered.length > 0, refusal !== ''),
253
+ usage: toUsage(usage),
254
+ parts,
255
+ };
256
+ }
257
+ /**
258
+ * A turn with tools run through `params.toolExecutor`, as text.
259
+ * @deprecated Use `runTurn()`, which also returns the reply's parts, status and usage.
260
+ */
261
+ chat(params) {
262
+ return chatViaTurn(this, params);
263
+ }
264
+ /** @deprecated Use `runTurn()`. */
265
+ chatSync(params) {
266
+ return chatSyncViaTurn(this, params);
167
267
  }
168
268
  }
169
269
  //# sourceMappingURL=openai.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai.js","sourceRoot":"","sources":["../../src/providers/openai.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAG5B,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC1F,OAAO,EACL,eAAe,EACf,eAAe,EACf,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,qBAAqB,CAAC;AAE7B,MAAM,aAAa,GA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BACd,QAAQ,EAAE,IAAI,CAAC,IAAI;gBACnB,0EAA0E;gBAC1E,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK;gBAC1C,QAAQ,EAAE,QAAQ;gBAClB,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;aACxC,CAAC,CAAC;YACH,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;QAClH,CAAC;QAED,KAAK,CAAC,CAAC,MAAM,CAAC;QACd,MAAM;YACJ,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,OAAO,KAAK,EAAE,CAAC;YAChE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC;YACrB,KAAK;SACN,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,IAAI,CAAC,MAA0B;QAC7B,OAAO,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnC,CAAC;IAED,mCAAmC;IACnC,QAAQ,CAAC,MAA0B;QACjC,OAAO,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACvC,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ import type { ProviderConfig } from '../types.js';
2
+ import type { AIProvider } from './types.js';
3
+ export type ProviderFactory = (config: ProviderConfig) => AIProvider | Promise<AIProvider>;
4
+ /** Register a custom provider. Re-registering replaces its factory for hot reload. */
5
+ export declare function registerProvider(type: string, factory: ProviderFactory): void;
6
+ export declare function getProviderFactory(type: string): ProviderFactory | undefined;
7
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/providers/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,MAAM,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,cAAc,KAAK,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAK3F,sFAAsF;AACtF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,IAAI,CAG7E;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAE5E"}
@@ -0,0 +1,12 @@
1
+ const builtins = new Set(['claude', 'openai', 'gemini', 'openai-compatible']);
2
+ const factories = new Map();
3
+ /** Register a custom provider. Re-registering replaces its factory for hot reload. */
4
+ export function registerProvider(type, factory) {
5
+ if (builtins.has(type))
6
+ throw new Error(`Cannot register reserved provider type: ${type}`);
7
+ factories.set(type, factory);
8
+ }
9
+ export function getProviderFactory(type) {
10
+ return factories.get(type);
11
+ }
12
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/providers/registry.ts"],"names":[],"mappings":"AAKA,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,mBAAmB,CAAC,CAAC,CAAC;AAC9E,MAAM,SAAS,GAAG,IAAI,GAAG,EAA2B,CAAC;AAErD,sFAAsF;AACtF,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAE,OAAwB;IACrE,IAAI,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,2CAA2C,IAAI,EAAE,CAAC,CAAC;IAC3F,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC/B,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC7C,OAAO,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC"}
@@ -0,0 +1,16 @@
1
+ import type { JSONSchema, ToolDefinition, ToolParameter } from '../types.js';
2
+ /** The 0.4 flat parameter form as a JSON Schema object. */
3
+ export declare function legacyParametersToSchema(parameters: Record<string, ToolParameter>, required?: string[]): JSONSchema;
4
+ /** The JSON Schema sent to providers for this tool's input. */
5
+ export declare function toolInputSchema(tool: ToolDefinition): JSONSchema;
6
+ export declare class ToolDefinitionError extends Error {
7
+ readonly problems: string[];
8
+ constructor(problems: string[]);
9
+ }
10
+ /**
11
+ * Checks tool definitions before any request, so a mistake fails at startup
12
+ * with a clear message instead of as a provider error on the first message.
13
+ * Throws a `ToolDefinitionError` listing every problem.
14
+ */
15
+ export declare function validateTools(tools: readonly ToolDefinition[]): void;
16
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/providers/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAQ7E,2DAA2D;AAC3D,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,EACzC,QAAQ,GAAE,MAAM,EAAO,GACtB,UAAU,CAUZ;AAED,+DAA+D;AAC/D,wBAAgB,eAAe,CAAC,IAAI,EAAE,cAAc,GAAG,UAAU,CAGhE;AAED,qBAAa,mBAAoB,SAAQ,KAAK;IAChC,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE;gBAAlB,QAAQ,EAAE,MAAM,EAAE;CAIxC;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,SAAS,cAAc,EAAE,GAAG,IAAI,CA6CpE"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Names every provider accepts: Claude and OpenAI allow letters, digits, `_`
3
+ * and `-` up to 64 characters, and Gemini also wants a letter or `_` first.
4
+ */
5
+ const TOOL_NAME = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;
6
+ /** The 0.4 flat parameter form as a JSON Schema object. */
7
+ export function legacyParametersToSchema(parameters, required = []) {
8
+ const properties = {};
9
+ for (const [key, parameter] of Object.entries(parameters)) {
10
+ properties[key] = {
11
+ type: parameter.type,
12
+ description: parameter.description,
13
+ ...(parameter.enum ? { enum: parameter.enum } : {}),
14
+ };
15
+ }
16
+ return { type: 'object', properties, required };
17
+ }
18
+ /** The JSON Schema sent to providers for this tool's input. */
19
+ export function toolInputSchema(tool) {
20
+ if (tool.inputSchema)
21
+ return tool.inputSchema;
22
+ return legacyParametersToSchema(tool.parameters ?? {}, tool.required ?? []);
23
+ }
24
+ export class ToolDefinitionError extends Error {
25
+ problems;
26
+ constructor(problems) {
27
+ super(`Invalid tool definitions:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
28
+ this.problems = problems;
29
+ this.name = 'ToolDefinitionError';
30
+ }
31
+ }
32
+ /**
33
+ * Checks tool definitions before any request, so a mistake fails at startup
34
+ * with a clear message instead of as a provider error on the first message.
35
+ * Throws a `ToolDefinitionError` listing every problem.
36
+ */
37
+ export function validateTools(tools) {
38
+ const problems = [];
39
+ const seen = new Set();
40
+ tools.forEach((tool, index) => {
41
+ const label = typeof tool?.name === 'string' && tool.name ? `"${tool.name}"` : `#${index}`;
42
+ if (typeof tool?.name !== 'string' || !TOOL_NAME.test(tool.name)) {
43
+ problems.push(`tool ${label}: the name must start with a letter or _, and use only letters, digits, _ and - (64 at most)`);
44
+ }
45
+ else if (seen.has(tool.name)) {
46
+ problems.push(`tool ${label}: another tool has the same name`);
47
+ }
48
+ else {
49
+ seen.add(tool.name);
50
+ }
51
+ if (typeof tool?.description !== 'string') {
52
+ problems.push(`tool ${label}: description must be a string`);
53
+ }
54
+ if (tool?.inputSchema && tool.parameters) {
55
+ problems.push(`tool ${label}: set inputSchema or parameters, not both`);
56
+ }
57
+ if (tool?.inputSchema) {
58
+ const schema = tool.inputSchema;
59
+ if (typeof schema !== 'object' || schema === null || Array.isArray(schema) || schema.type !== 'object') {
60
+ problems.push(`tool ${label}: inputSchema must be a JSON Schema with type: 'object' at the root`);
61
+ }
62
+ try {
63
+ JSON.stringify(schema);
64
+ }
65
+ catch {
66
+ problems.push(`tool ${label}: inputSchema must be plain JSON (no cycles or functions)`);
67
+ }
68
+ }
69
+ else if (tool?.parameters) {
70
+ for (const key of tool.required ?? []) {
71
+ if (!(key in tool.parameters)) {
72
+ problems.push(`tool ${label}: required lists "${key}", which isn't in parameters`);
73
+ }
74
+ }
75
+ }
76
+ });
77
+ if (problems.length > 0)
78
+ throw new ToolDefinitionError(problems);
79
+ }
80
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/providers/schema.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,SAAS,GAAG,gCAAgC,CAAC;AAEnD,2DAA2D;AAC3D,MAAM,UAAU,wBAAwB,CACtC,UAAyC,EACzC,WAAqB,EAAE;IAEvB,MAAM,UAAU,GAA+B,EAAE,CAAC;IAClD,KAAK,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC;QAC1D,UAAU,CAAC,GAAG,CAAC,GAAG;YAChB,IAAI,EAAE,SAAS,CAAC,IAAI;YACpB,WAAW,EAAE,SAAS,CAAC,WAAW;YAClC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACpD,CAAC;IACJ,CAAC;IACD,OA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KAAK,qBAAqB,GAAG,8BAA8B,CAAC,CAAC;gBACrF,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,IAAI,mBAAmB,CAAC,QAAQ,CAAC,CAAC;AACnE,CAAC"}
@@ -1,8 +1,21 @@
1
+ import type { Logger } from '../logger.js';
1
2
  import type { ProviderChatParams, ProviderToolCall, ToolResult } from '../types.js';
2
3
  export declare const MAX_TOOL_ROUNDS = 5;
3
4
  export declare const DEFAULT_TOOL_TIMEOUT_MS = 30000;
4
5
  export declare function parseToolInput(rawInput: string): Record<string, unknown>;
5
6
  export declare function serializeToolResult(result: ToolResult): Record<string, unknown>;
6
7
  export declare function toToolFailure(error: unknown): ToolResult;
8
+ /**
9
+ * Runs a tool with a timeout. The tool gets a signal that aborts when the
10
+ * timeout passes or when `signal` aborts (the visitor left), and the result
11
+ * comes back as a failure right away in both cases, so a tool that ignores
12
+ * its signal can't hold up the reply.
13
+ */
14
+ export declare function runToolWithTimeout(run: (signal: AbortSignal) => Promise<ToolResult>, options?: {
15
+ timeoutMs?: number;
16
+ signal?: AbortSignal;
17
+ name?: string;
18
+ logger?: Logger;
19
+ }): Promise<ToolResult>;
7
20
  export declare function executeToolCall(params: ProviderChatParams, call: ProviderToolCall): Promise<ToolResult>;
8
21
  //# sourceMappingURL=tool-execution.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-execution.d.ts","sourceRoot":"","sources":["../../src/providers/tool-execution.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEpF,eAAO,MAAM,eAAe,IAAI,CAAC;AACjC,eAAO,MAAM,uBAAuB,QAAS,CAAC;AAE9C,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAexE;AA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