codexmate 0.1.34 → 0.1.36

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 (68) hide show
  1. package/README.md +102 -86
  2. package/README.vi.md +105 -79
  3. package/README.zh.md +102 -84
  4. package/cli/analytics-export-args.js +7 -0
  5. package/cli/session-usage.js +4 -1
  6. package/cli.js +30 -6
  7. package/lib/data/model-prices.json +1868 -0
  8. package/lib/session-context-health.js +5 -1
  9. package/lib/session-evidence-collections.js +85 -0
  10. package/lib/session-features.js +15 -0
  11. package/lib/session-project-git.js +65 -0
  12. package/lib/session-projects.js +12 -1
  13. package/lib/session-stories.js +67 -0
  14. package/lib/session-usage-ledger.js +77 -0
  15. package/lib/session-usage-pricing.js +42 -0
  16. package/lib/session-usage-report.js +101 -0
  17. package/package.json +4 -1
  18. package/plugins/prompt-templates/computed.mjs +9 -0
  19. package/web-ui/app.js +12 -0
  20. package/web-ui/logic.codex.mjs +14 -0
  21. package/web-ui/logic.session-artifacts.mjs +39 -0
  22. package/web-ui/modules/app.methods.agents.mjs +3 -2
  23. package/web-ui/modules/app.methods.claude-config.mjs +26 -5
  24. package/web-ui/modules/app.methods.install.mjs +13 -17
  25. package/web-ui/modules/app.methods.navigation.mjs +1 -1
  26. package/web-ui/modules/app.methods.openclaw-editing.mjs +29 -0
  27. package/web-ui/modules/app.methods.openclaw-persist.mjs +3 -3
  28. package/web-ui/modules/app.methods.opencode-config.mjs +34 -0
  29. package/web-ui/modules/app.methods.pi-config.mjs +14 -9
  30. package/web-ui/modules/app.methods.providers.mjs +11 -0
  31. package/web-ui/modules/app.methods.session-browser.mjs +35 -0
  32. package/web-ui/modules/app.methods.session-trash.mjs +4 -5
  33. package/web-ui/modules/app.methods.startup-claude.mjs +1 -0
  34. package/web-ui/modules/app.methods.system-prompt.mjs +16 -7
  35. package/web-ui/modules/app.methods.web-ui-preferences.mjs +5 -0
  36. package/web-ui/modules/claude-provider-presets.mjs +23 -0
  37. package/web-ui/modules/i18n/locales/en.mjs +127 -1
  38. package/web-ui/modules/i18n/locales/ja.mjs +127 -1
  39. package/web-ui/modules/i18n/locales/vi.mjs +127 -1
  40. package/web-ui/modules/i18n/locales/zh-tw.mjs +127 -1
  41. package/web-ui/modules/i18n/locales/zh.mjs +127 -1
  42. package/web-ui/modules/pi-provider-templates.mjs +6 -1
  43. package/web-ui/modules/session-collections.mjs +65 -0
  44. package/web-ui/modules/session-evidence.mjs +81 -0
  45. package/web-ui/modules/session-features.mjs +15 -1
  46. package/web-ui/modules/session-git.mjs +39 -0
  47. package/web-ui/modules/session-stories.mjs +64 -0
  48. package/web-ui/modules/usage-pricing.mjs +30 -0
  49. package/web-ui/partials/index/layout-footer.html +1 -1
  50. package/web-ui/partials/index/modal-openclaw-config.html +3 -0
  51. package/web-ui/partials/index/modals-basic.html +1 -1
  52. package/web-ui/partials/index/modals-pi-provider.html +1 -1
  53. package/web-ui/partials/index/panel-config-claude.html +4 -21
  54. package/web-ui/partials/index/panel-config-codex.html +3 -1
  55. package/web-ui/partials/index/panel-config-opencode.html +4 -0
  56. package/web-ui/partials/index/panel-sessions.html +20 -20
  57. package/web-ui/partials/index/panel-settings.html +45 -0
  58. package/web-ui/partials/index/panel-usage.html +2 -0
  59. package/web-ui/partials/index/session-features.html +82 -2
  60. package/web-ui/partials/index/thread-handoff.html +73 -62
  61. package/web-ui/partials/index/usage-records.html +41 -0
  62. package/web-ui/res/web-ui-render.precompiled.js +896 -236
  63. package/web-ui/styles/session-features.css +63 -0
  64. package/web-ui/styles/sessions-list.css +74 -0
  65. package/web-ui/styles/sessions-preview.css +106 -68
  66. package/web-ui/styles/sessions-usage.css +8 -0
  67. package/web-ui/styles/settings-panel.css +4 -0
  68. package/web-ui/styles/theme-violet.css +9 -3
@@ -96,7 +96,11 @@ function createSessionContextHealthController(deps) {
96
96
  index++;
97
97
  }
98
98
  }
99
- return { readSessionContextHealth, readSessionContextNode, iterateSessionContextNodes };
99
+ async function* iterateSessionUsageRecords(params = {}) {
100
+ const target = resolve(params);
101
+ yield* records(target.source, target.filePath, target.sessionId);
102
+ }
103
+ return { readSessionContextHealth, readSessionContextNode, iterateSessionContextNodes, iterateSessionUsageRecords };
100
104
  }
101
105
 
102
106
  module.exports = { createSessionContextHealthController };
@@ -0,0 +1,85 @@
1
+ 'use strict';
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const { createLocalFeatureStore, digest } = require('./local-feature-store');
5
+ const { SOURCES } = require('./session-search-index');
6
+ const MAX_SELECTIONS = 100;
7
+ const MAX_NAME_LENGTH = 160;
8
+ const MAX_GOAL_LENGTH = 500;
9
+ const HASH_PATTERN = /^[a-f0-9]{64}$/;
10
+ const referenceKey = item => JSON.stringify([item.session.source, item.session.sessionId, item.session.filePath, item.nodeId]);
11
+
12
+ function normalizeReferences(items) {
13
+ if (!Array.isArray(items) || !items.length || items.length > MAX_SELECTIONS) throw new Error('collection-input-invalid');
14
+ const references = new Map();
15
+ for (const item of items) {
16
+ const session = item?.session;
17
+ if (!session || !SOURCES.includes(session.source) || typeof session.sessionId !== 'string'
18
+ || typeof session.filePath !== 'string' || (!session.sessionId && !session.filePath)
19
+ || typeof item.nodeId !== 'string' || !item.nodeId.startsWith('record-') || !HASH_PATTERN.test(item.textHash || '')
20
+ || typeof session.cwd !== 'string' || typeof session.title !== 'string') throw new Error('collection-input-invalid');
21
+ const reference = { session: { source: session.source, sessionId: session.sessionId, filePath: session.filePath,
22
+ cwd: session.cwd, title: session.title.slice(0, MAX_NAME_LENGTH) }, nodeId: item.nodeId, textHash: item.textHash };
23
+ references.set(referenceKey(reference), reference);
24
+ }
25
+ return [...references.values()];
26
+ }
27
+ function createSessionEvidenceCollections({ root, readNode }) {
28
+ const store = createLocalFeatureStore(path.join(root, 'collections.json'), { version: 1, items: [] });
29
+ function snapshot() {
30
+ const current = store.read();
31
+ if (!Array.isArray(current.value.items)) throw new Error('feature-store-invalid');
32
+ for (const item of current.value.items) {
33
+ if (!item || typeof item.id !== 'string' || typeof item.name !== 'string' || typeof item.goal !== 'string') throw new Error('feature-store-invalid');
34
+ try { normalizeReferences(item.references); } catch (_) { throw new Error('feature-store-invalid'); }
35
+ }
36
+ return current;
37
+ }
38
+ function list() {
39
+ const current = snapshot();
40
+ return { items: current.value.items, revision: current.revision };
41
+ }
42
+ async function inspect(references) {
43
+ const items = [];
44
+ for (const reference of references) {
45
+ const result = await readNode({ ...reference.session, nodeId: reference.nodeId });
46
+ const state = result.error ? 'unavailable' : digest(result.node.text) === reference.textHash ? 'ready' : 'changed';
47
+ items.push({ ...reference, state });
48
+ }
49
+ return { items, complete: items.every(item => item.state === 'ready'), checkedAt: new Date().toISOString() };
50
+ }
51
+ async function open(params) {
52
+ const current = snapshot();
53
+ const item = current.value.items.find(entry => entry.id === params.id);
54
+ if (!item) throw new Error('collection-not-found');
55
+ return { item, revision: current.revision, ...await inspect(item.references) };
56
+ }
57
+ async function save(params) {
58
+ const current = snapshot();
59
+ if (current.revision !== params.revision) throw new Error('feature-store-conflict');
60
+ if (typeof params.name !== 'string' || !params.name.trim() || params.name.length > MAX_NAME_LENGTH
61
+ || typeof params.goal !== 'string' || params.goal.length > MAX_GOAL_LENGTH) throw new Error('collection-input-invalid');
62
+ const references = normalizeReferences(params.references);
63
+ const existing = params.id && current.value.items.find(item => item.id === params.id);
64
+ if (params.id && !existing) throw new Error('collection-not-found');
65
+ const report = await inspect(references);
66
+ if (!report.complete) throw new Error('collection-source-unavailable');
67
+ const now = new Date().toISOString();
68
+ const item = { id: existing?.id || crypto.randomBytes(16).toString('hex'), name: params.name.trim(), goal: params.goal,
69
+ references, createdAt: existing?.createdAt || now, updatedAt: now };
70
+ if (existing) current.value.items[current.value.items.indexOf(existing)] = item;
71
+ else current.value.items.unshift(item);
72
+ store.write(current.value, current.revision);
73
+ return { ...list(), item };
74
+ }
75
+ function remove(params) {
76
+ const current = snapshot();
77
+ if (current.revision !== params.revision) throw new Error('feature-store-conflict');
78
+ if (!current.value.items.some(item => item.id === params.id)) throw new Error('collection-not-found');
79
+ current.value.items = current.value.items.filter(item => item.id !== params.id);
80
+ store.write(current.value, current.revision);
81
+ return list();
82
+ }
83
+ return { list, open, save, remove };
84
+ }
85
+ module.exports = { createSessionEvidenceCollections };
@@ -3,9 +3,12 @@ const { createSessionBookmarks } = require('./session-bookmarks');
3
3
  const { digest } = require('./local-feature-store');
4
4
  const { createSessionSearchIndex } = require('./session-search-index');
5
5
  const { generateHandoffDraft } = require('./session-handoff-draft');
6
+ const { priceUsageReport } = require('./session-usage-pricing');
6
7
  const { createSessionProjects } = require('./session-projects');
7
8
  const { createSessionFeatureSettings } = require('./session-feature-settings');
8
9
  const { createSessionDiagnostics } = require('./session-diagnostics');
10
+ const { createSessionEvidenceCollections } = require('./session-evidence-collections');
11
+ const { createSessionStories } = require('./session-stories');
9
12
 
10
13
  function createSessionFeatures(deps) {
11
14
  async function readNode(params) {
@@ -23,7 +26,17 @@ function createSessionFeatures(deps) {
23
26
  const projects = createSessionProjects({ ...deps, bookmarks });
24
27
  const settings = createSessionFeatureSettings(deps.root);
25
28
  const diagnostics = deps.diagnostics ? createSessionDiagnostics(deps.diagnostics) : null;
29
+ const collections = createSessionEvidenceCollections({ root: deps.root, readNode });
30
+ const stories = createSessionStories({ root: deps.root, projects });
26
31
  const actions = {
32
+ 'session-collections-list': () => collections.list(),
33
+ 'session-collection-open': (params) => collections.open(params),
34
+ 'session-collection-save': (params) => collections.save(params),
35
+ 'session-collection-remove': (params) => collections.remove(params),
36
+ 'session-stories-list': (params) => stories.list(params),
37
+ 'session-story-save': (params) => stories.save(params),
38
+ 'session-story-remove': (params) => stories.remove(params),
39
+ 'session-usage-pricing': async (params) => priceUsageReport(await deps.usageReport.read(params)),
27
40
  'session-diagnostics-targets': (params) => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.targets(params.cwd); },
28
41
  'session-diagnostics-start': (params) => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.start(params); },
29
42
  'session-diagnostics-status': () => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.status(); },
@@ -31,6 +44,8 @@ function createSessionFeatures(deps) {
31
44
  'session-feature-settings-get': () => settings.get(),
32
45
  'session-feature-settings-save': (params) => settings.save(params),
33
46
  'session-projects': (params) => projects.list(params),
47
+ 'session-project-git': (params) => projects.git(params),
48
+ 'session-project-git-commit': (params) => projects.commit(params),
34
49
  'session-project-map': (params) => projects.map(params),
35
50
  'session-project-prompt': (params) => projects.prompt(params),
36
51
  'session-handoff-draft': (params) => generateHandoffDraft(params, readNode),
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+ const { execFile } = require('child_process');
3
+ const path = require('path');
4
+ const MAX_COMMITS = 30;
5
+ const MAX_CHANGES = 50;
6
+ const TIME_WINDOW_MS = 24 * 60 * 60 * 1000;
7
+ const GIT_TIMEOUT_MS = 5000;
8
+ const MAX_OUTPUT_BYTES = 256 * 1024;
9
+ function git(cwd, args) {
10
+ return new Promise((resolve, reject) => execFile('git', ['--no-optional-locks', '-C', cwd, ...args],
11
+ { encoding: 'utf8', timeout: GIT_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true },
12
+ (error, stdout, stderr) => { if (error) { error.stderr = stderr; reject(error); } else resolve(stdout); }));
13
+ }
14
+ function changesFromStatus(output) {
15
+ const fields = output.split('\0');
16
+ const changes = [];
17
+ for (let index = 0; index < fields.length; index++) {
18
+ const field = fields[index];
19
+ if (!field) continue;
20
+ const status = field.slice(0, 2);
21
+ changes.push({ status, path: field.slice(3) });
22
+ if (/[RC]/.test(status)) index++;
23
+ }
24
+ return { changes: changes.slice(0, MAX_CHANGES), changedFiles: changes.length, changesTruncated: changes.length > MAX_CHANGES };
25
+ }
26
+ async function readProjectGit({ cwd, sessions }) {
27
+ const readAt = new Date().toISOString();
28
+ if (!cwd || !path.isAbsolute(cwd)) return { status: 'path-unavailable', readAt };
29
+ try {
30
+ const root = (await git(cwd, ['rev-parse', '--show-toplevel'])).trim();
31
+ const state = changesFromStatus(await git(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=normal']));
32
+ const branch = (await git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(error => {
33
+ if (error.code === 1) return ''; throw error;
34
+ })).trim();
35
+ const head = (await git(cwd, ['rev-parse', '--verify', '--quiet', 'HEAD']).catch(error => {
36
+ if (error.code === 1) return ''; throw error;
37
+ })).trim();
38
+ if (!head) return { status: 'unborn', root, branch, head, readAt, commits: [], ...state };
39
+ const history = await git(cwd, ['log', `-${MAX_COMMITS + 1}`, '--format=%H%x00%cI%x00%s%x00']);
40
+ const fields = history.split('\0');
41
+ const commits = [];
42
+ for (let index = 0; index + 2 < fields.length; index += 3) {
43
+ const sha = fields[index].trim();
44
+ if (!sha) continue;
45
+ const timestamp = fields[index + 1];
46
+ const time = Date.parse(timestamp);
47
+ const candidates = sessions.filter(session => path.resolve(session.cwd || cwd) === path.resolve(cwd)
48
+ && Number.isFinite(Date.parse(session.updatedAt || session.timestamp))
49
+ && Math.abs(time - Date.parse(session.updatedAt || session.timestamp)) <= TIME_WINDOW_MS);
50
+ commits.push({ sha, timestamp, subject: fields[index + 2], candidates });
51
+ }
52
+ return { status: 'ready', root, branch, head, readAt, ...state, commits: commits.slice(0, MAX_COMMITS),
53
+ commitsTruncated: commits.length > MAX_COMMITS, association: 'session-update-within-24h', readOnly: true };
54
+ } catch (error) {
55
+ const status = error.code === 'ENOENT' ? 'git-unavailable' : /not a git repository/.test(error.stderr || '') ? 'not-repository'
56
+ : /cannot change to/.test(error.stderr || '') ? 'path-unavailable' : error.killed ? 'read-timeout' : 'read-failed';
57
+ return { status, readAt, readOnly: true };
58
+ }
59
+ }
60
+ async function readCommitFiles({ cwd, sha }) {
61
+ if (!/^[a-f0-9]{40,64}$/.test(sha || '')) throw new Error('project-git-commit-invalid');
62
+ const output = await git(cwd, ['show', '--format=', '--stat', '--no-ext-diff', '--no-textconv', sha, '--']);
63
+ return { sha, stat: output, readOnly: true, readAt: new Date().toISOString() };
64
+ }
65
+ module.exports = { readProjectGit, readCommitFiles };
@@ -4,6 +4,7 @@ const path = require('path');
4
4
  const { createLocalFeatureStore } = require('./local-feature-store');
5
5
  const { projectKey } = require('./session-bookmarks');
6
6
  const { SOURCES } = require('./session-search-index');
7
+ const { readProjectGit, readCommitFiles } = require('./session-project-git');
7
8
  const PROJECT_DISCOVERY_LIMIT = 3000;
8
9
  const PROJECT_SESSION_LIMIT = 100;
9
10
 
@@ -71,6 +72,16 @@ function createSessionProjects({ root, inventory, bookmarks, handoffs }) {
71
72
  if (!stat.isFile() || stat.size > 2 * 1024 * 1024) throw new Error('feature-read-failed');
72
73
  return { filePath: file, content: fs.readFileSync(file, 'utf8'), readOnly: true };
73
74
  }
74
- return { list, map, prompt };
75
+ async function git(params) {
76
+ const report = await list({ project: params.project });
77
+ if (!report.detail) throw new Error('project-mapping-invalid');
78
+ return readProjectGit({ cwd: report.detail.cwd, sessions: report.detail.sessions });
79
+ }
80
+ async function commit(params) {
81
+ const report = await git(params);
82
+ if (!report.commits?.some(item => item.sha === params.sha)) throw new Error('project-git-commit-invalid');
83
+ return readCommitFiles({ cwd: report.root, sha: params.sha });
84
+ }
85
+ return { list, map, prompt, git, commit };
75
86
  }
76
87
  module.exports = { createSessionProjects };
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+ const path = require('path');
3
+ const { createLocalFeatureStore, digest } = require('./local-feature-store');
4
+ const { projectKey } = require('./session-bookmarks');
5
+ const SHA_PATTERN = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
6
+ const MAX_NOTE_LENGTH = 4000;
7
+ const sessionKey = session => JSON.stringify([session.source, session.sessionId, session.filePath]);
8
+
9
+ function createSessionStories({ root, projects }) {
10
+ const store = createLocalFeatureStore(path.join(root, 'stories.json'), { version: 1, items: [] });
11
+ function snapshot() {
12
+ const current = store.read();
13
+ if (!Array.isArray(current.value.items) || current.value.items.some(item => !item || typeof item.id !== 'string'
14
+ || typeof item.project !== 'string' || !SHA_PATTERN.test(item.sha || '') || typeof item.note !== 'string'
15
+ || !item.session || ['source', 'sessionId', 'filePath', 'cwd', 'title'].some(key => typeof item.session[key] !== 'string'))) {
16
+ throw new Error('feature-store-invalid');
17
+ }
18
+ return current;
19
+ }
20
+ async function projectSessions(project) {
21
+ if (typeof project !== 'string' || !path.isAbsolute(project)) throw new Error('story-input-invalid');
22
+ const report = await projects.list({ project });
23
+ if (report.detail && projectKey(report.detail.cwd) !== projectKey(project)) throw new Error('story-project-unavailable');
24
+ return (report.detail?.sessions || []).filter(session => projectKey(session.cwd) === projectKey(project));
25
+ }
26
+ async function list(params) {
27
+ const sessions = await projectSessions(params.project);
28
+ const current = snapshot();
29
+ const items = current.value.items.filter(item => item.project === projectKey(params.project)).map(item => ({ ...item,
30
+ available: sessions.some(session => sessionKey(session) === sessionKey(item.session)), association: 'user-linked' }));
31
+ return { items, sessions, revision: current.revision, scope: 'discovered-candidates', readAt: new Date().toISOString() };
32
+ }
33
+ async function save(params) {
34
+ const current = snapshot();
35
+ if (current.revision !== params.revision) throw new Error('feature-store-conflict');
36
+ if (!SHA_PATTERN.test(params.sha || '') || typeof params.note !== 'string' || params.note.length > MAX_NOTE_LENGTH
37
+ || !params.session) throw new Error('story-input-invalid');
38
+ const sessions = await projectSessions(params.project);
39
+ const session = sessions.find(entry => sessionKey(entry) === sessionKey(params.session));
40
+ if (!session) throw new Error('story-session-unavailable');
41
+ // Only bind commits actually offered by the existing read-only project view.
42
+ const report = await projects.git({ project: params.project });
43
+ if (!report.commits?.some(commit => commit.sha === params.sha)) throw new Error('project-git-commit-invalid');
44
+ const project = projectKey(params.project);
45
+ const id = digest(JSON.stringify([project, params.sha, sessionKey(session)]));
46
+ const existing = current.value.items.find(item => item.id === id);
47
+ const now = new Date().toISOString();
48
+ const item = { id, project, sha: params.sha, session: { source: session.source, sessionId: session.sessionId,
49
+ filePath: session.filePath, cwd: session.cwd, title: session.title }, note: params.note,
50
+ createdAt: existing?.createdAt || now, updatedAt: now };
51
+ if (existing) current.value.items[current.value.items.indexOf(existing)] = item;
52
+ else current.value.items.unshift(item);
53
+ store.write(current.value, current.revision);
54
+ return { ...await list(params), item };
55
+ }
56
+ async function remove(params) {
57
+ await projectSessions(params.project);
58
+ const current = snapshot();
59
+ if (current.revision !== params.revision) throw new Error('feature-store-conflict');
60
+ if (!current.value.items.some(item => item.id === params.id && item.project === projectKey(params.project))) throw new Error('story-not-found');
61
+ current.value.items = current.value.items.filter(item => item.id !== params.id);
62
+ store.write(current.value, current.revision);
63
+ return list(params);
64
+ }
65
+ return { list, save, remove };
66
+ }
67
+ module.exports = { createSessionStories };
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ const FIELDS = ['inputTokens', 'cachedInputTokens', 'cacheCreationInputTokens', 'outputTokens', 'totalTokens'];
4
+ function count(value) {
5
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
6
+ }
7
+ function readUsage(usage, source) {
8
+ if (!usage || typeof usage !== 'object') return null;
9
+ if (source === 'gemini') usage = { input: usage.input, output: usage.output,
10
+ cached_input_tokens: usage.cached, total_tokens: usage.total };
11
+ const input = count(usage.input_tokens ?? usage.inputTokens ?? usage.input);
12
+ const output = count(usage.output_tokens ?? usage.outputTokens ?? usage.output);
13
+ const cached = count(usage.cached_input_tokens ?? usage.cache_read_input_tokens ?? usage.cacheRead
14
+ ?? usage.input_tokens_details?.cached_tokens);
15
+ const created = count(usage.cache_creation_input_tokens ?? usage.cacheWrite);
16
+ const total = count(usage.total_tokens ?? usage.totalTokens);
17
+ if ([input, output, cached, created, total].every(value => value === null)) return null;
18
+ // Codex cached input is a subset of input; reasoning is a subset of output.
19
+ // Gemini's recorded total includes reasoning/tool tokens; missing totals stay unknown.
20
+ const inferredTotal = (input || 0) + (output || 0) + (source === 'codex' ? 0 : (cached || 0) + (created || 0));
21
+ return { inputTokens: input, cachedInputTokens: cached, cacheCreationInputTokens: created,
22
+ outputTokens: output, totalTokens: total ?? (source !== 'gemini' && input !== null && output !== null ? inferredTotal : null) };
23
+ }
24
+ function recordModel(record, fallback) {
25
+ const model = record?.message?.model ?? record?.payload?.model ?? record?.model;
26
+ return typeof model === 'string' && model.trim() && model !== '<synthetic>' ? model.trim() : fallback;
27
+ }
28
+ function recordTime(record) {
29
+ const timestamp = record?.timestamp ?? record?.message?.timestamp;
30
+ return typeof timestamp === 'string' && Number.isFinite(Date.parse(timestamp)) ? new Date(timestamp).toISOString() : '';
31
+ }
32
+
33
+ function createSessionUsageLedger(session) {
34
+ const source = session.source;
35
+ const supported = ['codex', 'claude', 'pi', 'gemini'].includes(source);
36
+ let model = Array.isArray(session.models) && session.models.length > 1 ? 'unknown' : (session.model || 'unknown');
37
+ const snapshots = new Map();
38
+ const rows = new Map();
39
+ let cumulative;
40
+ let observedRecords = 0;
41
+ function add(record) {
42
+ model = recordModel(record, model);
43
+ if (!supported) return;
44
+ const payload = record?.payload;
45
+ const message = record?.message;
46
+ const isCodex = source === 'codex' && record?.type === 'event_msg' && payload?.type === 'token_count';
47
+ const isGemini = source === 'gemini' && record?.type === 'gemini';
48
+ const isAssistant = message?.role === 'assistant' || record?.type === 'assistant' || record?.role === 'assistant' || isGemini;
49
+ if (!isCodex && !isAssistant) return;
50
+ const usage = isGemini ? record.tokens : (isCodex ? payload?.info?.total_token_usage : (message?.usage ?? record?.usage));
51
+ const totals = readUsage(usage, source);
52
+ if (!totals) return;
53
+ const requestId = message?.id ?? record?.id ?? record?.uuid;
54
+ const previous = isCodex ? cumulative : (requestId ? snapshots.get(requestId) : null);
55
+ const reset = isCodex && previous && totals.totalTokens < previous.totalTokens;
56
+ const delta = Object.fromEntries(FIELDS.map(field => {
57
+ if (totals[field] === null) return [field, null];
58
+ const before = !reset && previous ? previous[field] || 0 : 0;
59
+ return [field, Math.max(0, totals[field] - before)];
60
+ }));
61
+ if (isCodex) cumulative = totals;
62
+ else if (requestId) snapshots.set(requestId, Object.fromEntries(FIELDS.map(field =>
63
+ [field, totals[field] === null ? previous?.[field] ?? null : Math.max(totals[field], previous?.[field] || 0)])));
64
+ if (previous && FIELDS.every(field => !delta[field])) return;
65
+ observedRecords++;
66
+ const timestamp = recordTime(record);
67
+ const date = timestamp.slice(0, 10);
68
+ const key = `${date}\n${model}`;
69
+ const row = rows.get(key) || { date, source, model, ...Object.fromEntries(FIELDS.map(field => [field, 0])), usageEvents: 0 };
70
+ for (const field of FIELDS) row[field] = row[field] === null || delta[field] === null ? null : row[field] + delta[field];
71
+ row.usageEvents += 1;
72
+ rows.set(key, row);
73
+ }
74
+ return { add, finish: () => ({ supported, observedRecords, rows: [...rows.values()] }) };
75
+ }
76
+
77
+ module.exports = { createSessionUsageLedger, FIELDS };
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+ const snapshot = require('./data/model-prices.json');
3
+ const TOKEN_FIELDS = ['inputTokens', 'outputTokens', 'cachedInputTokens', 'cacheCreationInputTokens'];
4
+ const RATE_FIELDS = ['input_cost_per_token', 'output_cost_per_token', 'cache_read_input_token_cost', 'cache_creation_input_token_cost'];
5
+ const INCLUDED_CACHE_SOURCES = ['codex', 'gemini'];
6
+
7
+ function estimateUsageRow(row, catalog = snapshot) {
8
+ const rates = catalog.models[row.model];
9
+ const unknown = reason => ({ ...row, estimatedUsd: null, reason, rates: rates || null });
10
+ if (!rates) return unknown('model-unknown');
11
+ const counts = TOKEN_FIELDS.map(field => row[field]);
12
+ if (INCLUDED_CACHE_SOURCES.includes(row.source)) {
13
+ counts[3] = counts[3] ?? 0;
14
+ if (counts[0] !== null && counts[2] !== null) counts[0] -= counts[2];
15
+ }
16
+ if (counts.some(count => !Number.isSafeInteger(count) || count < 0)) return unknown('usage-incomplete');
17
+ // Gemini totals can include reasoning/tool tokens absent from the priced categories.
18
+ if (!Number.isSafeInteger(row.totalTokens) || counts.reduce((sum, count) => sum + count, 0) !== row.totalTokens) return unknown('usage-unclassified');
19
+ let estimatedUsd = 0;
20
+ for (const [index, count] of counts.entries()) {
21
+ if (!count) continue;
22
+ const rate = rates[RATE_FIELDS[index]];
23
+ if (typeof rate !== 'number' || !Number.isFinite(rate) || rate < 0) return unknown('rate-missing');
24
+ estimatedUsd += count * rate;
25
+ }
26
+ if (!Number.isFinite(estimatedUsd)) return unknown('usage-incomplete');
27
+ return { ...row, estimatedUsd, reason: 'base-rate', rates };
28
+ }
29
+
30
+ function priceUsageReport(report, catalog = snapshot) {
31
+ const rows = report.rows.map(row => estimateUsageRow(row, catalog));
32
+ const priced = rows.filter(row => row.estimatedUsd !== null);
33
+ const knownSubtotalUsd = priced.reduce((sum, row) => sum + row.estimatedUsd, 0);
34
+ const complete = rows.length > 0 && priced.length === rows.length && !report.summary.failedSessions.length
35
+ && !report.summary.unreportedSessions && !report.summary.unsupportedSessions;
36
+ const { models, license, ...priceSource } = catalog;
37
+ return { rows, priceSource, summary: { knownSubtotalUsd, estimatedUsd: complete ? knownSubtotalUsd : null,
38
+ pricedRows: priced.length, unknownRows: rows.length - priced.length, complete,
39
+ failedSessions: report.summary.failedSessions.length, unreportedSessions: report.summary.unreportedSessions,
40
+ unsupportedSessions: report.summary.unsupportedSessions }, timezone: report.timezone, attribution: 'base-rate-reference' };
41
+ }
42
+ module.exports = { estimateUsageRow, priceUsageReport };
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+
3
+ const { createSessionUsageLedger, FIELDS } = require('./session-usage-ledger');
4
+ const { createContextRecordReader } = require('./session-context-records');
5
+ const { createConcurrencyLimiter } = require('../cli/session-usage.concurrent');
6
+ const { parseUsageExportDate, normalizeUsageExportModelFilters, sessionMatchesUsageExportModelFilters } = require('../cli/session-usage');
7
+ const CACHE_LIMIT = 256;
8
+ const CONCURRENCY = 4;
9
+ const COLUMNS = ['date', 'source', 'model', ...FIELDS, 'usageEvents', 'sessions'];
10
+
11
+ function mergeRows(reports, params) {
12
+ if ([params.from, params.to].some(value => value && !/^\d{4}-\d{2}-\d{2}$/.test(value))) {
13
+ throw new Error('Invalid usage date range; records require YYYY-MM-DD');
14
+ }
15
+ const from = parseUsageExportDate(params.from, 'start');
16
+ const to = parseUsageExportDate(params.to, 'end');
17
+ if (Number.isNaN(from) || Number.isNaN(to) || (from !== null && to !== null && from >= to)) {
18
+ throw new Error('Invalid usage date range');
19
+ }
20
+ const filters = normalizeUsageExportModelFilters(params);
21
+ const groups = new Map();
22
+ for (const report of reports) {
23
+ for (const row of report.rows) {
24
+ if (!sessionMatchesUsageExportModelFilters(row, filters)) continue;
25
+ const timestamp = row.date ? Date.parse(row.date + 'T00:00:00.000Z') : null;
26
+ if ((from !== null || to !== null) && timestamp === null) continue;
27
+ if ((from !== null && timestamp < from) || (to !== null && timestamp >= to)) continue;
28
+ const key = `${row.date}\n${row.source}\n${row.model}`;
29
+ const group = groups.get(key) || { date: row.date, source: row.source, model: row.model,
30
+ ...Object.fromEntries(FIELDS.map(field => [field, 0])), usageEvents: 0, sessions: 0 };
31
+ for (const field of FIELDS) group[field] = group[field] === null || row[field] === null ? null : group[field] + row[field];
32
+ group.usageEvents += row.usageEvents;
33
+ group.sessions++;
34
+ groups.set(key, group);
35
+ }
36
+ }
37
+ return [...groups.values()].sort((a, b) => a.date.localeCompare(b.date) || a.source.localeCompare(b.source) || a.model.localeCompare(b.model));
38
+ }
39
+
40
+ function createSessionUsageReportController(deps) {
41
+ const cache = new Map();
42
+ const limit = createConcurrencyLimiter(CONCURRENCY);
43
+ async function scan(session, forceRefresh) {
44
+ const stat = session.filePath ? await deps.fs.promises.stat(session.filePath) : null;
45
+ const signature = stat ? `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` : '';
46
+ const key = `${session.source}:${session.filePath || session.sessionId}:${session.model || ''}`;
47
+ if (!forceRefresh && signature && cache.get(key)?.signature === signature) return cache.get(key).report;
48
+ const { createContextAnalyzer } = await import('../web-ui/logic.context-health.mjs');
49
+ const analyzer = createContextAnalyzer();
50
+ const reader = createContextRecordReader(session.source, session.cwd || '');
51
+ const ledger = createSessionUsageLedger(session);
52
+ let index = 0;
53
+ for await (const record of deps.iterateSessionUsageRecords(session)) {
54
+ for (const node of reader(record, index++)) analyzer.add(node);
55
+ ledger.add(record);
56
+ }
57
+ if (stat) {
58
+ const after = await deps.fs.promises.stat(session.filePath);
59
+ if (`${after.size}:${after.mtimeMs}:${after.ctimeMs}` !== signature) throw new Error('Session changed during usage scan; refresh');
60
+ }
61
+ const report = { ...ledger.finish(), estimatedTextTokens: analyzer.finish().totalEstimatedTokens };
62
+ if (signature) {
63
+ cache.delete(key);
64
+ cache.set(key, { signature, report });
65
+ if (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
66
+ }
67
+ return report;
68
+ }
69
+ async function read(params = {}) {
70
+ // Validate filters before touching session files.
71
+ mergeRows([], params);
72
+ // Refresh discovery independently; unchanged numeric ledgers still reuse the scan cache.
73
+ const sessions = await deps.listSessionUsage({ ...params, forceRefresh: true });
74
+ const reports = await Promise.all(sessions.map(session => limit(async () => {
75
+ try { return { ...await scan(session, params.forceRefresh), source: session.source, sessionId: session.sessionId || '' }; }
76
+ catch (error) { return { error: error.message, source: session.source, sessionId: session.sessionId || '', rows: [] }; }
77
+ })));
78
+ const rows = mergeRows(reports, params);
79
+ const totals = Object.fromEntries(FIELDS.map(field => [field, !rows.length || rows.some(row => row[field] === null)
80
+ ? null : rows.reduce((sum, row) => sum + row[field], 0)]));
81
+ return { attribution: 'records', timezone: 'UTC', estimator: 'cjk-1-non-cjk-4-v1', rows,
82
+ summary: { ...totals, scannedSessions: reports.filter(report => !report.error).length,
83
+ candidateSessions: sessions.length, unreportedSessions: reports.filter(report => !report.error && !report.observedRecords).length,
84
+ unsupportedSessions: reports.filter(report => !report.error && !report.supported).length,
85
+ failedSessions: reports.filter(report => report.error).map(({ source, sessionId, error }) => ({ source, sessionId, error })),
86
+ undatedTokens: reports.flatMap(report => report.rows).filter(row => !row.date).reduce((sum, row) => sum + row.totalTokens, 0),
87
+ estimatedTextTokens: reports.reduce((sum, report) => sum + (report.estimatedTextTokens || 0), 0) } };
88
+ }
89
+ return { read };
90
+ }
91
+
92
+ function exportSessionUsageReport(report, format = 'csv') {
93
+ if (report.summary.failedSessions.length) return { error: 'Usage scan incomplete; inspect read-sessions-usage-report and refresh' };
94
+ const extension = format === 'json' ? 'json' : 'csv';
95
+ const csvCell = value => value === null ? '' : /[",\r\n]/.test(String(value)) ? '"' + String(value).replace(/"/g, '""') + '"' : String(value);
96
+ const content = extension === 'json' ? JSON.stringify(report, null, 2) + '\n'
97
+ : [COLUMNS.join(','), ...report.rows.map(row => COLUMNS.map(field => csvCell(row[field])).join(','))].join('\r\n') + '\r\n';
98
+ return { format: extension, mimeType: extension === 'json' ? 'application/json' : 'text/csv',
99
+ fileName: `usage-records.${extension}`, rows: report.rows, content };
100
+ }
101
+ module.exports = { createSessionUsageReportController, exportSessionUsageReport };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codexmate",
3
- "version": "0.1.34",
3
+ "version": "0.1.36",
4
4
  "description": "Codex/Claude Code/OpenClaw 配置、会话与任务编排 CLI + Web 工具",
5
5
  "main": "cli.js",
6
6
  "bin": {
@@ -41,6 +41,9 @@
41
41
  "test:ci": "node tools/ci/run-check.js all",
42
42
  "test:unit": "node tests/unit/run.mjs",
43
43
  "test:e2e": "node tests/e2e/run.js",
44
+ "test:file-sharing": "node tests/e2e/file-sharing-acceptance.cjs",
45
+ "test:file-sharing:lan": "node tests/e2e/file-sharing-acceptance.cjs --lan",
46
+ "test:usage-records": "node tests/e2e/usage-records-acceptance.cjs",
44
47
  "test:e2e:browser": "e2e run",
45
48
  "test:e2e:browser:install": "e2e-web install chromium --with-deps",
46
49
  "test:e2e:browser:list": "e2e list",
@@ -158,12 +158,21 @@ function localizeBuiltinPromptTemplate(item, t) {
158
158
 
159
159
  import { pluginsRegistry } from '../registry.mjs';
160
160
 
161
+ const PLUGIN_TAB_ORDER = new Map([
162
+ ['prompt-templates', 0],
163
+ ['text-tools', 1],
164
+ ['file-sharing', 2]
165
+ ]);
166
+
161
167
  export function createPromptTemplatesComputed() {
162
168
  return {
163
169
  pluginsCatalog() {
164
170
  return pluginsRegistry
165
171
  .map((entry) => entry && entry.meta)
166
172
  .filter(Boolean)
173
+ .sort((left, right) =>
174
+ (PLUGIN_TAB_ORDER.get(left.id) ?? PLUGIN_TAB_ORDER.size)
175
+ - (PLUGIN_TAB_ORDER.get(right.id) ?? PLUGIN_TAB_ORDER.size))
167
176
  .map((meta) => localizePluginMeta(meta, this.t));
168
177
  },
169
178
 
package/web-ui/app.js CHANGED
@@ -326,6 +326,11 @@ document.addEventListener('DOMContentLoaded', () => {
326
326
  sessionsViewMode: 'browser',
327
327
  sessionsUsageTimeRange: '7d',
328
328
  sessionsUsageList: [],
329
+ usageRecords: null,
330
+ usageRecordsLoading: false,
331
+ usageRecordsError: '',
332
+ usageRecordsRange: '',
333
+ usageRecordsOpen: false,
329
334
  sessionsUsageCompareEnabled: false,
330
335
  sessionsUsageSelectedDayKey: '',
331
336
  sessionsUsageLoadedOnce: false,
@@ -466,6 +471,8 @@ document.addEventListener('DOMContentLoaded', () => {
466
471
  currentClaudeConfig: '',
467
472
  currentClaudeModel: '',
468
473
  claudeCustomModelDraft: '',
474
+ claudeProviderPresetQuery: '',
475
+ claudeAddFromPreset: false,
469
476
  editingConfig: { name: '', apiKey: '', baseUrl: '', model: '', targetApi: 'responses' },
470
477
  claudeConfigs: {
471
478
  '智谱GLM': {
@@ -946,6 +953,11 @@ document.addEventListener('DOMContentLoaded', () => {
946
953
  this.persistWebUiPreferences({ sysPromptScope: newVal });
947
954
  }
948
955
  },
956
+ sysPromptFileName(newVal) {
957
+ if (typeof this.persistWebUiPreferences === 'function') {
958
+ this.persistWebUiPreferences({ sysPromptFileName: newVal });
959
+ }
960
+ },
949
961
  sysPromptMode(newVal) {
950
962
  if (typeof this.persistWebUiPreferences === 'function') {
951
963
  this.persistWebUiPreferences({ sysPromptMode: newVal });
@@ -3,6 +3,7 @@
3
3
  // 所以 catalog 仅按 baseUrl 的 host/path 命中。
4
4
 
5
5
  const DEFAULT_OPENAI_CODEX_CATALOG = Object.freeze([
6
+ 'gpt-5.4-mini',
6
7
  'gpt-5-codex',
7
8
  'gpt-5',
8
9
  'gpt-5-mini',
@@ -46,6 +47,19 @@ export function getCodexModelCatalogForProvider(provider) {
46
47
  // model 字段为可选首选项(添加后由前端写入内存字典 currentModels[name])。
47
48
  // useTransform=true 表示该服务需通过内建 OpenAI bridge 转发。
48
49
  export const CODEX_PROVIDER_TEMPLATES = Object.freeze([
50
+ {
51
+ label: 'OpenAI API',
52
+ name: 'openai-api',
53
+ url: 'https://api.openai.com/v1',
54
+ model: 'gpt-5.4-mini'
55
+ },
56
+ {
57
+ label: 'Groq',
58
+ name: 'groq',
59
+ url: 'https://api.groq.com/openai/v1',
60
+ model: 'openai/gpt-oss-120b',
61
+ useTransform: true
62
+ },
49
63
  {
50
64
  label: 'MuAPI',
51
65
  name: 'muapi',