codexmate 0.1.30 → 0.1.32

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 (77) hide show
  1. package/README.md +98 -7
  2. package/README.vi.md +98 -7
  3. package/README.zh.md +99 -7
  4. package/cli/agents-files.js +18 -4
  5. package/cli/config-bootstrap.js +25 -11
  6. package/cli/plugin-config.js +64 -0
  7. package/cli/prompt-history.js +17 -4
  8. package/cli/system-prompt-files.js +7 -2
  9. package/cli.js +396 -46
  10. package/lib/cli-config-engine.js +266 -0
  11. package/lib/cli-utils.js +2 -1
  12. package/lib/cli-webhook.js +1 -1
  13. package/lib/handoff-mcp.js +282 -0
  14. package/lib/http-access-control.js +335 -0
  15. package/lib/session-context-health.js +82 -0
  16. package/lib/session-context-records.js +153 -0
  17. package/lib/thread-handoff.js +130 -0
  18. package/lib/web-startup-auth.js +53 -0
  19. package/lib/workflow-engine.js +92 -21
  20. package/lib/workflow-runner.js +261 -0
  21. package/package.json +1 -1
  22. package/plugins/prompt-templates/computed.mjs +3 -3
  23. package/plugins/prompt-templates/invocation.mjs +73 -0
  24. package/plugins/prompt-templates/methods.mjs +48 -3
  25. package/plugins/prompt-templates/overview.mjs +2 -0
  26. package/web-ui/app.js +48 -2
  27. package/web-ui/index.html +1 -0
  28. package/web-ui/logic.context-health.mjs +144 -0
  29. package/web-ui/modules/access-token.mjs +33 -0
  30. package/web-ui/modules/api.mjs +2 -1
  31. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  32. package/web-ui/modules/app.methods.agents.mjs +20 -3
  33. package/web-ui/modules/app.methods.index.mjs +6 -0
  34. package/web-ui/modules/app.methods.navigation.mjs +17 -3
  35. package/web-ui/modules/app.methods.prompts-editor.mjs +7 -0
  36. package/web-ui/modules/app.methods.providers.mjs +2 -2
  37. package/web-ui/modules/app.methods.runtime.mjs +3 -2
  38. package/web-ui/modules/app.methods.session-actions.mjs +3 -0
  39. package/web-ui/modules/app.methods.session-browser.mjs +6 -2
  40. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  41. package/web-ui/modules/app.methods.workflows.mjs +41 -0
  42. package/web-ui/modules/context-health.methods.mjs +70 -0
  43. package/web-ui/modules/i18n/locales/en.mjs +70 -2
  44. package/web-ui/modules/i18n/locales/ja.mjs +70 -2
  45. package/web-ui/modules/i18n/locales/vi.mjs +70 -2
  46. package/web-ui/modules/i18n/locales/zh-tw.mjs +70 -2
  47. package/web-ui/modules/i18n/locales/zh.mjs +70 -2
  48. package/web-ui/modules/plugins.methods.mjs +2 -0
  49. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  50. package/web-ui/modules/sessions-filters-url.mjs +3 -0
  51. package/web-ui/modules/skills.methods.mjs +6 -5
  52. package/web-ui/modules/thread-handoff.mjs +142 -0
  53. package/web-ui/partials/index/context-health.html +45 -0
  54. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  55. package/web-ui/partials/index/panel-config-claude.html +2 -0
  56. package/web-ui/partials/index/panel-config-codex.html +2 -0
  57. package/web-ui/partials/index/panel-config-kilocode.html +3 -1
  58. package/web-ui/partials/index/panel-config-openclaw.html +2 -0
  59. package/web-ui/partials/index/panel-config-opencode.html +3 -1
  60. package/web-ui/partials/index/panel-config-pi.html +2 -0
  61. package/web-ui/partials/index/panel-dashboard.html +59 -0
  62. package/web-ui/partials/index/panel-plugins.html +37 -9
  63. package/web-ui/partials/index/panel-prompts.html +46 -18
  64. package/web-ui/partials/index/panel-sessions.html +35 -44
  65. package/web-ui/partials/index/thread-handoff.html +59 -0
  66. package/web-ui/res/web-ui-render.precompiled.js +1289 -177
  67. package/web-ui/styles/context-health.css +107 -0
  68. package/web-ui/styles/controls-forms.css +9 -0
  69. package/web-ui/styles/dashboard.css +51 -0
  70. package/web-ui/styles/modals-core.css +87 -0
  71. package/web-ui/styles/navigation-panels.css +1 -1
  72. package/web-ui/styles/plugins-panel.css +62 -0
  73. package/web-ui/styles/prompts-editor.css +34 -4
  74. package/web-ui/styles/responsive.css +19 -10
  75. package/web-ui/styles/sessions-preview.css +206 -111
  76. package/web-ui/styles/sub-tabs.css +181 -0
  77. package/web-ui/styles.css +2 -0
@@ -0,0 +1,335 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const net = require('net');
5
+
6
+ const IPV4_BYTE_COUNT = 4;
7
+ const IPV6_BYTE_COUNT = 16;
8
+ const IPV4_PREFIX_MAX = 32;
9
+ const IPV6_PREFIX_MAX = 128;
10
+ const BITS_PER_BYTE = 8;
11
+ const AUTH_REALM = 'codexmate';
12
+ const SECURITY_HEADERS = Object.freeze({
13
+ 'X-Content-Type-Options': 'nosniff',
14
+ 'X-Frame-Options': 'DENY',
15
+ 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws: wss:"
16
+ });
17
+
18
+ function parseIpv4Bytes(value) {
19
+ if (net.isIP(value) !== 4) {
20
+ return null;
21
+ }
22
+ return Buffer.from(value.split('.').map((part) => Number(part)));
23
+ }
24
+
25
+ function parseIpv6Words(value) {
26
+ if (net.isIP(value) !== 6) {
27
+ return null;
28
+ }
29
+ const halves = value.split('::');
30
+ if (halves.length > 2) {
31
+ return null;
32
+ }
33
+
34
+ const parseSide = (side) => {
35
+ if (!side) {
36
+ return [];
37
+ }
38
+ const words = [];
39
+ const tokens = side.split(':');
40
+ for (let index = 0; index < tokens.length; index += 1) {
41
+ const token = tokens[index];
42
+ if (token.includes('.')) {
43
+ if (index !== tokens.length - 1) {
44
+ return null;
45
+ }
46
+ const ipv4 = parseIpv4Bytes(token);
47
+ if (!ipv4) {
48
+ return null;
49
+ }
50
+ words.push(ipv4[0] * 256 + ipv4[1]);
51
+ words.push(ipv4[2] * 256 + ipv4[3]);
52
+ continue;
53
+ }
54
+ if (!/^[0-9a-f]{1,4}$/i.test(token)) {
55
+ return null;
56
+ }
57
+ words.push(parseInt(token, 16));
58
+ }
59
+ return words;
60
+ };
61
+
62
+ const left = parseSide(halves[0]);
63
+ const right = parseSide(halves[1] || '');
64
+ if (!left || !right) {
65
+ return null;
66
+ }
67
+
68
+ let words;
69
+ if (halves.length === 1) {
70
+ if (left.length !== 8) {
71
+ return null;
72
+ }
73
+ words = left;
74
+ } else {
75
+ const missing = 8 - left.length - right.length;
76
+ if (missing < 1) {
77
+ return null;
78
+ }
79
+ words = left.concat(new Array(missing).fill(0), right);
80
+ }
81
+
82
+ const bytes = Buffer.alloc(IPV6_BYTE_COUNT);
83
+ for (let index = 0; index < words.length; index += 1) {
84
+ bytes.writeUInt16BE(words[index], index * 2);
85
+ }
86
+ return bytes;
87
+ }
88
+
89
+ function parseIp(value) {
90
+ if (typeof value !== 'string') {
91
+ return null;
92
+ }
93
+ const address = value.trim();
94
+ const ipv4 = parseIpv4Bytes(address);
95
+ if (ipv4) {
96
+ return { version: 4, bytes: ipv4 };
97
+ }
98
+ const ipv6 = parseIpv6Words(address);
99
+ if (ipv6) {
100
+ return { version: 6, bytes: ipv6 };
101
+ }
102
+ return null;
103
+ }
104
+
105
+ function isIpv4Mapped(bytes) {
106
+ if (bytes.length !== IPV6_BYTE_COUNT) {
107
+ return false;
108
+ }
109
+ for (let index = 0; index < 10; index += 1) {
110
+ if (bytes[index] !== 0) {
111
+ return false;
112
+ }
113
+ }
114
+ return bytes[10] === 255 && bytes[11] === 255;
115
+ }
116
+
117
+ function normalizeIp(ip) {
118
+ if (ip && ip.version === 6 && isIpv4Mapped(ip.bytes)) {
119
+ return { version: 4, bytes: ip.bytes.slice(12, 16) };
120
+ }
121
+ return ip;
122
+ }
123
+
124
+ function parseCidr(value) {
125
+ if (typeof value !== 'string') {
126
+ return null;
127
+ }
128
+ const parts = value.trim().split('/');
129
+ if (parts.length > 2) {
130
+ return null;
131
+ }
132
+ const ip = parseIp(parts[0]);
133
+ if (!ip) {
134
+ return null;
135
+ }
136
+ let prefix = null;
137
+ if (parts.length === 2) {
138
+ if (!/^\d+$/.test(parts[1])) {
139
+ return null;
140
+ }
141
+ prefix = Number(parts[1]);
142
+ }
143
+ const maxPrefix = ip.version === 4 ? IPV4_PREFIX_MAX : IPV6_PREFIX_MAX;
144
+ if (prefix !== null && prefix > maxPrefix) {
145
+ return null;
146
+ }
147
+ if (ip.version === 6 && isIpv4Mapped(ip.bytes) && (prefix === null || prefix >= 96)) {
148
+ return {
149
+ version: 4,
150
+ bytes: ip.bytes.slice(12, 16),
151
+ prefix: prefix === null ? IPV4_PREFIX_MAX : prefix - 96
152
+ };
153
+ }
154
+ return {
155
+ version: ip.version,
156
+ bytes: ip.bytes,
157
+ prefix: prefix === null ? maxPrefix : prefix
158
+ };
159
+ }
160
+
161
+ function parseAllowedIps(value) {
162
+ let source = value;
163
+ if (source === undefined || source === null) {
164
+ source = [];
165
+ } else if (typeof source === 'string') {
166
+ source = source.split(',');
167
+ } else if (!Array.isArray(source)) {
168
+ throw new Error('parseAllowedIps: allowed IP list must be a string or an array');
169
+ }
170
+
171
+ const entries = [];
172
+ for (const item of source) {
173
+ if (typeof item !== 'string') {
174
+ throw new Error('parseAllowedIps: allowed IP entries must be strings');
175
+ }
176
+ for (const part of item.split(',')) {
177
+ const entry = part.trim();
178
+ if (!entry) {
179
+ continue;
180
+ }
181
+ if (!parseCidr(entry)) {
182
+ throw new Error(`parseAllowedIps: invalid CIDR entry "${entry}"`);
183
+ }
184
+ entries.push(entry);
185
+ }
186
+ }
187
+ return entries;
188
+ }
189
+
190
+ function bytesMatchPrefix(left, right, prefix) {
191
+ const fullBytes = Math.floor(prefix / BITS_PER_BYTE);
192
+ for (let index = 0; index < fullBytes; index += 1) {
193
+ if (left[index] !== right[index]) {
194
+ return false;
195
+ }
196
+ }
197
+ const remainingBits = prefix % BITS_PER_BYTE;
198
+ if (!remainingBits) {
199
+ return true;
200
+ }
201
+ const mask = (0xff << (BITS_PER_BYTE - remainingBits)) & 0xff;
202
+ return (left[fullBytes] & mask) === (right[fullBytes] & mask);
203
+ }
204
+
205
+ function compileAllowedIps(allowedIps) {
206
+ return parseAllowedIps(allowedIps).map((entry) => parseCidr(entry));
207
+ }
208
+
209
+ function isIpAllowed(ip, allowedIps) {
210
+ const candidate = normalizeIp(parseIp(ip));
211
+ if (!candidate) {
212
+ return false;
213
+ }
214
+ return compileAllowedIps(allowedIps).some((rule) => (
215
+ candidate.version === rule.version &&
216
+ bytesMatchPrefix(candidate.bytes, rule.bytes, rule.prefix)
217
+ ));
218
+ }
219
+
220
+ function sendJson(res, statusCode, payload, headers = {}) {
221
+ const body = JSON.stringify(payload);
222
+ res.writeHead(statusCode, {
223
+ ...SECURITY_HEADERS,
224
+ ...headers,
225
+ 'Content-Type': 'application/json; charset=utf-8',
226
+ 'Content-Length': Buffer.byteLength(body)
227
+ });
228
+ res.end(body);
229
+ }
230
+ function tokensMatch(provided, expected) {
231
+ const providedDigest = crypto.createHash('sha256').update(provided, 'utf8').digest();
232
+ const expectedDigest = crypto.createHash('sha256').update(expected, 'utf8').digest();
233
+ return crypto.timingSafeEqual(providedDigest, expectedDigest);
234
+ }
235
+ function isLoopbackAddress(value) {
236
+ const candidate = normalizeIp(parseIp(value));
237
+ if (!candidate) {
238
+ return false;
239
+ }
240
+ if (candidate.version === 4) {
241
+ return candidate.bytes[0] === 127;
242
+ }
243
+ return candidate.bytes.every((byte, index) => (index === 15 ? byte === 1 : byte === 0));
244
+ }
245
+
246
+
247
+ function getBearerToken(req) {
248
+ const headers = req && req.headers;
249
+ const authorization = headers && headers.authorization;
250
+ if (typeof authorization !== 'string') {
251
+ return null;
252
+ }
253
+ const match = /^Bearer[ \t]+(.+)$/i.exec(authorization.trim());
254
+ if (!match || /\s/.test(match[1])) {
255
+ return null;
256
+ }
257
+ return match[1];
258
+ }
259
+
260
+ function createHttpAccessControlMiddleware(options = {}) {
261
+ const requiresToken = typeof options.requiresToken === 'function'
262
+ ? options.requiresToken
263
+ : () => true;
264
+ const bypassLoopback = options.bypassLoopback === true;
265
+ const token = typeof options.token === 'string' ? options.token.trim() : '';
266
+ const allowedRules = compileAllowedIps(options.allowedIps);
267
+
268
+ return (req, res, next) => {
269
+ if (allowedRules.length > 0) {
270
+ const remoteAddress = req && req.socket && req.socket.remoteAddress;
271
+ const candidate = normalizeIp(parseIp(remoteAddress));
272
+ const allowed = candidate && allowedRules.some((rule) => (
273
+ candidate.version === rule.version &&
274
+ bytesMatchPrefix(candidate.bytes, rule.bytes, rule.prefix)
275
+ ));
276
+ if (!allowed) {
277
+ sendJson(res, 403, { error: 'Forbidden' });
278
+ return;
279
+ }
280
+ }
281
+
282
+ const remoteAddress = req && req.socket && req.socket.remoteAddress;
283
+ const loopbackPeer = bypassLoopback && isLoopbackAddress(remoteAddress);
284
+ if (token && !loopbackPeer && requiresToken(req)) {
285
+ const provided = getBearerToken(req);
286
+ if (!provided || !tokensMatch(provided, token)) {
287
+ sendJson(res, 401, { error: 'Unauthorized' }, {
288
+ 'WWW-Authenticate': `Bearer realm="${AUTH_REALM}"`
289
+ });
290
+ return;
291
+ }
292
+ }
293
+
294
+ next();
295
+ };
296
+ }
297
+
298
+ function isLoopbackHost(host) {
299
+ if (typeof host !== 'string') {
300
+ return false;
301
+ }
302
+ let value = host.trim().toLowerCase();
303
+ if (!value) {
304
+ return false;
305
+ }
306
+ if (value.startsWith('[') && value.endsWith(']')) {
307
+ value = value.slice(1, -1);
308
+ }
309
+ if (value === 'localhost' || value === 'localhost.') {
310
+ return true;
311
+ }
312
+ const ip = normalizeIp(parseIp(value));
313
+ if (!ip) {
314
+ return false;
315
+ }
316
+ if (ip.version === 4) {
317
+ return ip.bytes[0] === 127;
318
+ }
319
+ return ip.bytes.every((byte, index) => (index === 15 ? byte === 1 : byte === 0));
320
+ }
321
+
322
+ function assertExternalTokenConfigured(host, token) {
323
+ const normalizedToken = typeof token === 'string' ? token.trim() : '';
324
+ if (!isLoopbackHost(host) && !normalizedToken) {
325
+ throw new Error('对外监听必须设置 CODEXMATE_HTTP_TOKEN');
326
+ }
327
+ }
328
+
329
+ module.exports = {
330
+ createHttpAccessControlMiddleware,
331
+ parseAllowedIps,
332
+ isIpAllowed,
333
+ isLoopbackHost,
334
+ assertExternalTokenConfigured
335
+ };
@@ -0,0 +1,82 @@
1
+ 'use strict';
2
+
3
+ const readline = require('readline');
4
+ const { createContextRecordReader } = require('./session-context-records');
5
+ const RULE_FIELDS = ['system_prompt', 'systemInstruction', 'instructions', 'project_rules', 'skills_instructions'];
6
+
7
+ function createSessionContextHealthController(deps) {
8
+ const { fs, normalizeSessionSourceName, resolveSessionFilePath, queryOpencodeSessionMessages, queryZedSessionMessages } = deps;
9
+ async function* records(source, filePath, sessionId) {
10
+ if (source === 'opencode' || source === 'zed') {
11
+ const query = source === 'zed' ? queryZedSessionMessages : queryOpencodeSessionMessages;
12
+ const data = query(sessionId, { maxMessages: Infinity, contextHealth: true });
13
+ if (!data) throw new Error('会话数据库读取失败');
14
+ if (data.cwd) yield { type: 'session_meta', payload: { cwd: data.cwd } };
15
+ if (data.instructions) yield { type: 'system_context', instructions: data.instructions };
16
+ for (const message of data.messages || []) yield message;
17
+ return;
18
+ }
19
+ if (source === 'gemini' || filePath.toLowerCase().endsWith('.json')) {
20
+ const data = JSON.parse(await fs.promises.readFile(filePath, 'utf8'));
21
+ const cwd = data.projectRoot || data.cwd;
22
+ if (cwd) yield { type: 'session_meta', payload: { cwd } };
23
+ for (const field of RULE_FIELDS) {
24
+ if (data[field]) yield { type: 'system_context', instructions: data[field] };
25
+ }
26
+ const messages = Array.isArray(data) ? data : (data.messages || data.children || []);
27
+ for (const message of messages) yield message;
28
+ return;
29
+ }
30
+ const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
31
+ const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
32
+ let readError;
33
+ stream.on('error', (error) => { readError = error; lines.close(); });
34
+ try {
35
+ for await (const line of lines) {
36
+ if (!line.trim()) { yield null; continue; }
37
+ try { yield JSON.parse(line.charCodeAt(0) === 0xFEFF ? line.slice(1) : line); }
38
+ catch (_) { throw new Error('会话含无法解析的消息记录'); }
39
+ }
40
+ if (readError) throw readError;
41
+ } finally { lines.close(); stream.destroy(); }
42
+ }
43
+ function resolve(params) {
44
+ const source = normalizeSessionSourceName(params.source, '');
45
+ if (!source) throw new Error('Invalid source');
46
+ const filePath = resolveSessionFilePath(source, params.filePath || params.file, params.sessionId);
47
+ if (!filePath) throw new Error('Session file not found');
48
+ return { source, filePath, sessionId: params.sessionId };
49
+ }
50
+ async function scan(params, focus) {
51
+ const target = resolve(params);
52
+ const { createContextAnalyzer } = await import('../web-ui/logic.context-health.mjs');
53
+ const analyzer = createContextAnalyzer();
54
+ const reader = createContextRecordReader(target.source, params.cwd || '');
55
+ let index = 0;
56
+ for await (const record of records(target.source, target.filePath, target.sessionId)) {
57
+ for (const node of reader(record, index)) {
58
+ if (!focus) analyzer.add(node);
59
+ if (node.id === focus) {
60
+ return { source: target.source, node: { id: node.id, role: node.role,
61
+ recordLineIndex: node.recordLineIndex, messageIndex: node.messageIndex,
62
+ text: node.parts.map((part) => part.text).join('\n') } };
63
+ }
64
+ }
65
+ index++;
66
+ }
67
+ if (focus) throw new Error('消息节点不存在,请刷新体检结果');
68
+ return { source: target.source, sessionId: target.sessionId, complete: true, scannedRecords: index, ...analyzer.finish() };
69
+ }
70
+ async function readSessionContextHealth(params = {}) {
71
+ try { return await scan(params); } catch (error) { return { error: error.message }; }
72
+ }
73
+ async function readSessionContextNode(params = {}) {
74
+ if (typeof params.nodeId !== 'string' || !/^record-\d+(?:\.(?:body-)?(?:children|messages|branches)-\d+)*$/.test(params.nodeId)) {
75
+ return { error: '消息节点 ID 无效' };
76
+ }
77
+ try { return await scan(params, params.nodeId); } catch (error) { return { error: error.message }; }
78
+ }
79
+ return { readSessionContextHealth, readSessionContextNode };
80
+ }
81
+
82
+ module.exports = { createSessionContextHealthController };
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+
3
+ const ROLE_CATEGORIES = { system: 'system', developer: 'system', skill: 'system', rules: 'system', user: 'user', human: 'user',
4
+ assistant: 'assistant', agent: 'assistant', model: 'assistant', gemini: 'assistant',
5
+ tool: 'tools', toolresult: 'tools', tool_result: 'tools', function_call_output: 'tools' };
6
+ const RULE_FIELDS = ['base_instructions', 'developer_instructions', 'system_prompt', 'systemInstruction', 'instructions', 'project_rules', 'skills_instructions'];
7
+
8
+ function categoryForRole(role) {
9
+ const key = String(role || '').toLowerCase();
10
+ return Object.prototype.hasOwnProperty.call(ROLE_CATEGORIES, key) ? ROLE_CATEGORIES[key] : '';
11
+ }
12
+
13
+ function contentParts(content, category) {
14
+ const parts = [];
15
+ const queue = [{ value: content, category }];
16
+ while (queue.length) {
17
+ const item = queue.pop();
18
+ const value = item.value;
19
+ if (typeof value === 'string') {
20
+ if (value) parts.push({ text: value, category: item.category });
21
+ continue;
22
+ }
23
+ if (!value || typeof value !== 'object') continue;
24
+ if (Array.isArray(value)) {
25
+ for (let index = value.length - 1; index >= 0; index--) queue.push({ value: value[index], category: item.category });
26
+ continue;
27
+ }
28
+ const type = String(value.type || '').toLowerCase();
29
+ const nextCategory = /^(code|diff)$/.test(type) || value.Code ? 'code'
30
+ : (/^(tool|tool_result|toolresult|function_call_output)$/.test(type) || value.ToolResult ? 'tools' : item.category);
31
+ const text = value.Text ?? value.text ?? value.thinking ?? value.Thinking ?? value.Code
32
+ ?? value.ToolResult ?? value.content ?? value.output ?? value.code ?? value.diff ?? value.value ?? value.summary ?? value.parts;
33
+ if (value.state && (value.state.output !== undefined || value.state.error !== undefined)) {
34
+ const output = value.state.output ?? value.state.error;
35
+ queue.push({ value: typeof output === 'object' ? JSON.stringify(output) : output, category: 'tools' });
36
+ } else if (/^(toolcall|tool_use)$/.test(type)) {
37
+ queue.push({ value: `${value.name || ''}\n${JSON.stringify(value.arguments || value.input || {})}`, category: 'assistant' });
38
+ } else if (text !== undefined) queue.push({ value: text, category: nextCategory });
39
+ }
40
+ return parts;
41
+ }
42
+
43
+ function normalizeReadPath(value, cwd) {
44
+ if (typeof value !== 'string' || !value.trim() || /^https?:\/\//i.test(value)) return '';
45
+ const raw = value.trim().replace(/\\/g, '/');
46
+ const full = raw.startsWith('/') || /^[A-Za-z]:\//.test(raw) ? raw : `${cwd || ''}/${raw}`;
47
+ const parts = [];
48
+ for (const part of full.split('/')) {
49
+ if (!part || part === '.') continue;
50
+ if (part === '..') parts.pop(); else parts.push(part);
51
+ }
52
+ return `${full.startsWith('/') ? '/' : ''}${parts.join('/')}`;
53
+ }
54
+
55
+ function readPaths(name, input, cwd) {
56
+ let args = input;
57
+ if (typeof input === 'string') { try { args = JSON.parse(input); } catch (_) { args = {}; } }
58
+ if (!args || typeof args !== 'object') return [];
59
+ const command = args.cmd || args.command || '';
60
+ const isRead = /read|cat|grep|get.content|open.file/i.test(name || '') || /(?:^|[\s;&|])(cat|sed|head|tail|rg|grep|Get-Content)\s/.test(command);
61
+ if (!isRead) return [];
62
+ const paths = [args.path, args.file_path, args.filePath, args.file, args.filename].filter((value) => typeof value === 'string');
63
+ if (!paths.length && command) {
64
+ const match = command.match(/(?:^|[;&|]\s*)(?:cat|sed|head|tail|rg|grep|Get-Content)\s+([^;&|]+)/);
65
+ const tokens = match ? match[1].match(/"[^"]+"|'[^']+'|\S+/g) || [] : [];
66
+ for (const token of tokens) {
67
+ const value = token.replace(/^['"]|['"]$/g, '');
68
+ if (!value.startsWith('-') && !/^\d+(?:,\d+)?[a-z]$/i.test(value)
69
+ && (value.includes('/') || /\.[A-Za-z0-9]+$/.test(value))) paths.push(value);
70
+ }
71
+ }
72
+ return paths.map((value) => normalizeReadPath(value, cwd)).filter(Boolean);
73
+ }
74
+
75
+ function createContextRecordReader(source, cwd = '') {
76
+ const calls = new Map();
77
+ return function readRecord(record, recordIndex) {
78
+ const metadataCwd = record?.type === 'session_meta' ? record.payload?.cwd : (record?.type === 'session' ? record.cwd : '');
79
+ if (typeof metadataCwd === 'string' && metadataCwd) cwd = metadataCwd;
80
+ const nodes = [];
81
+ const stack = [{ record, suffix: '' }];
82
+ while (stack.length) {
83
+ const current = stack.pop();
84
+ const raw = current.record;
85
+ if (!raw || typeof raw !== 'object') continue;
86
+ let body = raw.message && typeof raw.message === 'object' ? raw.message : raw;
87
+ if (source === 'codex' && raw.type === 'response_item') body = raw.payload || {};
88
+ if (raw.User) body = { ...raw.User, role: 'user' };
89
+ if (raw.Agent) body = { ...raw.Agent, role: 'assistant' };
90
+ if (raw.Tool || raw.ToolResult) body = { content: raw.Tool || raw.ToolResult, role: 'tool' };
91
+ if (raw.System) body = { content: raw.System.content ?? raw.System, role: 'system' };
92
+ const type = String(body.type || '').toLowerCase();
93
+ let role = body.role || raw.role || raw.type;
94
+ if (type === 'reasoning' || type === 'function_call' || type === 'tool_call') role = 'assistant';
95
+ if (type === 'function_call_output' || type === 'tool_result') role = 'tool';
96
+ const category = categoryForRole(role);
97
+ let parts = [];
98
+ const paths = [];
99
+ if (category) {
100
+ const content = body.content ?? body.text ?? body.message ?? body.output ?? body.summary ?? body.thinking ?? body.reasoning_content;
101
+ parts = contentParts(content, category);
102
+ const toolResults = body.tool_results;
103
+ if (toolResults) {
104
+ for (const result of Array.isArray(toolResults) ? toolResults : Object.values(toolResults)) {
105
+ parts.push(...contentParts(result, 'tools'));
106
+ }
107
+ }
108
+ for (const key of ['thoughts', 'reasoning_content', 'reasoning_details']) {
109
+ if (body[key] !== undefined && body[key] !== content) parts.push(...contentParts(body[key], 'assistant'));
110
+ }
111
+ if (type === 'function_call' || type === 'tool_call') {
112
+ parts = [{ category: 'assistant', text: `${body.name || body.tool || ''}\n${typeof body.arguments === 'string' ? body.arguments : JSON.stringify(body.arguments || body.input || {})}` }];
113
+ calls.set(body.call_id || body.id, readPaths(body.name || body.tool, body.arguments || body.input, cwd));
114
+ }
115
+ if (type === 'function_call_output' || String(role).toLowerCase() === 'toolresult') {
116
+ paths.push(...(calls.get(body.call_id || body.toolCallId || body.tool_use_id) || []));
117
+ }
118
+ for (const part of Array.isArray(body.content) ? body.content : []) {
119
+ if (!part) continue;
120
+ if (/^(toolcall|tool_use)$/i.test(part.type || '')) {
121
+ calls.set(part.id, readPaths(part.name, part.arguments || part.input, cwd));
122
+ }
123
+ if (part.type === 'tool_result') paths.push(...(calls.get(part.tool_use_id) || []));
124
+ if (/tool/i.test(part.type || '') && (part.state?.output !== undefined || part.state?.error !== undefined || part.type === 'tool_result')) {
125
+ paths.push(...readPaths(part.tool || part.name, part.state?.input || part.input, cwd));
126
+ }
127
+ }
128
+ if (category === 'tools') paths.push(...readPaths(body.name || body.tool, body.input || body.arguments, cwd));
129
+ }
130
+ if (raw.type === 'session_meta' || raw.type === 'system_context') {
131
+ const metadata = raw.payload || raw;
132
+ parts = RULE_FIELDS.flatMap((key) => contentParts(metadata[key], 'system'));
133
+ role = 'system';
134
+ }
135
+ if (parts.length) nodes.push({ id: `record-${recordIndex}${current.suffix}`, role,
136
+ recordLineIndex: recordIndex, messageIndex: recordIndex, parts, readPaths: paths });
137
+ const containers = body === raw ? [{ value: raw, prefix: '' }]
138
+ : [{ value: body, prefix: 'body-' }, { value: raw, prefix: '' }];
139
+ const groups = containers.flatMap((container) => ['children', 'messages', 'branches'].map((field) => ({
140
+ children: container.value[field], field: `${container.prefix}${field}`
141
+ })));
142
+ for (const group of groups) {
143
+ if (!Array.isArray(group.children)) continue;
144
+ for (let index = group.children.length - 1; index >= 0; index--) {
145
+ stack.push({ record: group.children[index], suffix: `${current.suffix}.${group.field}-${index}` });
146
+ }
147
+ }
148
+ }
149
+ return nodes;
150
+ };
151
+ }
152
+
153
+ module.exports = { createContextRecordReader, contentParts };