tokless 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,497 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const { estimateTokens } = require('./analyzer');
7
+
8
+ const ALWAYS_ON_LINE_LIMIT = 100;
9
+ const SKILL_LINE_LIMIT = 120;
10
+ const ALWAYS_ON_BYTE_ADVISORY = 4000;
11
+ const SKILL_BYTE_ADVISORY = 8000;
12
+
13
+ // Baseline per-step schema token estimates
14
+ const DEFAULT_BUILTIN_TOOLS_EST_TOKENS = 4200;
15
+ const DEFAULT_SUBAGENT_READONLY_EST_TOKENS = 900;
16
+ const HEAVY_MCP_EST_TOKENS = 3000;
17
+ const STANDARD_MCP_EST_TOKENS = 1500;
18
+ const HEAVY_MCP_NAME_RE = /chrome|devtools|playwright|puppeteer|browser|github|gitlab|atlassian|jira|confluence|linear|figma|notion|supabase|postgres|mysql|sqlite|databricks|looker/i;
19
+
20
+ const KNOWN_TOOL_EST_TOKENS = {
21
+ read_file: 220,
22
+ view_file: 220,
23
+ write_file: 260,
24
+ edit_file: 280,
25
+ run_command: 320,
26
+ manage_task: 220,
27
+ search_web: 160,
28
+ ask_question: 220,
29
+ swarm: 580,
30
+ run_workflow: 360
31
+ };
32
+
33
+ function stripJsonCommentsAndTrailingCommas(raw) {
34
+ if (!raw || typeof raw !== 'string') return '';
35
+ let out = '';
36
+ let inStr = false;
37
+ let quote = '';
38
+ let i = 0;
39
+ while (i < raw.length) {
40
+ const ch = raw[i];
41
+ const next = raw[i + 1];
42
+ if (inStr) {
43
+ out += ch;
44
+ if (ch === '\\' && i + 1 < raw.length) {
45
+ out += raw[++i];
46
+ } else if (ch === quote) {
47
+ inStr = false;
48
+ }
49
+ i++;
50
+ continue;
51
+ }
52
+ if (ch === '"' || ch === "'") {
53
+ inStr = true;
54
+ quote = ch;
55
+ out += ch;
56
+ i++;
57
+ continue;
58
+ }
59
+ if (ch === '/' && next === '/') {
60
+ i += 2;
61
+ while (i < raw.length && raw[i] !== '\n') i++;
62
+ continue;
63
+ }
64
+ if (ch === '/' && next === '*') {
65
+ i += 2;
66
+ while (i < raw.length && !(raw[i] === '*' && raw[i + 1] === '/')) i++;
67
+ i += 2;
68
+ continue;
69
+ }
70
+ out += ch;
71
+ i++;
72
+ }
73
+ return out.replace(/,\s*([}\]])/g, '$1');
74
+ }
75
+
76
+ function readJsonSafe(filePath) {
77
+ try {
78
+ if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) return null;
79
+ const raw = fs.readFileSync(filePath, 'utf8');
80
+ return JSON.parse(stripJsonCommentsAndTrailingCommas(raw));
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+
86
+ function parseAgentMarkdown(filePath) {
87
+ const raw = fs.readFileSync(filePath, 'utf8');
88
+ const norm = raw.replace(/\r\n/g, '\n');
89
+ let frontmatterText = '';
90
+ let bodyText = norm;
91
+
92
+ const fmMatch = norm.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
93
+ if (fmMatch) {
94
+ frontmatterText = fmMatch[1];
95
+ bodyText = fmMatch[2];
96
+ }
97
+
98
+ const fm = {};
99
+ if (frontmatterText) {
100
+ const lines = frontmatterText.split('\n');
101
+ let currentListKey = null;
102
+ for (const line of lines) {
103
+ const listItemMatch = line.match(/^\s*-\s+(.+?)\s*$/);
104
+ if (listItemMatch && currentListKey) {
105
+ if (!Array.isArray(fm[currentListKey])) fm[currentListKey] = [];
106
+ fm[currentListKey].push(listItemMatch[1].replace(/^['"]|['"]$/g, '').trim());
107
+ continue;
108
+ }
109
+ const kvMatch = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
110
+ if (!kvMatch) continue;
111
+ const key = kvMatch[1];
112
+ const valRaw = kvMatch[2].trim();
113
+ currentListKey = null;
114
+
115
+ if (valRaw === '') {
116
+ currentListKey = key;
117
+ fm[key] = [];
118
+ } else if (valRaw.startsWith('[') && valRaw.endsWith(']')) {
119
+ const inner = valRaw.slice(1, -1).trim();
120
+ fm[key] = inner
121
+ ? inner.split(',').map(s => s.replace(/^['"]|['"]$/g, '').trim()).filter(Boolean)
122
+ : [];
123
+ } else if (valRaw === 'true') {
124
+ fm[key] = true;
125
+ } else if (valRaw === 'false') {
126
+ fm[key] = false;
127
+ } else {
128
+ fm[key] = valRaw.replace(/^['"]|['"]$/g, '');
129
+ }
130
+ }
131
+ }
132
+
133
+ return { frontmatter: fm, bodyText };
134
+ }
135
+
136
+ function estimateToolsSchemaTokens(toolsField, isMainAgent) {
137
+ if (Array.isArray(toolsField)) {
138
+ if (toolsField.length === 0) return 0;
139
+ return toolsField.reduce((sum, name) => sum + (KNOWN_TOOL_EST_TOKENS[name] || 240), 0);
140
+ }
141
+ return isMainAgent ? DEFAULT_BUILTIN_TOOLS_EST_TOKENS : DEFAULT_SUBAGENT_READONLY_EST_TOKENS;
142
+ }
143
+
144
+ function collectMcpServersFromFile(filePath, scope, displaySource, outList) {
145
+ const parsed = readJsonSafe(filePath);
146
+ if (!parsed || typeof parsed !== 'object') return;
147
+ const serversMap = parsed.mcpServers && typeof parsed.mcpServers === 'object'
148
+ ? parsed.mcpServers
149
+ : null;
150
+ if (!serversMap) return;
151
+
152
+ for (const [serverName, cfg] of Object.entries(serversMap)) {
153
+ if (!cfg || typeof cfg !== 'object') continue;
154
+ const enabled = cfg.disabled !== true;
155
+ const transport = cfg.url || cfg.serverUrl ? 'http' : 'stdio';
156
+ const isHeavy = HEAVY_MCP_NAME_RE.test(serverName) ||
157
+ (typeof cfg.command === 'string' && HEAVY_MCP_NAME_RE.test(cfg.command)) ||
158
+ (Array.isArray(cfg.args) && cfg.args.some(a => HEAVY_MCP_NAME_RE.test(String(a))));
159
+ const tier = isHeavy ? 'heavy' : 'standard';
160
+ const estTokensPerStep = enabled ? (isHeavy ? HEAVY_MCP_EST_TOKENS : STANDARD_MCP_EST_TOKENS) : 0;
161
+
162
+ outList.push({
163
+ name: serverName,
164
+ scope,
165
+ source: displaySource,
166
+ transport,
167
+ enabled,
168
+ tier,
169
+ estTokensPerStep
170
+ });
171
+ }
172
+ }
173
+
174
+ function auditMcpAndTools(rootDir, options = {}) {
175
+ const homeDir = options.homeDir ? path.resolve(options.homeDir) : os.homedir();
176
+ const mcpServers = [];
177
+
178
+ // 1. Global ~/.gemini/config/mcp_config.json
179
+ const globalMcpPath = path.join(homeDir, '.gemini', 'config', 'mcp_config.json');
180
+ collectMcpServersFromFile(
181
+ globalMcpPath,
182
+ 'global',
183
+ '~/.gemini/config/mcp_config.json',
184
+ mcpServers
185
+ );
186
+
187
+ // 2. Global enabled plugins ~/.gemini/config/plugins/*/mcp_config.json
188
+ const globalConfig = readJsonSafe(path.join(homeDir, '.gemini', 'config', 'config.json')) || {};
189
+ const pluginStateMap = (globalConfig.plugins && typeof globalConfig.plugins === 'object')
190
+ ? globalConfig.plugins
191
+ : {};
192
+ const pluginsDir = path.join(homeDir, '.gemini', 'config', 'plugins');
193
+ if (fs.existsSync(pluginsDir) && fs.statSync(pluginsDir).isDirectory()) {
194
+ for (const entry of fs.readdirSync(pluginsDir, { withFileTypes: true })) {
195
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
196
+ const pDir = path.join(pluginsDir, entry.name);
197
+ const manifest = readJsonSafe(path.join(pDir, 'plugin.json'));
198
+ const userOverride = pluginStateMap[entry.name];
199
+ const isEnabled = userOverride && typeof userOverride.enabled === 'boolean'
200
+ ? userOverride.enabled
201
+ : !(manifest && manifest.disabled === true);
202
+ if (!isEnabled) continue;
203
+
204
+ collectMcpServersFromFile(
205
+ path.join(pDir, 'mcp_config.json'),
206
+ 'plugin',
207
+ `~/.gemini/config/plugins/${entry.name}/mcp_config.json`,
208
+ mcpServers
209
+ );
210
+ }
211
+ }
212
+
213
+ // 3. Workspace MCP configs (.mcp.json, .agents/mcp_config.json, .agent/mcp_config.json, plugin root mcp_config.json)
214
+ const workspaceMcpCandidates = [
215
+ { p: path.join(rootDir, '.mcp.json'), label: '.mcp.json' },
216
+ { p: path.join(rootDir, '.agents', 'mcp_config.json'), label: '.agents/mcp_config.json' },
217
+ { p: path.join(rootDir, '.agent', 'mcp_config.json'), label: '.agent/mcp_config.json' }
218
+ ];
219
+ if (fs.existsSync(path.join(rootDir, 'plugin.json'))) {
220
+ workspaceMcpCandidates.push({ p: path.join(rootDir, 'mcp_config.json'), label: 'mcp_config.json' });
221
+ }
222
+ for (const item of workspaceMcpCandidates) {
223
+ collectMcpServersFromFile(item.p, 'workspace', item.label, mcpServers);
224
+ }
225
+
226
+ const enabledMcpServers = mcpServers.filter(s => s.enabled);
227
+ const activeMcpEstTokensPerStep = enabledMcpServers.reduce((sum, s) => sum + s.estTokensPerStep, 0);
228
+ const defaultToolAndMcpPerStep = DEFAULT_BUILTIN_TOOLS_EST_TOKENS + activeMcpEstTokensPerStep;
229
+ const est30StepSnowballTokens = defaultToolAndMcpPerStep * 30;
230
+
231
+ // 4. Scan project agent definitions (.agents/agents/*.md, .agent/agents/*.md, and plugin agents/*.md)
232
+ const agentDirs = [
233
+ path.join(rootDir, '.agents', 'agents'),
234
+ path.join(rootDir, '.agent', 'agents')
235
+ ];
236
+ if (fs.existsSync(path.join(rootDir, 'plugin.json'))) {
237
+ agentDirs.push(path.join(rootDir, 'agents'));
238
+ }
239
+
240
+ const agents = [];
241
+ const seenAgentPaths = new Set();
242
+ for (const aDir of agentDirs) {
243
+ if (!fs.existsSync(aDir) || !fs.statSync(aDir).isDirectory()) continue;
244
+ for (const entry of fs.readdirSync(aDir, { withFileTypes: true })) {
245
+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.md')) continue;
246
+ const fullPath = path.resolve(aDir, entry.name);
247
+ if (seenAgentPaths.has(fullPath)) continue;
248
+ seenAgentPaths.add(fullPath);
249
+
250
+ const { frontmatter, bodyText } = parseAgentMarkdown(fullPath);
251
+ const relPath = path.relative(rootDir, fullPath).replace(/\\/g, '/');
252
+ const agentName = frontmatter.name || path.basename(entry.name, '.md');
253
+ const inheritMcp = frontmatter.inheritMcp === false ? false : true;
254
+ const isMainAgent = frontmatter.mainAgent !== false;
255
+ const hasExplicitTools = Array.isArray(frontmatter.tools);
256
+ const toolsList = hasExplicitTools ? frontmatter.tools : null;
257
+ const toolCount = hasExplicitTools ? toolsList.length : null;
258
+ const toolsEstTokens = estimateToolsSchemaTokens(toolsList, isMainAgent);
259
+ const mcpEstTokens = inheritMcp ? activeMcpEstTokensPerStep : 0;
260
+ const promptEstTokens = estimateTokens(bodyText.trim().length);
261
+ const toolAndMcpPerStep = toolsEstTokens + mcpEstTokens;
262
+ const savedPerStepTokens = Math.max(0, defaultToolAndMcpPerStep - toolAndMcpPerStep);
263
+
264
+ agents.push({
265
+ name: agentName,
266
+ relativePath: relPath,
267
+ inheritMcp,
268
+ mainAgent: Boolean(frontmatter.mainAgent),
269
+ subagent: frontmatter.subagent !== false,
270
+ hasExplicitTools,
271
+ tools: toolsList,
272
+ toolCount,
273
+ toolsEstTokens,
274
+ mcpEstTokens,
275
+ promptEstTokens,
276
+ toolAndMcpPerStep,
277
+ totalPerStepEstTokens: toolAndMcpPerStep + promptEstTokens,
278
+ savedPerStepTokens
279
+ });
280
+ }
281
+ }
282
+
283
+ const slimAgents = agents.filter(a => !a.inheritMcp);
284
+ const mcpInheritingAgents = agents.filter(a => a.inheritMcp);
285
+ const suggestions = [];
286
+
287
+ if (enabledMcpServers.length > 0 && slimAgents.length === 0) {
288
+ suggestions.push(
289
+ `检测到 ${enabledMcpServers.length} 个已启用 MCP Server(每步额外注入约 ${activeMcpEstTokensPerStep.toLocaleString('en-US')} Token,30 步滚雪球约 ${(activeMcpEstTokensPerStep * 30).toLocaleString('en-US')} Token),且当前项目尚未配置净身角色。建议在 .agents/agents/ 下定义 inheritMcp: false 与最小 tools 清单的专属角色(或直接运行 agy --agent tokless-coder / tokless-reviewer)卸除无关 MCP 底座税。`
290
+ );
291
+ } else if (agents.length === 0) {
292
+ suggestions.push(
293
+ `默认全量内置工具底座每步约占 ${DEFAULT_BUILTIN_TOOLS_EST_TOKENS.toLocaleString('en-US')} Token(30 步累计约 ${(DEFAULT_BUILTIN_TOOLS_EST_TOKENS * 30).toLocaleString('en-US')} Cache Read)。高频纯代码子代理建议挂载 inheritMcp: false + tools: [read_file, write_file, edit_file, run_command](省 ~70% 工具底座),纯文本润色/摘要子代理建议设 tools: [](0 工具底座税)。`
294
+ );
295
+ }
296
+
297
+ if (enabledMcpServers.length > 0 && mcpInheritingAgents.length > 0) {
298
+ const names = mcpInheritingAgents.map(a => a.name).join(', ');
299
+ suggestions.push(
300
+ `角色 [${names}] 当前开启或默认继承了 MCP (inheritMcp: true),每步多付约 ${activeMcpEstTokensPerStep.toLocaleString('en-US')} Token;若该角色无需调用浏览器或外部 MCP 工具,建议显式加上 inheritMcp: false。`
301
+ );
302
+ }
303
+
304
+ return {
305
+ builtinDefaultToolsEstTokensPerStep: DEFAULT_BUILTIN_TOOLS_EST_TOKENS,
306
+ totalMcpCount: mcpServers.length,
307
+ enabledMcpCount: enabledMcpServers.length,
308
+ activeMcpEstTokensPerStep,
309
+ defaultSessionEstTokensPerStep: defaultToolAndMcpPerStep,
310
+ est30StepSnowballTokens,
311
+ mcpServers,
312
+ agents,
313
+ suggestions
314
+ };
315
+ }
316
+
317
+ function findFileCaseInsensitive(dir, targetName) {
318
+ if (!fs.existsSync(dir)) return null;
319
+ const exact = path.join(dir, targetName);
320
+ if (fs.existsSync(exact) && fs.statSync(exact).isFile()) {
321
+ return exact;
322
+ }
323
+ const lower = targetName.toLowerCase();
324
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
325
+ const match = entries.find(e => e.isFile() && e.name.toLowerCase() === lower);
326
+ return match ? path.join(dir, match.name) : null;
327
+ }
328
+
329
+ function inspectDocFile(filePath, rootDir, category, loadMode) {
330
+ const content = fs.readFileSync(filePath, 'utf8');
331
+ const lines = content.length === 0 ? 0 : content.split(/\r?\n/).length;
332
+ const chars = content.length;
333
+ const bytes = Buffer.byteLength(content, 'utf8');
334
+ const estTokens = estimateTokens(chars);
335
+ const relPath = path.relative(rootDir, filePath).replace(/\\/g, '/');
336
+
337
+ const isAlwaysOn = loadMode === 'Always-On';
338
+ const lineLimit = isAlwaysOn ? ALWAYS_ON_LINE_LIMIT : SKILL_LINE_LIMIT;
339
+ const byteAdvisory = isAlwaysOn ? ALWAYS_ON_BYTE_ADVISORY : SKILL_BYTE_ADVISORY;
340
+
341
+ const exceedsLineLimit = lines > lineLimit;
342
+ const highDensity = bytes > byteAdvisory;
343
+
344
+ const suggestions = [];
345
+ if (exceedsLineLimit) {
346
+ if (isAlwaysOn) {
347
+ suggestions.push(
348
+ `行数超标 (${lines} 行 > ${lineLimit} 行上限):将命令模板、操作步骤与长示例下沉到 .agents/skills/*/SKILL.md(改为按需加载),常驻规则仅保留硬性边界与目录分工,压至 80 行以内。`
349
+ );
350
+ } else {
351
+ suggestions.push(
352
+ `行数超标 (${lines} 行 > ${lineLimit} 行上限):将长篇参考表、模板代码拆分到同级 references/ 或 scripts/ 目录,SKILL.md 主体只保留触发条件与核心步骤(控制在 100 行以内)。`
353
+ );
354
+ }
355
+ }
356
+ if (highDensity) {
357
+ if (isAlwaysOn) {
358
+ suggestions.push(
359
+ `高密度体积偏大 (${bytes} 字节 / 约 ${estTokens} Token,每轮对话必扣):建议删减长段落背景描述与内联示例,精简为短句清单,将常驻成本压到 2,000 字节 (~600 Token) 以内。`
360
+ );
361
+ } else {
362
+ suggestions.push(
363
+ `单次触发体积偏大 (${bytes} 字节 / 约 ${estTokens} Token):建议精简冗长散文描述,将大段规范/示例外置到 references/*.md 按需读取。`
364
+ );
365
+ }
366
+ }
367
+
368
+ let status = 'OK';
369
+ if (exceedsLineLimit) {
370
+ status = 'BLOAT';
371
+ } else if (highDensity) {
372
+ status = 'DENSE';
373
+ }
374
+
375
+ return {
376
+ relativePath: relPath,
377
+ absolutePath: filePath,
378
+ category,
379
+ loadMode,
380
+ lineLimit,
381
+ lines,
382
+ chars,
383
+ bytes,
384
+ estTokens,
385
+ exceedsLineLimit,
386
+ highDensity,
387
+ status,
388
+ suggestions
389
+ };
390
+ }
391
+
392
+ function auditProject(dirPath, options = {}) {
393
+ if (!dirPath) {
394
+ throw new Error('Project directory path is required.');
395
+ }
396
+ const rootDir = path.resolve(dirPath);
397
+ if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
398
+ throw new Error(`Project directory not found: ${rootDir}`);
399
+ }
400
+
401
+ const files = [];
402
+ const seenDocPaths = new Set();
403
+ const pushDoc = (filePath, category, loadMode) => {
404
+ const resolved = path.resolve(filePath);
405
+ if (seenDocPaths.has(resolved)) return;
406
+ seenDocPaths.add(resolved);
407
+ files.push(inspectDocFile(resolved, rootDir, category, loadMode));
408
+ };
409
+
410
+ // 1. Root AGENTS.md & GEMINI.md (Always-On)
411
+ const agentsPath = findFileCaseInsensitive(rootDir, 'AGENTS.md');
412
+ if (agentsPath) {
413
+ pushDoc(agentsPath, 'AGENTS.md', 'Always-On');
414
+ }
415
+
416
+ const geminiPath = findFileCaseInsensitive(rootDir, 'GEMINI.md');
417
+ if (geminiPath) {
418
+ pushDoc(geminiPath, 'GEMINI.md', 'Always-On');
419
+ }
420
+
421
+ // 2. .agents/rules/*.md (and plugin rules/*.md if plugin.json exists)
422
+ const rulesDirs = [path.join(rootDir, '.agents', 'rules')];
423
+ if (fs.existsSync(path.join(rootDir, 'plugin.json'))) {
424
+ rulesDirs.push(path.join(rootDir, 'rules'));
425
+ }
426
+ for (const rulesDir of rulesDirs) {
427
+ if (fs.existsSync(rulesDir) && fs.statSync(rulesDir).isDirectory()) {
428
+ for (const entry of fs.readdirSync(rulesDir, { withFileTypes: true })) {
429
+ if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) {
430
+ pushDoc(path.join(rulesDir, entry.name), 'rule', 'Always-On');
431
+ }
432
+ }
433
+ }
434
+ }
435
+
436
+ // 3. .agents/skills/*/SKILL.md (and plugin skills/*/SKILL.md if plugin.json exists)
437
+ const skillsDirs = [path.join(rootDir, '.agents', 'skills')];
438
+ if (fs.existsSync(path.join(rootDir, 'plugin.json'))) {
439
+ skillsDirs.push(path.join(rootDir, 'skills'));
440
+ }
441
+ for (const skillsDir of skillsDirs) {
442
+ if (fs.existsSync(skillsDir) && fs.statSync(skillsDir).isDirectory()) {
443
+ for (const entry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
444
+ if (entry.isDirectory()) {
445
+ const skillFile = findFileCaseInsensitive(path.join(skillsDir, entry.name), 'SKILL.md');
446
+ if (skillFile) {
447
+ pushDoc(skillFile, 'skill', 'Progressive Disclosure');
448
+ }
449
+ }
450
+ }
451
+ }
452
+ }
453
+
454
+ const alwaysOnFiles = files.filter(f => f.loadMode === 'Always-On');
455
+ const skillFiles = files.filter(f => f.loadMode === 'Progressive Disclosure');
456
+
457
+ const sum = arr => ({
458
+ count: arr.length,
459
+ lines: arr.reduce((s, f) => s + f.lines, 0),
460
+ chars: arr.reduce((s, f) => s + f.chars, 0),
461
+ bytes: arr.reduce((s, f) => s + f.bytes, 0),
462
+ estTokens: arr.reduce((s, f) => s + f.estTokens, 0)
463
+ });
464
+
465
+ const flaggedFiles = files.filter(f => f.exceedsLineLimit || f.highDensity);
466
+ const mcpAndToolTax = auditMcpAndTools(rootDir, options);
467
+
468
+ return {
469
+ projectDir: rootDir,
470
+ projectName: path.basename(rootDir),
471
+ thresholds: {
472
+ alwaysOnLineLimit: ALWAYS_ON_LINE_LIMIT,
473
+ skillLineLimit: SKILL_LINE_LIMIT,
474
+ alwaysOnByteAdvisory: ALWAYS_ON_BYTE_ADVISORY,
475
+ skillByteAdvisory: SKILL_BYTE_ADVISORY
476
+ },
477
+ summary: {
478
+ totalFiles: files.length,
479
+ alwaysOn: sum(alwaysOnFiles),
480
+ progressiveDisclosure: sum(skillFiles),
481
+ lineViolations: files.filter(f => f.exceedsLineLimit).length,
482
+ densityWarnings: files.filter(f => !f.exceedsLineLimit && f.highDensity).length,
483
+ enabledMcpCount: mcpAndToolTax.enabledMcpCount,
484
+ defaultToolAndMcpPerStepTokens: mcpAndToolTax.defaultSessionEstTokensPerStep,
485
+ agentRoleCount: mcpAndToolTax.agents.length
486
+ },
487
+ files,
488
+ flaggedFiles,
489
+ mcpAndToolTax
490
+ };
491
+ }
492
+
493
+ module.exports = {
494
+ auditProject,
495
+ auditMcpAndTools,
496
+ parseAgentMarkdown
497
+ };
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const {
7
+ generateFileSkeleton,
8
+ scanDirectorySkeleton,
9
+ formatDirectorySkeleton,
10
+ } = require('./lib/skeleton');
11
+
12
+ function printUsage() {
13
+ console.log(`repo-skeleton - 极速提取代码文件或目录的紧凑语法骨架与精确行号范围
14
+
15
+ 用法:
16
+ node cli.js <文件路径> [--json]
17
+ node cli.js <目录路径> [--depth <深度, 默认 2>] [--json]
18
+
19
+ 选项:
20
+ --depth <N> 目录扫描最大深度(默认: 2,自动排除 node_modules/.git/dist/build/exports/.next/target/__pycache__)
21
+ --json 输出结构化 JSON
22
+ -h, --help 显示帮助信息`);
23
+ }
24
+
25
+ function parseArgs(argv) {
26
+ const args = argv.slice(2);
27
+ let target = null;
28
+ let depth = 2;
29
+ let json = false;
30
+ let help = false;
31
+
32
+ for (let i = 0; i < args.length; i++) {
33
+ const arg = args[i];
34
+ if (arg === '-h' || arg === '--help') {
35
+ help = true;
36
+ } else if (arg === '--json') {
37
+ json = true;
38
+ } else if (arg === '--depth') {
39
+ const next = args[i + 1];
40
+ if (next !== undefined && /^\d+$/.test(next)) {
41
+ depth = parseInt(next, 10);
42
+ i++;
43
+ }
44
+ } else if (arg.startsWith('--depth=')) {
45
+ const val = arg.slice('--depth='.length);
46
+ if (/^\d+$/.test(val)) {
47
+ depth = parseInt(val, 10);
48
+ }
49
+ } else if (!arg.startsWith('-') && !target) {
50
+ target = arg;
51
+ }
52
+ }
53
+
54
+ return { target, depth, json, help };
55
+ }
56
+
57
+ function main() {
58
+ const { target, depth, json, help } = parseArgs(process.argv);
59
+
60
+ if (help || !target) {
61
+ printUsage();
62
+ process.exit(help ? 0 : 1);
63
+ }
64
+
65
+ const resolved = path.resolve(target);
66
+ if (!fs.existsSync(resolved)) {
67
+ console.error(`错误: 目标路径不存在: ${resolved}`);
68
+ process.exit(1);
69
+ }
70
+
71
+ const stat = fs.statSync(resolved);
72
+ const t0 = performance.now();
73
+
74
+ if (stat.isFile()) {
75
+ const result = generateFileSkeleton(resolved, { includeHeader: false });
76
+ const elapsedMs = Number((performance.now() - t0).toFixed(2));
77
+
78
+ if (json) {
79
+ console.log(JSON.stringify({ mode: 'file', elapsedMs, ...result }, null, 2));
80
+ return;
81
+ }
82
+
83
+ console.log(`文件: ${result.filePath}`);
84
+ console.log(
85
+ `统计: 总行数 ${result.totalLines} 行 | 全文估算 ${result.rawTokens} tokens → 骨架估算 ${result.skeletonTokens} tokens (节省 ${result.savedPercent}%, 耗时 ${elapsedMs}ms)`
86
+ );
87
+ console.log('---');
88
+ console.log(result.formatted);
89
+ return;
90
+ }
91
+
92
+ if (stat.isDirectory()) {
93
+ const result = scanDirectorySkeleton(resolved, { depth });
94
+ const elapsedMs = Number((performance.now() - t0).toFixed(2));
95
+
96
+ if (json) {
97
+ console.log(JSON.stringify({ mode: 'directory', elapsedMs, ...result }, null, 2));
98
+ return;
99
+ }
100
+
101
+ console.log(formatDirectorySkeleton(result, { elapsedMs }));
102
+ return;
103
+ }
104
+
105
+ console.error(`错误: 不支持的目标类型: ${resolved}`);
106
+ process.exit(1);
107
+ }
108
+
109
+ main();