coding-tool-x 3.5.13 → 3.5.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,386 @@
1
+ const http = require('http');
2
+ const https = require('https');
3
+
4
+ const CLAUDE_COUNT_TOKENS_BETA_HEADER = 'claude-code-20250219,token-counting-2024-11-01';
5
+ const CLAUDE_COUNT_TOKENS_USER_AGENT = 'claude-cli/2.1.59 (external, cli)';
6
+ const DEFAULT_TIMEOUT_MS = 5000;
7
+
8
+ function cloneJsonCompatible(value) {
9
+ try {
10
+ return JSON.parse(JSON.stringify(value));
11
+ } catch {
12
+ return value;
13
+ }
14
+ }
15
+
16
+ function toArrayContent(content) {
17
+ if (Array.isArray(content)) {
18
+ return content.map(item => cloneJsonCompatible(item));
19
+ }
20
+ if (typeof content === 'string') {
21
+ return content.trim() ? [{ type: 'text', text: content }] : [];
22
+ }
23
+ if (content && typeof content === 'object') {
24
+ return [cloneJsonCompatible(content)];
25
+ }
26
+ return [];
27
+ }
28
+
29
+ function createClaudeStreamRecoveryState() {
30
+ return {
31
+ model: '',
32
+ blockTypeByIndex: new Map(),
33
+ textByIndex: new Map(),
34
+ toolUseByIndex: new Map()
35
+ };
36
+ }
37
+
38
+ function appendTextDelta(state, index, value) {
39
+ const previous = state.textByIndex.get(index) || '';
40
+ state.textByIndex.set(index, previous + value);
41
+ }
42
+
43
+ function appendToolInputDelta(state, index, value) {
44
+ const current = state.toolUseByIndex.get(index) || {
45
+ id: `toolu_recovered_${index}`,
46
+ name: '',
47
+ inputJson: ''
48
+ };
49
+ current.inputJson = `${current.inputJson || ''}${value}`;
50
+ state.toolUseByIndex.set(index, current);
51
+ }
52
+
53
+ function mergeClaudeStreamEvent(state, eventType, parsed) {
54
+ if (!state || !parsed || typeof parsed !== 'object') {
55
+ return;
56
+ }
57
+
58
+ if (eventType === 'message_start' && parsed.message && typeof parsed.message === 'object') {
59
+ const model = typeof parsed.message.model === 'string' ? parsed.message.model.trim() : '';
60
+ if (model) {
61
+ state.model = model;
62
+ }
63
+ } else if (!state.model && typeof parsed.model === 'string' && parsed.model.trim()) {
64
+ state.model = parsed.model.trim();
65
+ }
66
+
67
+ if (eventType === 'content_block_start') {
68
+ const index = Number(parsed.index);
69
+ const blockIndex = Number.isFinite(index) ? index : 0;
70
+ const block = (parsed.content_block && typeof parsed.content_block === 'object') ? parsed.content_block : {};
71
+ const blockType = typeof block.type === 'string' ? block.type : '';
72
+ if (!blockType) {
73
+ return;
74
+ }
75
+
76
+ state.blockTypeByIndex.set(blockIndex, blockType);
77
+
78
+ if (blockType === 'text' && typeof block.text === 'string') {
79
+ state.textByIndex.set(blockIndex, block.text);
80
+ return;
81
+ }
82
+
83
+ if (blockType === 'tool_use') {
84
+ state.toolUseByIndex.set(blockIndex, {
85
+ id: String(block.id || `toolu_recovered_${blockIndex}`),
86
+ name: typeof block.name === 'string' ? block.name : '',
87
+ inputJson: block.input && typeof block.input === 'object' && !Array.isArray(block.input)
88
+ ? JSON.stringify(block.input)
89
+ : ''
90
+ });
91
+ }
92
+ return;
93
+ }
94
+
95
+ if (eventType !== 'content_block_delta') {
96
+ return;
97
+ }
98
+
99
+ const index = Number(parsed.index);
100
+ const blockIndex = Number.isFinite(index) ? index : 0;
101
+ const delta = (parsed.delta && typeof parsed.delta === 'object') ? parsed.delta : {};
102
+
103
+ if (delta.type === 'text_delta' && typeof delta.text === 'string') {
104
+ appendTextDelta(state, blockIndex, delta.text);
105
+ return;
106
+ }
107
+
108
+ if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
109
+ appendToolInputDelta(state, blockIndex, delta.partial_json);
110
+ }
111
+ }
112
+
113
+ function parseToolInput(inputJson) {
114
+ if (typeof inputJson !== 'string' || !inputJson.trim()) {
115
+ return {};
116
+ }
117
+ try {
118
+ const parsed = JSON.parse(inputJson);
119
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
120
+ return parsed;
121
+ }
122
+ } catch {
123
+ }
124
+ return {};
125
+ }
126
+
127
+ function buildAssistantMessageFromStreamState(state) {
128
+ if (!state || !(state.blockTypeByIndex instanceof Map) || state.blockTypeByIndex.size === 0) {
129
+ return null;
130
+ }
131
+
132
+ const content = [];
133
+ const indexes = Array.from(state.blockTypeByIndex.keys())
134
+ .map(value => Number(value))
135
+ .filter(Number.isFinite)
136
+ .sort((a, b) => a - b);
137
+
138
+ indexes.forEach((index) => {
139
+ const blockType = state.blockTypeByIndex.get(index);
140
+ if (blockType === 'text') {
141
+ const text = state.textByIndex.get(index) || '';
142
+ if (text) {
143
+ content.push({
144
+ type: 'text',
145
+ text
146
+ });
147
+ }
148
+ return;
149
+ }
150
+
151
+ if (blockType === 'tool_use') {
152
+ const toolUse = state.toolUseByIndex.get(index);
153
+ if (!toolUse || !toolUse.name) {
154
+ return;
155
+ }
156
+ content.push({
157
+ type: 'tool_use',
158
+ id: toolUse.id,
159
+ name: toolUse.name,
160
+ input: parseToolInput(toolUse.inputJson)
161
+ });
162
+ }
163
+ });
164
+
165
+ if (content.length === 0) {
166
+ return null;
167
+ }
168
+
169
+ return {
170
+ role: 'assistant',
171
+ content
172
+ };
173
+ }
174
+
175
+ function buildClaudeCountTokensTargetUrl(baseUrl = '') {
176
+ let targetUrl;
177
+ try {
178
+ targetUrl = new URL(String(baseUrl || '').trim() || 'https://api.anthropic.com');
179
+ } catch {
180
+ targetUrl = new URL('https://api.anthropic.com');
181
+ }
182
+
183
+ let pathname = targetUrl.pathname.replace(/\/+$/, '');
184
+ if (!pathname || pathname === '/') {
185
+ pathname = '/v1/messages/count_tokens';
186
+ } else if (pathname.endsWith('/messages/count_tokens')) {
187
+ // noop
188
+ } else if (pathname.endsWith('/messages')) {
189
+ pathname = `${pathname}/count_tokens`;
190
+ } else if (pathname.endsWith('/v1')) {
191
+ pathname = `${pathname}/messages/count_tokens`;
192
+ } else {
193
+ pathname = `${pathname}/v1/messages/count_tokens`;
194
+ }
195
+
196
+ targetUrl.pathname = pathname;
197
+ targetUrl.searchParams.set('beta', 'true');
198
+ return targetUrl.toString();
199
+ }
200
+
201
+ function buildClaudeCountTokensHeaders(apiKey) {
202
+ return {
203
+ 'x-api-key': apiKey,
204
+ authorization: `Bearer ${apiKey}`,
205
+ 'anthropic-version': '2023-06-01',
206
+ 'anthropic-beta': CLAUDE_COUNT_TOKENS_BETA_HEADER,
207
+ 'content-type': 'application/json',
208
+ accept: 'application/json',
209
+ 'accept-encoding': 'gzip, deflate',
210
+ 'user-agent': CLAUDE_COUNT_TOKENS_USER_AGENT
211
+ };
212
+ }
213
+
214
+ function postJson(url, headers, payload, timeoutMs = DEFAULT_TIMEOUT_MS) {
215
+ return new Promise((resolve, reject) => {
216
+ const target = new URL(url);
217
+ const isHttps = target.protocol === 'https:';
218
+ const client = isHttps ? https : http;
219
+ const body = JSON.stringify(payload || {});
220
+ const request = client.request({
221
+ hostname: target.hostname,
222
+ port: target.port || (isHttps ? 443 : 80),
223
+ path: `${target.pathname}${target.search}`,
224
+ method: 'POST',
225
+ timeout: timeoutMs,
226
+ headers: {
227
+ ...headers,
228
+ 'Content-Type': 'application/json',
229
+ 'Content-Length': Buffer.byteLength(body)
230
+ }
231
+ }, (response) => {
232
+ let rawBody = '';
233
+ response.on('data', (chunk) => {
234
+ rawBody += chunk.toString('utf8');
235
+ });
236
+ response.on('end', () => {
237
+ resolve({
238
+ statusCode: Number(response.statusCode) || 500,
239
+ headers: response.headers || {},
240
+ rawBody
241
+ });
242
+ });
243
+ response.on('error', reject);
244
+ });
245
+
246
+ request.on('error', reject);
247
+ request.on('timeout', () => {
248
+ request.destroy(new Error('count_tokens request timeout'));
249
+ });
250
+ request.write(body);
251
+ request.end();
252
+ });
253
+ }
254
+
255
+ function readCountTokensValue(responseBody) {
256
+ if (!responseBody || typeof responseBody !== 'object') {
257
+ return null;
258
+ }
259
+
260
+ const direct = Number(responseBody.input_tokens ?? responseBody.inputTokens);
261
+ if (Number.isFinite(direct)) {
262
+ return direct;
263
+ }
264
+
265
+ const nested = Number(responseBody.usage?.input_tokens ?? responseBody.usage?.inputTokens);
266
+ if (Number.isFinite(nested)) {
267
+ return nested;
268
+ }
269
+
270
+ return null;
271
+ }
272
+
273
+ function buildClaudeCountTokensPayload(requestBody = {}) {
274
+ const payload = {
275
+ model: requestBody.model,
276
+ messages: Array.isArray(requestBody.messages)
277
+ ? requestBody.messages.map(message => cloneJsonCompatible(message))
278
+ : []
279
+ };
280
+
281
+ if (requestBody.system !== undefined) {
282
+ payload.system = cloneJsonCompatible(requestBody.system);
283
+ }
284
+ if (Array.isArray(requestBody.tools) && requestBody.tools.length > 0) {
285
+ payload.tools = cloneJsonCompatible(requestBody.tools);
286
+ }
287
+ if (requestBody.tool_choice && typeof requestBody.tool_choice === 'object') {
288
+ payload.tool_choice = cloneJsonCompatible(requestBody.tool_choice);
289
+ }
290
+ if (requestBody.metadata && typeof requestBody.metadata === 'object') {
291
+ payload.metadata = cloneJsonCompatible(requestBody.metadata);
292
+ }
293
+ if (requestBody.thinking && typeof requestBody.thinking === 'object') {
294
+ payload.thinking = cloneJsonCompatible(requestBody.thinking);
295
+ }
296
+
297
+ return payload;
298
+ }
299
+
300
+ async function countClaudeInputTokens({ baseUrl, apiKey, payload, timeoutMs = DEFAULT_TIMEOUT_MS }) {
301
+ const response = await postJson(
302
+ buildClaudeCountTokensTargetUrl(baseUrl),
303
+ buildClaudeCountTokensHeaders(apiKey),
304
+ payload,
305
+ timeoutMs
306
+ );
307
+
308
+ if (response.statusCode < 200 || response.statusCode >= 300) {
309
+ throw new Error(`count_tokens returned HTTP ${response.statusCode}`);
310
+ }
311
+
312
+ let parsedBody = null;
313
+ try {
314
+ parsedBody = response.rawBody ? JSON.parse(response.rawBody) : {};
315
+ } catch {
316
+ parsedBody = null;
317
+ }
318
+
319
+ const tokens = readCountTokensValue(parsedBody);
320
+ if (!Number.isFinite(tokens)) {
321
+ throw new Error('count_tokens response missing input_tokens');
322
+ }
323
+
324
+ return tokens;
325
+ }
326
+
327
+ function appendAssistantMessage(messages = [], assistantMessage) {
328
+ const normalizedMessages = Array.isArray(messages)
329
+ ? messages.map(message => cloneJsonCompatible(message))
330
+ : [];
331
+
332
+ normalizedMessages.push({
333
+ role: 'assistant',
334
+ content: toArrayContent(assistantMessage.content)
335
+ });
336
+ return normalizedMessages;
337
+ }
338
+
339
+ async function recoverClaudeUsageViaCountTokens({
340
+ baseUrl,
341
+ apiKey,
342
+ requestBody,
343
+ assistantMessage,
344
+ timeoutMs = DEFAULT_TIMEOUT_MS
345
+ }) {
346
+ if (!assistantMessage || !assistantMessage.content || !baseUrl || !apiKey) {
347
+ return null;
348
+ }
349
+
350
+ const promptPayload = buildClaudeCountTokensPayload(requestBody);
351
+ if (!promptPayload.model || !Array.isArray(promptPayload.messages)) {
352
+ return null;
353
+ }
354
+
355
+ const promptTokens = await countClaudeInputTokens({
356
+ baseUrl,
357
+ apiKey,
358
+ payload: promptPayload,
359
+ timeoutMs
360
+ });
361
+
362
+ const promptWithAssistantPayload = {
363
+ ...promptPayload,
364
+ messages: appendAssistantMessage(promptPayload.messages, assistantMessage)
365
+ };
366
+
367
+ const promptPlusAssistantTokens = await countClaudeInputTokens({
368
+ baseUrl,
369
+ apiKey,
370
+ payload: promptWithAssistantPayload,
371
+ timeoutMs
372
+ });
373
+
374
+ return {
375
+ inputTokens: promptTokens,
376
+ outputTokens: Math.max(promptPlusAssistantTokens - promptTokens, 0)
377
+ };
378
+ }
379
+
380
+ module.exports = {
381
+ createClaudeStreamRecoveryState,
382
+ mergeClaudeStreamEvent,
383
+ buildAssistantMessageFromStreamState,
384
+ buildClaudeCountTokensPayload,
385
+ recoverClaudeUsageViaCountTokens
386
+ };
@@ -6,7 +6,6 @@ const tomlStringify = require('@iarna/toml').stringify;
6
6
  const { PATHS } = require('../../config/paths');
7
7
  const { getCodexDir } = require('./codex-config');
8
8
  const { isProxyConfig, readConfig } = require('./codex-settings-manager');
9
- const { clearNativeOAuth } = require('./native-oauth-adapters');
10
9
  const { syncCodexUserEnvironment } = require('./codex-env-manager');
11
10
  const BaseChannelService = require('./base/base-channel-service');
12
11
 
@@ -35,13 +34,17 @@ function resolveCurrentManagedChannel(channels = []) {
35
34
  return allChannels.find(ch => ch.enabled !== false) || null;
36
35
  }
37
36
 
37
+ function channelRequiresOpenaiAuth(channel) {
38
+ return channel?.requiresOpenaiAuth === true;
39
+ }
40
+
38
41
  function buildManagedCodexEnvMap(channels = [], { includeProxyKey = false, activeChannel = null } = {}) {
39
42
  if (includeProxyKey) {
40
43
  return { [CODEX_MANAGED_ENV_KEY]: CODEX_PROXY_ENV_VALUE };
41
44
  }
42
45
 
43
46
  const targetChannel = activeChannel || resolveCurrentManagedChannel(channels);
44
- if (targetChannel?.apiKey) {
47
+ if (!channelRequiresOpenaiAuth(targetChannel) && targetChannel?.apiKey) {
45
48
  return { [CODEX_MANAGED_ENV_KEY]: targetChannel.apiKey };
46
49
  }
47
50
  return {};
@@ -108,7 +111,7 @@ function writeCodexConfigForMultiChannel(channels) {
108
111
  base_url: ch.baseUrl,
109
112
  wire_api: ch.wireApi || 'responses',
110
113
  env_key: CODEX_MANAGED_ENV_KEY,
111
- requires_openai_auth: ch.requiresOpenaiAuth !== false
114
+ requires_openai_auth: channelRequiresOpenaiAuth(ch)
112
115
  };
113
116
  if (ch.queryParams && Object.keys(ch.queryParams).length > 0) {
114
117
  config.model_providers[ch.providerKey].query_params = ch.queryParams;
@@ -147,7 +150,7 @@ class CodexChannelService extends BaseChannelService {
147
150
  ch.speedTestModel = ch.speedTestModel || null;
148
151
  ch.modelRedirects = Array.isArray(ch.modelRedirects) ? ch.modelRedirects : [];
149
152
  ch.gatewaySourceType = ch.gatewaySourceType || 'codex';
150
- ch.requiresOpenaiAuth = ch.requiresOpenaiAuth !== false;
153
+ ch.requiresOpenaiAuth = ch.requiresOpenaiAuth === true;
151
154
  ch.queryParams = ch.queryParams || {};
152
155
  return ch;
153
156
  }
@@ -193,12 +196,10 @@ class CodexChannelService extends BaseChannelService {
193
196
  return;
194
197
  }
195
198
  }
196
- clearNativeOAuth('codex');
197
199
  syncAllChannelEnvVars();
198
200
  }
199
201
 
200
202
  _applyToNativeSettings(channel) {
201
- clearNativeOAuth('codex');
202
203
  const codexDir = getCodexDir();
203
204
  const configPath = path.join(codexDir, 'config.toml');
204
205
 
@@ -224,7 +225,7 @@ class CodexChannelService extends BaseChannelService {
224
225
  base_url: channel.baseUrl,
225
226
  wire_api: channel.wireApi || 'responses',
226
227
  env_key: CODEX_MANAGED_ENV_KEY,
227
- requires_openai_auth: channel.requiresOpenaiAuth !== false
228
+ requires_openai_auth: channelRequiresOpenaiAuth(channel)
228
229
  };
229
230
 
230
231
  if (channel.queryParams && Object.keys(channel.queryParams).length > 0) {