codexmate 0.0.20 → 0.0.22

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 (96) hide show
  1. package/README.md +289 -152
  2. package/README.zh.md +321 -0
  3. package/cli/agents-files.js +224 -0
  4. package/cli/archive-helpers.js +446 -0
  5. package/cli/auth-profiles.js +359 -0
  6. package/cli/builtin-proxy.js +1044 -0
  7. package/cli/claude-proxy.js +998 -0
  8. package/cli/config-bootstrap.js +384 -0
  9. package/cli/openai-bridge.js +950 -0
  10. package/cli/openclaw-config.js +629 -0
  11. package/cli/session-usage.concurrent.js +28 -0
  12. package/cli/session-usage.js +112 -0
  13. package/cli/session-usage.models.js +176 -0
  14. package/cli/skills.js +1141 -0
  15. package/cli/zip-commands.js +510 -0
  16. package/cli.js +9408 -9719
  17. package/lib/cli-models-utils.js +109 -1
  18. package/lib/cli-path-utils.js +69 -0
  19. package/lib/cli-sessions.js +386 -0
  20. package/lib/download-artifacts.js +77 -0
  21. package/lib/task-orchestrator.js +869 -0
  22. package/package.json +14 -10
  23. package/res/logo.png +0 -0
  24. package/res/vue.global.prod.js +13 -0
  25. package/web-ui/app.js +193 -15
  26. package/web-ui/index.html +5 -1
  27. package/web-ui/logic.agents-diff.mjs +1 -1
  28. package/web-ui/logic.claude.mjs +60 -0
  29. package/web-ui/logic.runtime.mjs +11 -7
  30. package/web-ui/logic.sessions.mjs +372 -21
  31. package/web-ui/modules/api.mjs +22 -1
  32. package/web-ui/modules/app.computed.dashboard.mjs +23 -10
  33. package/web-ui/modules/app.computed.index.mjs +4 -0
  34. package/web-ui/modules/app.computed.main-tabs.mjs +198 -0
  35. package/web-ui/modules/app.computed.session.mjs +521 -9
  36. package/web-ui/modules/app.methods.agents.mjs +62 -11
  37. package/web-ui/modules/app.methods.codex-config.mjs +189 -34
  38. package/web-ui/modules/app.methods.index.mjs +7 -1
  39. package/web-ui/modules/app.methods.install.mjs +24 -20
  40. package/web-ui/modules/app.methods.navigation.mjs +142 -1
  41. package/web-ui/modules/app.methods.openclaw-core.mjs +339 -39
  42. package/web-ui/modules/app.methods.openclaw-editing.mjs +39 -4
  43. package/web-ui/modules/app.methods.openclaw-persist.mjs +122 -4
  44. package/web-ui/modules/app.methods.providers.mjs +192 -53
  45. package/web-ui/modules/app.methods.session-actions.mjs +99 -19
  46. package/web-ui/modules/app.methods.session-browser.mjs +196 -5
  47. package/web-ui/modules/app.methods.session-timeline.mjs +22 -15
  48. package/web-ui/modules/app.methods.session-trash.mjs +3 -0
  49. package/web-ui/modules/app.methods.startup-claude.mjs +70 -71
  50. package/web-ui/modules/app.methods.task-orchestration.mjs +471 -0
  51. package/web-ui/modules/config-mode.computed.mjs +2 -0
  52. package/web-ui/modules/config-template-confirm-pref.mjs +33 -0
  53. package/web-ui/modules/i18n.mjs +1609 -0
  54. package/web-ui/modules/plugins.computed.mjs +220 -0
  55. package/web-ui/modules/plugins.methods.mjs +620 -0
  56. package/web-ui/modules/plugins.storage.mjs +37 -0
  57. package/web-ui/partials/index/layout-footer.html +1 -57
  58. package/web-ui/partials/index/layout-header.html +299 -175
  59. package/web-ui/partials/index/modal-config-template-agents.html +79 -29
  60. package/web-ui/partials/index/modal-confirm-toast.html +1 -1
  61. package/web-ui/partials/index/modal-health-check.html +14 -14
  62. package/web-ui/partials/index/modal-openclaw-config.html +47 -42
  63. package/web-ui/partials/index/modal-skills.html +130 -114
  64. package/web-ui/partials/index/modals-basic.html +71 -102
  65. package/web-ui/partials/index/panel-config-claude.html +50 -12
  66. package/web-ui/partials/index/panel-config-codex.html +34 -37
  67. package/web-ui/partials/index/panel-config-openclaw.html +10 -16
  68. package/web-ui/partials/index/panel-docs.html +147 -0
  69. package/web-ui/partials/index/panel-market.html +38 -38
  70. package/web-ui/partials/index/panel-orchestration.html +397 -0
  71. package/web-ui/partials/index/panel-plugins.html +243 -0
  72. package/web-ui/partials/index/panel-sessions.html +51 -146
  73. package/web-ui/partials/index/panel-settings.html +188 -96
  74. package/web-ui/partials/index/panel-usage.html +353 -0
  75. package/web-ui/session-helpers.mjs +221 -10
  76. package/web-ui/styles/base-theme.css +120 -229
  77. package/web-ui/styles/controls-forms.css +59 -51
  78. package/web-ui/styles/docs-panel.css +247 -0
  79. package/web-ui/styles/layout-shell.css +394 -128
  80. package/web-ui/styles/modals-core.css +18 -3
  81. package/web-ui/styles/navigation-panels.css +184 -183
  82. package/web-ui/styles/plugins-panel.css +518 -0
  83. package/web-ui/styles/responsive.css +102 -62
  84. package/web-ui/styles/sessions-list.css +13 -27
  85. package/web-ui/styles/sessions-preview.css +13 -7
  86. package/web-ui/styles/sessions-toolbar-trash.css +25 -0
  87. package/web-ui/styles/sessions-usage.css +581 -6
  88. package/web-ui/styles/settings-panel.css +166 -0
  89. package/web-ui/styles/skills-list.css +16 -11
  90. package/web-ui/styles/skills-market.css +63 -2
  91. package/web-ui/styles/task-orchestration.css +776 -0
  92. package/web-ui/styles/titles-cards.css +67 -66
  93. package/web-ui/styles.css +4 -0
  94. package/README.en.md +0 -259
  95. package/res/screenshot.png +0 -0
  96. package/res/vue.global.js +0 -18552
@@ -1,6 +1,112 @@
1
1
  const crypto = require('crypto');
2
2
  const { joinApiUrl, normalizeBaseUrl } = require('./cli-utils');
3
3
 
4
+ const BIGMODEL_CLAUDE_COMPAT_MODELS = Object.freeze([
5
+ 'glm-3-turbo',
6
+ 'glm-4',
7
+ 'glm-4-0520',
8
+ 'glm-4-plus',
9
+ 'glm-4-air',
10
+ 'glm-4-airx',
11
+ 'glm-4-flash',
12
+ 'glm-4-flashx',
13
+ 'glm-4v',
14
+ 'glm-4v-flash',
15
+ 'glm-4v-plus',
16
+ 'glm-4v-plus-0111',
17
+ 'glm-4.5',
18
+ 'glm-4.5-air',
19
+ 'glm-4.5v',
20
+ 'glm-4.6',
21
+ 'glm-4.6v',
22
+ 'glm-4.7',
23
+ 'glm-4.7-flash',
24
+ 'glm-4.7-flashx',
25
+ 'glm-5',
26
+ 'glm-5-turbo',
27
+ 'glm-5.1',
28
+ 'glm-5v',
29
+ 'glm-5v-turbo',
30
+ 'glm-z1',
31
+ 'glm-z1-air',
32
+ 'glm-coding'
33
+ ]);
34
+
35
+ const ANTHROPIC_CLAUDE_MODELS = Object.freeze([
36
+ 'claude-opus-4-6',
37
+ 'claude-opus-4-1',
38
+ 'claude-opus-4',
39
+ 'claude-sonnet-4-6',
40
+ 'claude-sonnet-4-5',
41
+ 'claude-sonnet-4',
42
+ 'claude-haiku-4-5',
43
+ 'claude-3-7-sonnet',
44
+ 'claude-3-5-sonnet',
45
+ 'claude-3-5-haiku',
46
+ 'claude-3-opus',
47
+ 'claude-3-sonnet',
48
+ 'claude-3-haiku'
49
+ ]);
50
+
51
+ function normalizeModelCatalogId(value) {
52
+ return typeof value === 'string' ? value.trim().toLowerCase() : '';
53
+ }
54
+
55
+ function isBigModelClaudeCompatibleBaseUrl(baseUrl) {
56
+ const normalized = normalizeBaseUrl(baseUrl);
57
+ if (!normalized) return false;
58
+ try {
59
+ const parsed = new URL(normalized);
60
+ const host = String(parsed.hostname || '').toLowerCase();
61
+ const pathname = String(parsed.pathname || '').toLowerCase();
62
+ const isBigModelHost = host === 'bigmodel.cn' || host.endsWith('.bigmodel.cn');
63
+ const hasAnthropicSegment = /(^|\/)anthropic(\/|$)/.test(pathname);
64
+ return isBigModelHost && hasAnthropicSegment;
65
+ } catch (_) {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ function isAnthropicBaseUrl(baseUrl) {
71
+ const normalized = normalizeBaseUrl(baseUrl);
72
+ if (!normalized) return false;
73
+ try {
74
+ const parsed = new URL(normalized);
75
+ const host = String(parsed.hostname || '').toLowerCase();
76
+ return host === 'api.anthropic.com' || host.endsWith('.anthropic.com');
77
+ } catch (_) {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ function getSupplementalModelsForBaseUrl(baseUrl) {
83
+ if (isBigModelClaudeCompatibleBaseUrl(baseUrl)) {
84
+ return [...BIGMODEL_CLAUDE_COMPAT_MODELS];
85
+ }
86
+ if (isAnthropicBaseUrl(baseUrl)) {
87
+ return [...ANTHROPIC_CLAUDE_MODELS];
88
+ }
89
+ return [];
90
+ }
91
+
92
+ function mergeModelCatalog(remoteModels = [], supplementalModels = []) {
93
+ const merged = [];
94
+ const seen = new Set();
95
+ const push = (value) => {
96
+ if (typeof value !== 'string') return;
97
+ const trimmed = value.trim();
98
+ if (!trimmed) return;
99
+ const normalized = normalizeModelCatalogId(trimmed);
100
+ if (!normalized || seen.has(normalized)) return;
101
+ seen.add(normalized);
102
+ merged.push(trimmed);
103
+ };
104
+
105
+ for (const item of remoteModels) push(item);
106
+ for (const item of supplementalModels) push(item);
107
+ return merged;
108
+ }
109
+
4
110
  function extractModelNames(payload) {
5
111
  if (!payload || typeof payload !== 'object') return [];
6
112
  const data = Array.isArray(payload.data)
@@ -307,5 +413,7 @@ module.exports = {
307
413
  buildModelConversationSpecs,
308
414
  extractModelResponseText,
309
415
  hashModelsCacheValue,
310
- buildModelsCacheKey
416
+ buildModelsCacheKey,
417
+ getSupplementalModelsForBaseUrl,
418
+ mergeModelCatalog
311
419
  };
@@ -0,0 +1,69 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { execSync } = require('child_process');
4
+
5
+ function normalizePathForCompare(targetPath, options = {}) {
6
+ const ignoreCase = !!options.ignoreCase;
7
+ let resolved = '';
8
+ try {
9
+ resolved = fs.realpathSync.native ? fs.realpathSync.native(targetPath) : fs.realpathSync(targetPath);
10
+ } catch (e) {
11
+ resolved = path.resolve(targetPath);
12
+ }
13
+ return ignoreCase ? resolved.toLowerCase() : resolved;
14
+ }
15
+
16
+ function isPathInside(targetPath, rootPath) {
17
+ if (!targetPath || !rootPath) {
18
+ return false;
19
+ }
20
+ const ignoreCase = process.platform === 'win32';
21
+ const resolvedTarget = normalizePathForCompare(targetPath, { ignoreCase });
22
+ const resolvedRoot = normalizePathForCompare(rootPath, { ignoreCase });
23
+ if (resolvedTarget === resolvedRoot) {
24
+ return true;
25
+ }
26
+ const separator = resolvedRoot.includes('/') && !resolvedRoot.includes('\\') ? '/' : path.sep;
27
+ const rootWithSlash = resolvedRoot.endsWith(separator) ? resolvedRoot : resolvedRoot + separator;
28
+ return resolvedTarget.startsWith(rootWithSlash);
29
+ }
30
+
31
+ function resolveCopyTargetRoot(targetDir) {
32
+ const base = typeof targetDir === 'string' ? targetDir.trim() : '';
33
+ const pathApi = base.includes('/') && !base.includes('\\') && path.posix ? path.posix : path;
34
+ const suffixSegments = [];
35
+ let current = pathApi.resolve(base || '');
36
+ while (current && !fs.existsSync(current)) {
37
+ const parent = pathApi.dirname(current);
38
+ if (!parent || parent === current) {
39
+ break;
40
+ }
41
+ suffixSegments.unshift(pathApi.basename(current));
42
+ current = parent;
43
+ }
44
+ let resolvedRoot = normalizePathForCompare(current || base);
45
+ if (!resolvedRoot) {
46
+ resolvedRoot = pathApi.resolve(base || '');
47
+ }
48
+ for (const segment of suffixSegments) {
49
+ resolvedRoot = pathApi.join(resolvedRoot, segment);
50
+ }
51
+ return resolvedRoot;
52
+ }
53
+
54
+ function commandExists(command, args = '') {
55
+ try {
56
+ execSync(`${command} ${args}`, { stdio: 'ignore', shell: process.platform === 'win32' });
57
+ return true;
58
+ } catch (e) {
59
+ return false;
60
+ }
61
+ }
62
+
63
+ module.exports = {
64
+ normalizePathForCompare,
65
+ isPathInside,
66
+ resolveCopyTargetRoot,
67
+ commandExists
68
+ };
69
+
@@ -0,0 +1,386 @@
1
+ const fs = require('fs');
2
+
3
+ const {
4
+ toIsoTime,
5
+ truncateText,
6
+ extractMessageText,
7
+ normalizeRole
8
+ } = require('./cli-session-utils');
9
+
10
+ const DEFAULT_SESSION_DETAIL_MESSAGES = 300;
11
+ const FAST_SESSION_DETAIL_PREVIEW_FILE_BYTES = 256 * 1024;
12
+ const FAST_SESSION_DETAIL_PREVIEW_CHUNK_BYTES = 64 * 1024;
13
+ const FAST_SESSION_DETAIL_PREVIEW_MAX_BYTES = 1024 * 1024;
14
+
15
+ const BOOTSTRAP_TEXT_MARKERS = [
16
+ 'agents.md instructions',
17
+ '<instructions>',
18
+ '<environment_context>',
19
+ 'you are a coding agent',
20
+ 'codex cli'
21
+ ];
22
+
23
+ function getFileStatSafe(filePath) {
24
+ try {
25
+ return fs.statSync(filePath);
26
+ } catch (e) {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ function isBootstrapLikeText(text) {
32
+ if (!text || typeof text !== 'string') {
33
+ return false;
34
+ }
35
+
36
+ const normalized = text.toLowerCase().replace(/\s+/g, ' ').trim();
37
+ if (!normalized) {
38
+ return false;
39
+ }
40
+
41
+ return BOOTSTRAP_TEXT_MARKERS.some(marker => normalized.includes(marker));
42
+ }
43
+
44
+ function removeLeadingSystemMessage(messages) {
45
+ if (!Array.isArray(messages) || messages.length === 0) {
46
+ return [];
47
+ }
48
+
49
+ let startIndex = 0;
50
+ while (startIndex < messages.length) {
51
+ const item = messages[startIndex];
52
+ const role = item ? normalizeRole(item.role) : '';
53
+ const text = item && typeof item.text === 'string' ? item.text : '';
54
+ const isSystemRole = role === 'system';
55
+ const isBootstrapText = isBootstrapLikeText(text);
56
+ if (!item || isSystemRole || isBootstrapText) {
57
+ startIndex += 1;
58
+ continue;
59
+ }
60
+ break;
61
+ }
62
+
63
+ if (startIndex <= 0) {
64
+ return messages;
65
+ }
66
+ return messages.slice(startIndex);
67
+ }
68
+
69
+ function normalizeQueryTokens(query) {
70
+ if (typeof query !== 'string') {
71
+ return [];
72
+ }
73
+ return query
74
+ .split(/\s+/)
75
+ .map(item => item.trim())
76
+ .map(item => item.toLowerCase())
77
+ .filter(Boolean);
78
+ }
79
+
80
+ function expandSessionQueryTokens(tokens) {
81
+ const base = Array.isArray(tokens) ? tokens.map(t => String(t || '').toLowerCase()).filter(Boolean) : [];
82
+ const result = [];
83
+ const seen = new Set();
84
+ let hasClaudeAlias = false;
85
+ let hasDaudeAlias = false;
86
+
87
+ // First pass: detect multi-token aliases (e.g., "claude code", "daude code")
88
+ for (let i = 0; i < base.length; i++) {
89
+ const token = base[i];
90
+ const nextToken = base[i + 1] || '';
91
+
92
+ // Check for "claude code" pattern (two separate tokens)
93
+ if (token === 'claude' && nextToken === 'code') {
94
+ hasClaudeAlias = true;
95
+ i++; // Skip next token
96
+ continue;
97
+ }
98
+ // Check for "daude code" pattern (two separate tokens)
99
+ if (token === 'daude' && nextToken === 'code') {
100
+ hasDaudeAlias = true;
101
+ i++; // Skip next token
102
+ continue;
103
+ }
104
+ // Check for combined patterns (e.g., "claude-code", "claude_code", "claudecode")
105
+ if (/^claude[-_ ]?code$/.test(token) || token === 'claudecode') {
106
+ hasClaudeAlias = true;
107
+ continue;
108
+ }
109
+ if (/^daude[-_ ]?code$/.test(token) || token === 'daudecode') {
110
+ hasDaudeAlias = true;
111
+ continue;
112
+ }
113
+ if (!seen.has(token)) {
114
+ seen.add(token);
115
+ result.push(token);
116
+ }
117
+ }
118
+
119
+ const push = (token) => {
120
+ const normalized = String(token || '').toLowerCase();
121
+ if (!normalized || seen.has(normalized)) return;
122
+ seen.add(normalized);
123
+ result.push(normalized);
124
+ };
125
+
126
+ if (hasClaudeAlias) {
127
+ push('claude');
128
+ push('code');
129
+ }
130
+ if (hasDaudeAlias) {
131
+ push('daude');
132
+ push('code');
133
+ }
134
+
135
+ return result;
136
+ }
137
+
138
+ function matchTokensInText(text, tokens, mode = 'and') {
139
+ if (!Array.isArray(tokens) || tokens.length === 0) {
140
+ return true;
141
+ }
142
+ const haystack = String(text || '').toLowerCase();
143
+ if (!haystack) {
144
+ return false;
145
+ }
146
+ if (mode === 'or') {
147
+ return tokens.some(token => haystack.includes(token));
148
+ }
149
+ return tokens.every(token => haystack.includes(token));
150
+ }
151
+
152
+ function extractMessageFromRecord(record, source) {
153
+ if (!record) {
154
+ return null;
155
+ }
156
+ if (source === 'codex') {
157
+ if (record.type === 'response_item' && record.payload && record.payload.type === 'message') {
158
+ const role = normalizeRole(record.payload.role);
159
+ const text = extractMessageText(record.payload.content);
160
+ if (!role || !text) {
161
+ return null;
162
+ }
163
+ return { role, text };
164
+ }
165
+ return null;
166
+ }
167
+
168
+ const role = normalizeRole(record.type);
169
+ if (!role) {
170
+ return null;
171
+ }
172
+ const content = record.message ? record.message.content : '';
173
+ const text = extractMessageText(content);
174
+ if (!text) {
175
+ return null;
176
+ }
177
+ return { role, text };
178
+ }
179
+
180
+ function appendSessionDetailTailMessage(state, record, source, lineIndex = -1) {
181
+ if (!state || typeof state !== 'object') {
182
+ return;
183
+ }
184
+
185
+ const message = extractMessageFromRecord(record, source);
186
+ if (!message) {
187
+ return;
188
+ }
189
+
190
+ const role = normalizeRole(message.role);
191
+ const text = typeof message.text === 'string' ? message.text : '';
192
+ if (!role || !text) {
193
+ return;
194
+ }
195
+
196
+ if (state.leadingSystem && (role === 'system' || isBootstrapLikeText(text))) {
197
+ return;
198
+ }
199
+
200
+ state.leadingSystem = false;
201
+ state.totalMessages += 1;
202
+ if (!Number.isFinite(state.tailLimit) || state.tailLimit <= 0) {
203
+ return;
204
+ }
205
+
206
+ if (state.messages.length >= state.tailLimit) {
207
+ state.messages.shift();
208
+ }
209
+ state.messages.push({
210
+ role,
211
+ text,
212
+ timestamp: toIsoTime(record && record.timestamp, ''),
213
+ recordLineIndex: Number.isInteger(lineIndex) ? lineIndex : -1
214
+ });
215
+ }
216
+
217
+ function applySessionDetailRecordMetadata(record, source, state) {
218
+ if (!state || typeof state !== 'object' || !record) {
219
+ return;
220
+ }
221
+
222
+ if (record.timestamp) {
223
+ state.updatedAt = toIsoTime(record.timestamp, state.updatedAt);
224
+ }
225
+
226
+ if (source === 'codex') {
227
+ if (record.type === 'session_meta' && record.payload) {
228
+ state.sessionId = record.payload.id || state.sessionId;
229
+ state.cwd = record.payload.cwd || state.cwd;
230
+ }
231
+ return;
232
+ }
233
+
234
+ if (!state.sessionId && record.sessionId) {
235
+ state.sessionId = record.sessionId;
236
+ }
237
+ if (!state.cwd && record.cwd) {
238
+ state.cwd = record.cwd;
239
+ }
240
+ }
241
+
242
+ function extractSessionDetailPreviewFromTailText(text, source, messageLimit) {
243
+ const safeMessageLimit = Number.isFinite(Number(messageLimit))
244
+ ? Math.max(1, Math.floor(Number(messageLimit)))
245
+ : DEFAULT_SESSION_DETAIL_MESSAGES;
246
+ const state = {
247
+ sessionId: '',
248
+ cwd: '',
249
+ updatedAt: '',
250
+ messages: [],
251
+ tailLimit: safeMessageLimit,
252
+ totalMessages: null,
253
+ clipped: false
254
+ };
255
+ const lines = typeof text === 'string' && text
256
+ ? text.split(/\r?\n/)
257
+ : [];
258
+
259
+ for (let lineIndex = lines.length - 1; lineIndex >= 0; lineIndex -= 1) {
260
+ const trimmed = lines[lineIndex].trim();
261
+ if (!trimmed) {
262
+ continue;
263
+ }
264
+
265
+ let record;
266
+ try {
267
+ record = JSON.parse(trimmed);
268
+ } catch (_) {
269
+ continue;
270
+ }
271
+
272
+ if (record && record.timestamp && !state.updatedAt) {
273
+ state.updatedAt = toIsoTime(record.timestamp, '');
274
+ }
275
+ if ((!state.sessionId || !state.cwd) && record) {
276
+ applySessionDetailRecordMetadata(record, source, state);
277
+ }
278
+
279
+ const message = extractMessageFromRecord(record, source);
280
+ if (!message) {
281
+ continue;
282
+ }
283
+
284
+ const role = normalizeRole(message.role);
285
+ const textValue = typeof message.text === 'string' ? message.text : '';
286
+ if (!role || !textValue) {
287
+ continue;
288
+ }
289
+
290
+ if (state.messages.length >= safeMessageLimit) {
291
+ state.clipped = true;
292
+ break;
293
+ }
294
+
295
+ state.messages.unshift({
296
+ role,
297
+ text: textValue,
298
+ timestamp: toIsoTime(record && record.timestamp, ''),
299
+ recordLineIndex: -1
300
+ });
301
+ }
302
+
303
+ return state;
304
+ }
305
+
306
+ function extractSessionDetailPreviewFromFileFast(filePath, source, messageLimit) {
307
+ const fileStat = getFileStatSafe(filePath);
308
+ if (!fileStat || !Number.isFinite(fileStat.size) || fileStat.size <= FAST_SESSION_DETAIL_PREVIEW_FILE_BYTES) {
309
+ return null;
310
+ }
311
+ const safeMessageLimit = Number.isFinite(Number(messageLimit))
312
+ ? Math.max(1, Math.floor(Number(messageLimit)))
313
+ : DEFAULT_SESSION_DETAIL_MESSAGES;
314
+
315
+ let fd = null;
316
+ let position = fileStat.size;
317
+ let totalBytesRead = 0;
318
+ let combined = Buffer.alloc(0);
319
+ let latest = {
320
+ sessionId: '',
321
+ cwd: '',
322
+ updatedAt: '',
323
+ messages: [],
324
+ totalMessages: null,
325
+ clipped: false
326
+ };
327
+
328
+ try {
329
+ fd = fs.openSync(filePath, 'r');
330
+ while (position > 0 && totalBytesRead < FAST_SESSION_DETAIL_PREVIEW_MAX_BYTES) {
331
+ const remainingBudget = FAST_SESSION_DETAIL_PREVIEW_MAX_BYTES - totalBytesRead;
332
+ const chunkSize = Math.min(FAST_SESSION_DETAIL_PREVIEW_CHUNK_BYTES, position, remainingBudget);
333
+ if (chunkSize <= 0) {
334
+ break;
335
+ }
336
+
337
+ position -= chunkSize;
338
+ const chunk = Buffer.allocUnsafe(chunkSize);
339
+ const bytesRead = fs.readSync(fd, chunk, 0, chunkSize, position);
340
+ if (bytesRead <= 0) {
341
+ break;
342
+ }
343
+
344
+ totalBytesRead += bytesRead;
345
+ combined = Buffer.concat([chunk.subarray(0, bytesRead), combined]);
346
+ latest = extractSessionDetailPreviewFromTailText(combined.toString('utf-8'), source, safeMessageLimit);
347
+ if (latest.messages.length >= safeMessageLimit) {
348
+ latest.clipped = latest.clipped || position > 0;
349
+ return latest;
350
+ }
351
+ }
352
+
353
+ if (position > 0) {
354
+ latest.clipped = latest.clipped || position > 0;
355
+ return latest;
356
+ }
357
+ const normalizedMessages = removeLeadingSystemMessage(latest.messages);
358
+ latest.messages = normalizedMessages.length > safeMessageLimit
359
+ ? normalizedMessages.slice(-safeMessageLimit)
360
+ : normalizedMessages;
361
+ latest.totalMessages = normalizedMessages.length;
362
+ latest.clipped = latest.totalMessages > latest.messages.length;
363
+ return latest;
364
+ } catch (_) {
365
+ return null;
366
+ } finally {
367
+ if (fd !== null) {
368
+ try { fs.closeSync(fd); } catch (e) {}
369
+ }
370
+ }
371
+ }
372
+
373
+ module.exports = {
374
+ BOOTSTRAP_TEXT_MARKERS,
375
+ getFileStatSafe,
376
+ isBootstrapLikeText,
377
+ removeLeadingSystemMessage,
378
+ normalizeQueryTokens,
379
+ expandSessionQueryTokens,
380
+ matchTokensInText,
381
+ extractMessageFromRecord,
382
+ appendSessionDetailTailMessage,
383
+ applySessionDetailRecordMetadata,
384
+ extractSessionDetailPreviewFromTailText,
385
+ extractSessionDetailPreviewFromFileFast
386
+ };
@@ -0,0 +1,77 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+
5
+ const DEFAULT_DOWNLOAD_ARTIFACT_TTL_MS = 10 * 60 * 1000;
6
+ const g_downloadArtifacts = new Map();
7
+
8
+ function registerDownloadArtifact(filePath, options = {}) {
9
+ const token = crypto.randomBytes(16).toString('hex');
10
+ const fileName = typeof options.fileName === 'string' && options.fileName.trim()
11
+ ? options.fileName.trim()
12
+ : path.basename(filePath || '');
13
+ const ttlMs = Number.isFinite(options.ttlMs) && options.ttlMs > 0
14
+ ? Math.floor(options.ttlMs)
15
+ : DEFAULT_DOWNLOAD_ARTIFACT_TTL_MS;
16
+ const expiresAt = Date.now() + ttlMs;
17
+ const deleteAfterDownload = options.deleteAfterDownload !== false;
18
+
19
+ g_downloadArtifacts.set(token, {
20
+ filePath,
21
+ fileName,
22
+ deleteAfterDownload,
23
+ expiresAt
24
+ });
25
+
26
+ setTimeout(() => {
27
+ const artifact = g_downloadArtifacts.get(token);
28
+ if (!artifact) return;
29
+ if (Date.now() < artifact.expiresAt) return;
30
+ g_downloadArtifacts.delete(token);
31
+ if (artifact.deleteAfterDownload && artifact.filePath && fs.existsSync(artifact.filePath)) {
32
+ try {
33
+ fs.unlinkSync(artifact.filePath);
34
+ } catch (_) {}
35
+ }
36
+ }, ttlMs + 2000);
37
+
38
+ return {
39
+ token,
40
+ fileName,
41
+ downloadPath: `/download/${encodeURIComponent(token)}`
42
+ };
43
+ }
44
+
45
+ function resolveDownloadArtifact(tokenOrFileName, options = {}) {
46
+ if (!tokenOrFileName) return null;
47
+ const token = typeof tokenOrFileName === 'string' ? tokenOrFileName.trim() : '';
48
+ if (!token) return null;
49
+
50
+ const artifact = g_downloadArtifacts.get(token);
51
+ if (!artifact) {
52
+ return null;
53
+ }
54
+ if (Date.now() > artifact.expiresAt) {
55
+ g_downloadArtifacts.delete(token);
56
+ if (artifact.deleteAfterDownload && artifact.filePath && fs.existsSync(artifact.filePath)) {
57
+ try {
58
+ fs.unlinkSync(artifact.filePath);
59
+ } catch (_) {}
60
+ }
61
+ return null;
62
+ }
63
+ if (options && options.consume === true) {
64
+ g_downloadArtifacts.delete(token);
65
+ }
66
+ return {
67
+ token,
68
+ ...artifact
69
+ };
70
+ }
71
+
72
+ module.exports = {
73
+ DEFAULT_DOWNLOAD_ARTIFACT_TTL_MS,
74
+ registerDownloadArtifact,
75
+ resolveDownloadArtifact
76
+ };
77
+