codexmate 0.0.25 → 0.0.27

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 (35) hide show
  1. package/README.md +11 -3
  2. package/README.zh.md +10 -2
  3. package/cli/builtin-proxy.js +315 -95
  4. package/cli/openai-bridge.js +99 -5
  5. package/cli/session-convert-args.js +65 -0
  6. package/cli/session-convert-io.js +82 -0
  7. package/cli/session-convert.js +43 -0
  8. package/cli.js +547 -32
  9. package/package.json +74 -74
  10. package/web-ui/app.js +24 -2
  11. package/web-ui/logic.session-convert.mjs +70 -0
  12. package/web-ui/logic.sessions.mjs +151 -0
  13. package/web-ui/modules/app.computed.dashboard.mjs +44 -1
  14. package/web-ui/modules/app.computed.session.mjs +336 -12
  15. package/web-ui/modules/app.methods.claude-config.mjs +11 -1
  16. package/web-ui/modules/app.methods.codex-config.mjs +76 -0
  17. package/web-ui/modules/app.methods.navigation.mjs +51 -3
  18. package/web-ui/modules/app.methods.session-actions.mjs +55 -3
  19. package/web-ui/modules/app.methods.session-browser.mjs +270 -3
  20. package/web-ui/modules/app.methods.session-timeline.mjs +34 -3
  21. package/web-ui/modules/app.methods.session-trash.mjs +16 -1
  22. package/web-ui/modules/app.methods.startup-claude.mjs +234 -125
  23. package/web-ui/modules/i18n.dict.mjs +76 -0
  24. package/web-ui/partials/index/panel-config-claude.html +12 -4
  25. package/web-ui/partials/index/panel-sessions.html +33 -10
  26. package/web-ui/partials/index/panel-settings.html +16 -0
  27. package/web-ui/partials/index/panel-usage.html +95 -85
  28. package/web-ui/session-helpers.mjs +3 -0
  29. package/web-ui/styles/base-theme.css +29 -25
  30. package/web-ui/styles/layout-shell.css +1 -1
  31. package/web-ui/styles/navigation-panels.css +9 -9
  32. package/web-ui/styles/sessions-list.css +17 -0
  33. package/web-ui/styles/sessions-toolbar-trash.css +62 -0
  34. package/web-ui/styles/sessions-usage.css +211 -83
  35. package/web-ui/styles/settings-panel.css +19 -0
@@ -369,6 +369,76 @@ function normalizeResponsesInputToChatMessages(input) {
369
369
  return [];
370
370
  }
371
371
 
372
+
373
+ function normalizeResponsesToolsToChatTools(tools) {
374
+ if (!Array.isArray(tools)) return tools;
375
+ return tools
376
+ .map((tool) => {
377
+ if (!tool || typeof tool !== 'object') return null;
378
+ if (tool.type !== 'function') return null;
379
+ const sourceFn = tool.function && typeof tool.function === 'object' && !Array.isArray(tool.function)
380
+ ? tool.function
381
+ : {};
382
+ const name = typeof sourceFn.name === 'string' && sourceFn.name.trim()
383
+ ? sourceFn.name.trim()
384
+ : (typeof tool.name === 'string' ? tool.name.trim() : '');
385
+ if (!name) return null;
386
+ const parameters = sourceFn.parameters && typeof sourceFn.parameters === 'object' && !Array.isArray(sourceFn.parameters)
387
+ ? sourceFn.parameters
388
+ : (tool.parameters && typeof tool.parameters === 'object' && !Array.isArray(tool.parameters) ? tool.parameters : {});
389
+ const fn = { name, parameters };
390
+ const description = typeof sourceFn.description === 'string'
391
+ ? sourceFn.description
392
+ : (typeof tool.description === 'string' ? tool.description : undefined);
393
+ const strict = typeof sourceFn.strict === 'boolean'
394
+ ? sourceFn.strict
395
+ : (typeof tool.strict === 'boolean' ? tool.strict : undefined);
396
+ if (description !== undefined) fn.description = description;
397
+ if (strict !== undefined) fn.strict = strict;
398
+ return { type: 'function', function: fn };
399
+ })
400
+ .filter(Boolean);
401
+ }
402
+
403
+ function normalizeResponsesToolChoiceToChatToolChoice(toolChoice) {
404
+ if (!toolChoice || typeof toolChoice !== 'object' || Array.isArray(toolChoice)) return toolChoice;
405
+ if (toolChoice.type === 'function' && typeof toolChoice.name === 'string' && toolChoice.name.trim()) {
406
+ return { type: 'function', function: { name: toolChoice.name.trim() } };
407
+ }
408
+ return toolChoice;
409
+ }
410
+
411
+ function normalizeResponsesToolsForResponsesApi(tools) {
412
+ if (!Array.isArray(tools)) return tools;
413
+ return tools
414
+ .map((tool) => {
415
+ if (!tool || typeof tool !== 'object') return null;
416
+ if (tool.type !== 'function') return null;
417
+ const sourceFn = tool.function && typeof tool.function === 'object' && !Array.isArray(tool.function)
418
+ ? tool.function
419
+ : {};
420
+ const name = typeof sourceFn.name === 'string' && sourceFn.name.trim()
421
+ ? sourceFn.name.trim()
422
+ : (typeof tool.name === 'string' ? tool.name.trim() : '');
423
+ if (!name) return null;
424
+ const out = { type: 'function', name };
425
+ const description = typeof sourceFn.description === 'string'
426
+ ? sourceFn.description
427
+ : (typeof tool.description === 'string' ? tool.description : undefined);
428
+ const parameters = sourceFn.parameters && typeof sourceFn.parameters === 'object' && !Array.isArray(sourceFn.parameters)
429
+ ? sourceFn.parameters
430
+ : (tool.parameters && typeof tool.parameters === 'object' && !Array.isArray(tool.parameters) ? tool.parameters : undefined);
431
+ const strict = typeof sourceFn.strict === 'boolean'
432
+ ? sourceFn.strict
433
+ : (typeof tool.strict === 'boolean' ? tool.strict : undefined);
434
+ if (description !== undefined) out.description = description;
435
+ if (parameters !== undefined) out.parameters = parameters;
436
+ if (strict !== undefined) out.strict = strict;
437
+ return out;
438
+ })
439
+ .filter(Boolean);
440
+ }
441
+
372
442
  function convertResponsesRequestToChatCompletions(payload) {
373
443
  const body = payload && typeof payload === 'object' ? payload : {};
374
444
  const model = typeof body.model === 'string' ? body.model.trim() : '';
@@ -401,12 +471,11 @@ function convertResponsesRequestToChatCompletions(payload) {
401
471
  if (Array.isArray(body.stop) && body.stop.length) {
402
472
  chat.stop = body.stop.filter((item) => typeof item === 'string' && item.trim());
403
473
  }
404
- // Best-effort: pass through tool definitions (most OpenAI-compatible providers accept these fields).
405
474
  if (Array.isArray(body.tools) && body.tools.length) {
406
- chat.tools = body.tools;
475
+ chat.tools = normalizeResponsesToolsToChatTools(body.tools);
407
476
  }
408
477
  if (body.tool_choice !== undefined) {
409
- chat.tool_choice = body.tool_choice;
478
+ chat.tool_choice = normalizeResponsesToolChoiceToChatToolChoice(body.tool_choice);
410
479
  }
411
480
  if (body.response_format !== undefined) {
412
481
  chat.response_format = body.response_format;
@@ -489,6 +558,9 @@ function buildResponsesPayloadFromChatResult(model, text, toolCalls, upstreamPay
489
558
 
490
559
  function ensureResponseMetadata(response) {
491
560
  const payload = response && typeof response === 'object' ? response : {};
561
+ if (typeof payload.object !== 'string' || !payload.object.trim()) {
562
+ payload.object = 'response';
563
+ }
492
564
  if (typeof payload.created_at !== 'number') {
493
565
  payload.created_at = Math.floor(Date.now() / 1000);
494
566
  }
@@ -599,7 +671,11 @@ function extractResponsesOutputText(payload) {
599
671
 
600
672
  function toUpstreamNonStreamingResponsesPayload(payload) {
601
673
  const body = payload && typeof payload === 'object' ? payload : {};
602
- return { ...body, stream: false };
674
+ const normalized = { ...body, stream: false };
675
+ if (Array.isArray(body.tools)) {
676
+ normalized.tools = normalizeResponsesToolsForResponsesApi(body.tools);
677
+ }
678
+ return normalized;
603
679
  }
604
680
 
605
681
  function shouldFallbackFromUpstreamResponses(status, bodyText) {
@@ -616,6 +692,7 @@ function shouldFallbackFromUpstreamResponses(status, bodyText) {
616
692
  if (/unknown (endpoint|route)/i.test(text)) return true;
617
693
  if (/unsupported.*\/?v1\/responses/i.test(text)) return true;
618
694
  if (/does not support.*responses/i.test(text)) return true;
695
+ if (/name['"`]?\s+is a required property/i.test(text) && /tools/i.test(text) && /function/i.test(text)) return true;
619
696
 
620
697
  // Best-effort parse for structured error codes.
621
698
  try {
@@ -627,6 +704,7 @@ function shouldFallbackFromUpstreamResponses(status, bodyText) {
627
704
  if (/unknown (endpoint|route)/i.test(msg)) return true;
628
705
  if (/unsupported.*\/?v1\/responses/i.test(msg)) return true;
629
706
  if (/does not support.*responses/i.test(msg)) return true;
707
+ if (/name['"`]?\s+is a required property/i.test(msg) && /tools/i.test(msg) && /function/i.test(msg)) return true;
630
708
  } catch (_) {}
631
709
 
632
710
  return false;
@@ -804,7 +882,23 @@ function createOpenaiBridgeHttpHandler(options = {}) {
804
882
  ? upstream.headers
805
883
  : {};
806
884
 
807
- if (!normalizedSuffix || normalizedSuffix === 'models') {
885
+ if (!normalizedSuffix) {
886
+ if ((req.method || 'GET').toUpperCase() !== 'GET') {
887
+ res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
888
+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));
889
+ return;
890
+ }
891
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
892
+ res.end(JSON.stringify({
893
+ object: 'codexmate.openai_bridge',
894
+ provider: match.provider,
895
+ status: 'ok',
896
+ endpoints: ['/v1/responses', '/v1/models']
897
+ }));
898
+ return;
899
+ }
900
+
901
+ if (normalizedSuffix === 'models') {
808
902
  if ((req.method || 'GET').toUpperCase() !== 'GET') {
809
903
  res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
810
904
  res.end(JSON.stringify({ error: 'Method Not Allowed' }));
@@ -0,0 +1,65 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const { parseMaxMessagesValue } = require('../lib/cli-session-utils');
5
+
6
+ function ensureDir(dirPath) {
7
+ if (!dirPath) return;
8
+ if (fs.existsSync(dirPath)) return;
9
+ fs.mkdirSync(dirPath, { recursive: true });
10
+ }
11
+
12
+ function resolveOutputPath(outputPath, defaultFileName) {
13
+ const fallback = path.resolve(process.cwd(), defaultFileName);
14
+ if (typeof outputPath !== 'string' || !outputPath.trim()) return fallback;
15
+ const trimmed = outputPath.trim();
16
+ const resolved = path.resolve(trimmed);
17
+ if (/[\\\/]$/.test(trimmed)) {
18
+ ensureDir(resolved);
19
+ return path.join(resolved, defaultFileName);
20
+ }
21
+ if (fs.existsSync(resolved)) {
22
+ try { if (fs.statSync(resolved).isDirectory()) return path.join(resolved, defaultFileName); } catch (_) {}
23
+ }
24
+ return resolved;
25
+ }
26
+
27
+ function parseArgs(args = []) {
28
+ const options = { from: '', to: '', sessionId: '', filePath: '', output: '', maxMessages: undefined };
29
+ const errors = [];
30
+ for (let i = 0; i < args.length; i += 1) {
31
+ const arg = String(args[i] || '');
32
+ const next = args[i + 1] || '';
33
+ if (!arg) continue;
34
+ if (arg === '--from') { options.from = next; i += 1; continue; }
35
+ if (arg.startsWith('--from=')) { options.from = arg.slice(7); continue; }
36
+ if (arg === '--to') { options.to = next; i += 1; continue; }
37
+ if (arg.startsWith('--to=')) { options.to = arg.slice(5); continue; }
38
+ if (arg === '--session-id') { options.sessionId = next; i += 1; continue; }
39
+ if (arg.startsWith('--session-id=')) { options.sessionId = arg.slice(13); continue; }
40
+ if (arg === '--file') { options.filePath = next; i += 1; continue; }
41
+ if (arg.startsWith('--file=')) { options.filePath = arg.slice(7); continue; }
42
+ if (arg === '--output') { options.output = next; i += 1; continue; }
43
+ if (arg.startsWith('--output=')) { options.output = arg.slice(9); continue; }
44
+ if (arg === '--max-messages') { options.maxMessages = next; i += 1; continue; }
45
+ if (arg.startsWith('--max-messages=')) { options.maxMessages = arg.slice(15); continue; }
46
+ errors.push(`未知参数: ${arg}`);
47
+ }
48
+ options.from = String(options.from || '').trim().toLowerCase();
49
+ options.to = String(options.to || '').trim().toLowerCase();
50
+ if (options.from !== 'codex' && options.from !== 'claude') errors.push('参数 --from 仅支持 codex 或 claude');
51
+ if (options.to !== 'codex' && options.to !== 'claude') errors.push('参数 --to 仅支持 codex 或 claude');
52
+ if (options.from && options.to && options.from === options.to) errors.push('--from 与 --to 不能相同');
53
+ if (!options.from) errors.push('缺少 --from');
54
+ if (!options.to) errors.push('缺少 --to');
55
+ if (!options.sessionId && !options.filePath) errors.push('必须指定 --session-id 或 --file');
56
+ if (options.maxMessages !== undefined) {
57
+ const parsed = parseMaxMessagesValue(options.maxMessages);
58
+ if (parsed === null) errors.push('参数 --max-messages 无效');
59
+ else options.maxMessages = parsed === Infinity ? Infinity : Math.max(1, Math.floor(parsed));
60
+ }
61
+ return { options, error: errors.length ? errors.join(';') : '' };
62
+ }
63
+
64
+ module.exports = { ensureDir, resolveOutputPath, parseArgs };
65
+
@@ -0,0 +1,82 @@
1
+ const fs = require('fs');
2
+ const readline = require('readline');
3
+
4
+ const {
5
+ toIsoTime,
6
+ extractMessageText,
7
+ normalizeRole,
8
+ resolveMaxMessagesValue
9
+ } = require('../lib/cli-session-utils');
10
+
11
+ const { removeLeadingSystemMessage } = require('../lib/cli-sessions');
12
+
13
+ async function readSessionMessages(filePath, source, maxMessages) {
14
+ const limit = resolveMaxMessagesValue(maxMessages, 200);
15
+ const state = { sessionId: '', cwd: '', updatedAt: '', messages: [], truncated: false };
16
+ const stream = fs.createReadStream(filePath, { encoding: 'utf-8' });
17
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
18
+ for await (const line of rl) {
19
+ const trimmed = String(line || '').trim();
20
+ if (!trimmed) continue;
21
+ let record;
22
+ try { record = JSON.parse(trimmed); } catch (_) { continue; }
23
+ const timestamp = toIsoTime(record.timestamp, '');
24
+ if (timestamp) state.updatedAt = timestamp;
25
+ if (source === 'codex' && record.type === 'session_meta' && record.payload) {
26
+ if (!state.sessionId && record.payload.id) state.sessionId = String(record.payload.id || '');
27
+ if (!state.cwd && record.payload.cwd) state.cwd = String(record.payload.cwd || '');
28
+ continue;
29
+ }
30
+ if (source === 'claude') {
31
+ if (!state.sessionId && record.sessionId) state.sessionId = String(record.sessionId || '');
32
+ if (!state.cwd && record.cwd) state.cwd = String(record.cwd || '');
33
+ }
34
+ let role = '';
35
+ let text = '';
36
+ if (source === 'codex' && record.type === 'response_item' && record.payload && record.payload.type === 'message') {
37
+ role = normalizeRole(record.payload.role);
38
+ text = extractMessageText(record.payload.content);
39
+ } else if (source === 'claude') {
40
+ role = normalizeRole(record.type);
41
+ text = extractMessageText(record.message ? record.message.content : '');
42
+ }
43
+ if (!role || !text) continue;
44
+ state.messages.push({ role, text, timestamp });
45
+ if (limit !== Infinity && state.messages.length > limit) {
46
+ state.messages.shift();
47
+ state.truncated = true;
48
+ }
49
+ }
50
+ state.messages = removeLeadingSystemMessage(state.messages);
51
+ return state;
52
+ }
53
+
54
+ function buildTargetRecords(target, payload) {
55
+ const now = Date.now();
56
+ const sessionId = String(payload.sessionId || '').trim();
57
+ const cwd = String(payload.cwd || '').trim();
58
+ const messages = Array.isArray(payload.messages) ? payload.messages : [];
59
+ if (target === 'codex') {
60
+ const records = [{ type: 'session_meta', timestamp: new Date(now).toISOString(), payload: { id: sessionId, cwd } }];
61
+ for (let i = 0; i < messages.length; i += 1) {
62
+ const m = messages[i] || {};
63
+ const role = normalizeRole(m.role);
64
+ const text = typeof m.text === 'string' ? m.text : '';
65
+ if (!role || !text) continue;
66
+ records.push({ type: 'response_item', timestamp: m.timestamp || new Date(now + i).toISOString(), payload: { type: 'message', role, content: text } });
67
+ }
68
+ return records;
69
+ }
70
+ const records = [];
71
+ for (let i = 0; i < messages.length; i += 1) {
72
+ const m = messages[i] || {};
73
+ const role = normalizeRole(m.role);
74
+ const text = typeof m.text === 'string' ? m.text : '';
75
+ if (!role || !text) continue;
76
+ records.push({ type: role, timestamp: m.timestamp || new Date(now + i).toISOString(), sessionId, cwd, message: { content: text } });
77
+ }
78
+ return records;
79
+ }
80
+
81
+ module.exports = { readSessionMessages, buildTargetRecords };
82
+
@@ -0,0 +1,43 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const { parseArgs, ensureDir, resolveOutputPath } = require('./session-convert-args');
5
+ const { readSessionMessages, buildTargetRecords } = require('./session-convert-io');
6
+
7
+ function printUsage() {
8
+ console.log('\n用法:');
9
+ console.log(' codexmate convert-session --from <codex|claude> --to <codex|claude> (--session-id <ID>|--file <PATH>) [--output <PATH>] [--max-messages <N|all|Infinity>]');
10
+ }
11
+
12
+ async function cmdConvertSession(args = [], deps = {}) {
13
+ const parsed = parseArgs(args);
14
+ if (parsed.error) {
15
+ console.error('错误:', parsed.error);
16
+ printUsage();
17
+ process.exit(1);
18
+ }
19
+ if (!deps || typeof deps.resolveSessionFilePath !== 'function') {
20
+ console.error('错误: convert-session missing resolver');
21
+ process.exit(1);
22
+ }
23
+ const opt = parsed.options;
24
+ const filePath = deps.resolveSessionFilePath(opt.from, opt.filePath, opt.sessionId);
25
+ if (!filePath) {
26
+ console.error('转换失败: Session file not found');
27
+ process.exit(1);
28
+ }
29
+ const extracted = await readSessionMessages(filePath, opt.from, opt.maxMessages);
30
+ const sessionId = extracted.sessionId || opt.sessionId || path.basename(filePath, '.jsonl');
31
+ const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9_-]/g, '_');
32
+ const records = buildTargetRecords(opt.to, { sessionId, cwd: extracted.cwd || '', messages: extracted.messages });
33
+ const jsonl = `${records.map(r => JSON.stringify(r)).join('\n')}\n`;
34
+ const outputPath = resolveOutputPath(opt.output, `${opt.to}-session-${safeSessionId}.jsonl`);
35
+ ensureDir(path.dirname(outputPath));
36
+ fs.writeFileSync(outputPath, jsonl, 'utf-8');
37
+ console.log('\n✓ 会话已转换:', outputPath);
38
+ if (extracted.truncated) console.log('! 已截断: 可使用 --max-messages=all');
39
+ console.log();
40
+ }
41
+
42
+ module.exports = { cmdConvertSession };
43
+