tokless 0.0.0-stage → 0.4.1

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.
package/hooks.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "read-file-guard": {
3
+ "enabled": true,
4
+ "PreToolUse": [
5
+ {
6
+ "matcher": "read_file|view_file",
7
+ "hooks": [
8
+ {
9
+ "type": "command",
10
+ "command": "node ./scripts/read-guard-hook.js",
11
+ "timeout": 10
12
+ }
13
+ ]
14
+ }
15
+ ]
16
+ }
17
+ }
package/index.js ADDED
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+
7
+ const skeleton = require('./lib/skeleton');
8
+ const audit = require('./lib/audit');
9
+ const readGuard = require('./lib/read-guard');
10
+
11
+ const PACKAGE_ROOT = __dirname;
12
+
13
+ function detectGlobalPlugin(options = {}) {
14
+ const homeDir = options.homeDir || os.homedir();
15
+ const candidates = [
16
+ path.join(homeDir, '.gemini', 'config', 'plugins', 'tokless'),
17
+ path.join(homeDir, '.gemini', 'config', 'plugins', 'agy-tokless'),
18
+ ];
19
+
20
+ for (const pluginDir of candidates) {
21
+ const manifestPath = path.join(pluginDir, 'plugin.json');
22
+ if (fs.existsSync(manifestPath)) {
23
+ try {
24
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
25
+ const enabled = manifest.disabled !== true;
26
+ return { installed: true, enabled, pluginDir, manifestPath };
27
+ } catch (_) {
28
+ return { installed: true, enabled: true, pluginDir, manifestPath };
29
+ }
30
+ }
31
+ }
32
+
33
+ const defaultDir = candidates[1];
34
+ return {
35
+ installed: false,
36
+ enabled: false,
37
+ pluginDir: defaultDir,
38
+ manifestPath: path.join(defaultDir, 'plugin.json'),
39
+ };
40
+ }
41
+
42
+ module.exports = {
43
+ PACKAGE_ROOT,
44
+ detectGlobalPlugin,
45
+ skeleton,
46
+ audit,
47
+ readGuard,
48
+ IGNORED_DIRS: skeleton.IGNORED_DIRS,
49
+ SUPPORTED_EXTS: skeleton.SUPPORTED_EXTS,
50
+ generateFileSkeleton: skeleton.generateFileSkeleton,
51
+ scanDirectorySkeleton: skeleton.scanDirectorySkeleton,
52
+ formatSkeletonItems: skeleton.formatSkeletonItems,
53
+ formatDirectorySkeleton: skeleton.formatDirectorySkeleton,
54
+ generateSkeleton: skeleton.generateSkeleton,
55
+ estimateTokens: audit.estimateTokens,
56
+ analyzeSession: audit.analyzeSession,
57
+ compareSessions: audit.compareSessions,
58
+ auditProject: audit.auditProject,
59
+ auditMcpAndTools: audit.auditMcpAndTools,
60
+ parseAgentMarkdown: audit.parseAgentMarkdown,
61
+ formatSessionMarkdown: audit.formatSessionMarkdown,
62
+ formatCompareMarkdown: audit.formatCompareMarkdown,
63
+ formatProjectMarkdown: audit.formatProjectMarkdown,
64
+ COMPACTION_THRESHOLD_256K: audit.COMPACTION_THRESHOLD_256K,
65
+ COMPACTION_THRESHOLD_512K: audit.COMPACTION_THRESHOLD_512K,
66
+ GUARDED_CODE_EXTS: readGuard.GUARDED_CODE_EXTS,
67
+ READ_GUARD_SCRIPT_PATH: readGuard.READ_GUARD_SCRIPT_PATH,
68
+ HOOKS_CONFIG_PATH: readGuard.HOOKS_CONFIG_PATH,
69
+ PLUGIN_MANIFEST_PATH: readGuard.PLUGIN_MANIFEST_PATH,
70
+ evaluateReadGuard: readGuard.evaluateReadGuard,
71
+ checkReadGuard: readGuard.checkReadGuard,
72
+ formatHookResponse: readGuard.formatHookResponse,
73
+ buildPreToolUseHookConfig: readGuard.buildPreToolUseHookConfig,
74
+ buildClaudePreToolUseHookConfig: readGuard.buildClaudePreToolUseHookConfig,
75
+ getMaxLinesThreshold: readGuard.getMaxLinesThreshold,
76
+ };
package/install.js ADDED
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const path = require('path');
5
+ const { resolveTargets } = require('./targets');
6
+ const { shouldForceCopy, resolveHomeDir } = require('./targets/shared');
7
+
8
+ function parseCliArgs(argv) {
9
+ let target = null;
10
+ let copy = false;
11
+ let uninstall = false;
12
+ let help = false;
13
+
14
+ for (let i = 0; i < argv.length; i++) {
15
+ const arg = argv[i];
16
+ if (arg === '--help' || arg === '-h') {
17
+ help = true;
18
+ } else if (arg === '--copy') {
19
+ copy = true;
20
+ } else if (arg === '--uninstall') {
21
+ uninstall = true;
22
+ } else if (arg === '--target' || arg === '-t') {
23
+ if (i + 1 < argv.length) {
24
+ target = argv[i + 1];
25
+ i++;
26
+ }
27
+ } else if (arg.startsWith('--target=')) {
28
+ target = arg.slice('--target='.length);
29
+ }
30
+ }
31
+
32
+ return { target, copy, uninstall, help };
33
+ }
34
+
35
+ function runInstall(options = {}) {
36
+ const sourceDir = options.sourceDir || __dirname;
37
+ const homeDir = resolveHomeDir(options);
38
+ const forceCopy = shouldForceCopy(sourceDir, Boolean(options.copy));
39
+ const mode = options.mode || 'antigravity-only';
40
+ const adapters = resolveTargets(options.target, { homeDir, mode });
41
+
42
+ const results = [];
43
+ for (const adapter of adapters) {
44
+ results.push(
45
+ adapter.install({
46
+ sourceDir,
47
+ homeDir,
48
+ copy: forceCopy,
49
+ silent: options.silent,
50
+ })
51
+ );
52
+ }
53
+ return results;
54
+ }
55
+
56
+ function runUninstall(options = {}) {
57
+ const homeDir = resolveHomeDir(options);
58
+ const mode = options.mode || 'antigravity-only';
59
+ const adapters = resolveTargets(options.target, { homeDir, mode });
60
+
61
+ const results = [];
62
+ for (const adapter of adapters) {
63
+ results.push(
64
+ adapter.uninstall({
65
+ homeDir,
66
+ silent: options.silent,
67
+ })
68
+ );
69
+ }
70
+ return results;
71
+ }
72
+
73
+ function printHelp() {
74
+ console.log(`Usage: node install.js [--target agy|claude|codex|all] [--copy] [--uninstall]
75
+ (default) Install Antigravity plugin into ~/.gemini/config/plugins/agy-tokless
76
+ --target <hosts> Target host(s): agy, claude, codex, all (comma-separated supported)
77
+ --copy Copy all files instead of creating links (auto-enabled in _npx / node_modules)
78
+ --uninstall Remove installed tokless plugin/hooks for the selected target(s)`);
79
+ }
80
+
81
+ function main() {
82
+ const parsed = parseCliArgs(process.argv.slice(2));
83
+ if (parsed.help) {
84
+ printHelp();
85
+ return;
86
+ }
87
+ try {
88
+ if (parsed.uninstall) {
89
+ runUninstall({
90
+ target: parsed.target,
91
+ mode: 'antigravity-only',
92
+ });
93
+ return;
94
+ }
95
+ runInstall({
96
+ target: parsed.target,
97
+ copy: parsed.copy,
98
+ mode: 'antigravity-only',
99
+ });
100
+ } catch (err) {
101
+ console.error(`[tokless] ${err.message}`);
102
+ process.exit(1);
103
+ }
104
+ }
105
+
106
+ if (require.main === module) {
107
+ main();
108
+ }
109
+
110
+ module.exports = {
111
+ parseCliArgs,
112
+ runInstall,
113
+ runUninstall,
114
+ install: runInstall,
115
+ uninstall: runUninstall,
116
+ };
package/lib/audit.js ADDED
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ const analyzer = require('../tools/agy-audit/lib/analyzer');
4
+ const compare = require('../tools/agy-audit/lib/compare');
5
+ const project = require('../tools/agy-audit/lib/project');
6
+ const formatter = require('../tools/agy-audit/lib/formatter');
7
+ const paths = require('../tools/agy-audit/lib/paths');
8
+
9
+ module.exports = {
10
+ ...paths,
11
+ ...analyzer,
12
+ ...compare,
13
+ ...project,
14
+ ...formatter,
15
+ };
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+
3
+ module.exports = require('../scripts/read-guard-hook');
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+
3
+ module.exports = require('../tools/repo-skeleton/lib/skeleton');
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "tokless",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.1",
4
+ "description": "Token optimizer, AST codebase skeletonizer, PreToolUse blind-read guard, lightweight role templates, and cache/compaction auditor for AI coding agents.",
5
+ "license": "MIT",
6
+ "main": "./index.js",
7
+ "bin": {
8
+ "tokless": "./bin/tokless.js",
9
+ "repo-skeleton": "./tools/repo-skeleton/cli.js",
10
+ "agy-audit": "./tools/agy-audit/cli.js"
11
+ },
12
+ "exports": {
13
+ ".": "./index.js",
14
+ "./skeleton": "./lib/skeleton.js",
15
+ "./audit": "./lib/audit.js",
16
+ "./read-guard": "./lib/read-guard.js",
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "assets/",
21
+ "bin/",
22
+ "targets/",
23
+ "index.js",
24
+ "install.js",
25
+ "plugin.json",
26
+ "hooks.json",
27
+ "lib/",
28
+ "tools/",
29
+ "scripts/",
30
+ "rules/",
31
+ "skills/",
32
+ "agents/",
33
+ "README.md",
34
+ "README.en.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "install-plugin": "node ./install.js",
39
+ "uninstall-plugin": "node ./install.js --uninstall",
40
+ "audit": "node ./tools/agy-audit/cli.js",
41
+ "skeleton": "node ./tools/repo-skeleton/cli.js",
42
+ "test": "node ./tests/verify-tokless.js && node --test ./tests/cross-platform-fixes.test.js",
43
+ "prepublishOnly": "npm test"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/daoif/tokless.git"
48
+ },
49
+ "homepage": "https://github.com/daoif/tokless#readme",
50
+ "bugs": {
51
+ "url": "https://github.com/daoif/tokless/issues"
52
+ },
53
+ "keywords": [
54
+ "ai-coding",
55
+ "token-optimizer",
56
+ "code-skeleton",
57
+ "ast-skeleton",
58
+ "antigravity",
59
+ "claude-code",
60
+ "codex",
61
+ "pretooluse",
62
+ "prompt-caching",
63
+ "mcp"
64
+ ],
65
+ "engines": {
66
+ "node": ">=18.0.0"
67
+ }
68
+ }
package/plugin.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "agy-tokless",
3
+ "displayName": "AGY Tokless — Antigravity 省流护栏与账单透视套件",
4
+ "version": "0.4.1",
5
+ "description": "专为 AI 编程打造的省流护栏与账单审计插件:提供代码语法骨架提取(repo-skeleton)、大文件盲读拦截钩子(PreToolUse Hook)、轻量净身角色模板(agents)以及 Prefix Cache 断层与 MCP 底座税体检工具(agy-audit)。",
6
+ "disabled": false,
7
+ "suggestedPrompts": [
8
+ "使用 token-audit 检查最近会话的 Token 消耗黑洞、Prefix Cache 断层与当前项目的 MCP 底座空载税",
9
+ "使用 code-skeleton 提取当前项目核心源码目录的函数签名与行号骨架",
10
+ "对比优化前后两次会话的真实 Token 账单与缓存命中率差异"
11
+ ]
12
+ }
@@ -0,0 +1,20 @@
1
+ # AI 编程省流读取、净身角色与缓存保护规范 (tokless)
2
+
3
+ ## 1. 先看代码骨架,再按行号精准读取 (`tokless skeleton` / `repo-skeleton`)
4
+ - **严禁盲目全量读取大代码文件**:在未确定目标函数、类或逻辑块所在行号前,严禁不带起止行号(`StartLine`/`EndLine` 或 `offset`/`limit`)直接读取超过 200 行的源码文件,也严禁传入 `1~全文末尾` 的假切片糊弄全读。
5
+ - **两步精准定位法**:
6
+ 1. 探索陌生目录或大文件时,先用 `tokless skeleton`(兼容 `repo-skeleton`)提取语法签名与 `[L起-L止]` 行号(0 模型 Token,比盲读全文省 85%~97% 探索开销):
7
+ - 全局 CLI(推荐): `tokless skeleton <目录或文件路径> --depth 2`
8
+ - macOS / Linux: `node "$HOME/.gemini/config/plugins/agy-tokless/tools/repo-skeleton/cli.js" <目录或文件路径> --depth 2`
9
+ - Windows (PowerShell): `node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\repo-skeleton\cli.js" <目录或文件路径> --depth 2`
10
+ 2. 根据骨架中的 `[L起-L止]` 行号,调用 `read_file(Path, StartLine, EndLine)`(或 `Read(file_path, offset, limit)`)按需完整读取目标函数或逻辑块(无单次行数跨度硬限制,只要有明确目标区间即可一次读完)。
11
+
12
+ ## 2. 轻量角色净身(卸除无关 MCP 与工具底座税)
13
+ - 纯代码编写或只读代码审查会话优先启用 `inheritMcp: false` 及最小 `tools` 清单(如内置净身角色 `tokless-coder`、`tokless-reviewer`),剥离用不上的浏览器/外部 MCP Schema 每步固定底座税。
14
+
15
+ ## 3. 本地账单透视、Prefix Cache 保护与控水位减轮次 (`tokless audit` / `agy-audit`)
16
+ - **0 Token 账单与底座税体检**(支持 `session <ID>` 查缓存断层与 Top 5 膨胀步、`compare <前ID> <后ID>`、`project <项目目录>` 查规则肥胖度与 MCP 空载税):
17
+ - 全局 CLI(推荐): `tokless audit <session|compare|project> <参数>`
18
+ - macOS / Linux: `node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" <session|compare|project> <参数>`
19
+ - Windows (PowerShell): `node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" <session|compare|project> <参数>`
20
+ - **严控终端输出与保护 Prefix Cache**:`run_command` 必须主动限制长日志输出规模;对话中途保持顶部规则稳定只追加,控制上下文水位与对话轮次以降低累计 `Cache Read` 滚雪球并避免触发历史自动压缩(三代模型常见约 256K,四代模型实测跑上 440K 未触发、推测约 512K)。
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ const READ_GUARD_SCRIPT_PATH = __filename;
8
+ const HOOKS_CONFIG_PATH = path.resolve(__dirname, '../hooks.json');
9
+ const PLUGIN_MANIFEST_PATH = path.resolve(__dirname, '../plugin.json');
10
+
11
+ const GUARDED_CODE_EXTS = new Set([
12
+ '.js',
13
+ '.mjs',
14
+ '.cjs',
15
+ '.ts',
16
+ '.tsx',
17
+ '.jsx',
18
+ '.py',
19
+ '.go',
20
+ '.rs',
21
+ '.java',
22
+ '.c',
23
+ '.cpp',
24
+ '.cs',
25
+ '.vue',
26
+ '.svelte',
27
+ ]);
28
+
29
+ function loadSkeletonGenerator() {
30
+ const localLib = path.resolve(__dirname, '../tools/repo-skeleton/lib/skeleton.js');
31
+ return require(localLib).generateFileSkeleton;
32
+ }
33
+
34
+ function getMaxLinesThreshold(overrideVal) {
35
+ if (overrideVal !== undefined && overrideVal !== null) {
36
+ const parsedOverride = parseInt(String(overrideVal), 10);
37
+ if (Number.isInteger(parsedOverride) && parsedOverride > 0) {
38
+ return parsedOverride;
39
+ }
40
+ }
41
+ const raw = process.env.TOKLESS_READ_MAX_LINES || process.env.AGY_READ_MAX_LINES;
42
+ if (!raw) return 200;
43
+ const parsed = parseInt(raw, 10);
44
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 200;
45
+ }
46
+
47
+ function parseLineArg(val) {
48
+ if (val === undefined || val === null || val === '') return null;
49
+ const parsed = Number(val);
50
+ return Number.isFinite(parsed) ? Math.floor(parsed) : null;
51
+ }
52
+
53
+ function isClaudeCodePayload(payload, toolName) {
54
+ if (!payload || typeof payload !== 'object') return false;
55
+ if (toolName === 'Read') return true;
56
+ if (!payload.toolCall && (payload.hook_event_name === 'PreToolUse' || typeof payload.tool_name === 'string')) {
57
+ return toolName !== 'read_file' && toolName !== 'view_file';
58
+ }
59
+ return false;
60
+ }
61
+
62
+ function formatHookResponse(verdict, isClaude) {
63
+ if (isClaude) {
64
+ if (verdict.decision === 'deny') {
65
+ return {
66
+ hookSpecificOutput: {
67
+ hookEventName: 'PreToolUse',
68
+ permissionDecision: 'deny',
69
+ permissionDecisionReason: verdict.reason,
70
+ },
71
+ };
72
+ }
73
+ return {};
74
+ }
75
+ if (verdict.decision === 'deny') {
76
+ return { decision: 'deny', reason: verdict.reason };
77
+ }
78
+ return { decision: 'allow' };
79
+ }
80
+
81
+ function evaluateReadGuard(payloadOrJson, options = {}) {
82
+ try {
83
+ let payload = payloadOrJson;
84
+ if (typeof payloadOrJson === 'string') {
85
+ if (!payloadOrJson.trim()) {
86
+ return { decision: 'allow', host: 'antigravity' };
87
+ }
88
+ payload = JSON.parse(payloadOrJson);
89
+ }
90
+
91
+ if (!payload || typeof payload !== 'object') {
92
+ return { decision: 'allow', host: 'antigravity' };
93
+ }
94
+
95
+ const toolCall = payload.toolCall ? payload.toolCall : payload;
96
+ const toolName = toolCall && (toolCall.name || toolCall.tool_name);
97
+ const isClaude = isClaudeCodePayload(payload, toolName);
98
+ const host = isClaude ? 'claude' : 'antigravity';
99
+
100
+ if (toolName !== 'read_file' && toolName !== 'view_file' && toolName !== 'Read') {
101
+ return { decision: 'allow', host };
102
+ }
103
+
104
+ const args = (toolCall && (toolCall.args || toolCall.tool_input)) || {};
105
+ const targetPath = args.Path ?? args.path ?? args.file_path ?? args.AbsolutePath;
106
+
107
+ if (typeof targetPath !== 'string' || !targetPath.trim()) {
108
+ return { decision: 'allow', host };
109
+ }
110
+
111
+ const baseCwd = options.cwd || payload.cwd;
112
+ const resolvedPath = baseCwd
113
+ ? path.resolve(baseCwd, targetPath)
114
+ : path.resolve(targetPath);
115
+ const ext = path.extname(resolvedPath).toLowerCase();
116
+ if (!GUARDED_CODE_EXTS.has(ext)) {
117
+ return { decision: 'allow', host };
118
+ }
119
+
120
+ if (!fs.existsSync(resolvedPath)) {
121
+ return { decision: 'allow', host };
122
+ }
123
+ const stat = fs.statSync(resolvedPath);
124
+ if (!stat.isFile()) {
125
+ return { decision: 'allow', host };
126
+ }
127
+
128
+ let startNum = parseLineArg(args.StartLine ?? args.startLine ?? args.start_line);
129
+ let endNum = parseLineArg(args.EndLine ?? args.endLine ?? args.end_line);
130
+ const offsetNum = parseLineArg(args.offset ?? args.Offset);
131
+ const limitNum = parseLineArg(args.limit ?? args.Limit);
132
+
133
+ if (startNum === null && offsetNum !== null) {
134
+ startNum = Math.max(1, offsetNum);
135
+ }
136
+ if (endNum === null && limitNum !== null && limitNum > 0) {
137
+ const baseStart = startNum !== null ? Math.max(1, startNum) : 1;
138
+ endNum = baseStart + limitNum - 1;
139
+ }
140
+
141
+ const hasStart = startNum !== null;
142
+ const hasEnd = endNum !== null;
143
+ const maxLines = getMaxLinesThreshold(options.maxLines);
144
+
145
+ // 陷阱: 严禁设 300 行死跨度硬拦截(会导致报错重试+拆轮倒贴数十万 Cache Read);正常局部行号切片直接放行,仅核查盲读与 1~EOF 假切片
146
+ if (hasStart && startNum > 2) {
147
+ return { decision: 'allow', host };
148
+ }
149
+
150
+ const generateFileSkeleton = loadSkeletonGenerator();
151
+ const skeleton = generateFileSkeleton(resolvedPath, { includeHeader: false });
152
+
153
+ if (skeleton.totalLines <= maxLines) {
154
+ return { decision: 'allow', host };
155
+ }
156
+
157
+ const rangeHint = isClaude
158
+ ? '重新调用 Read 并传入目标区间的 offset 与 limit'
159
+ : '重新调用 read_file 并传入目标区间的 StartLine 和 EndLine';
160
+
161
+ if (!hasStart && !hasEnd) {
162
+ const reason =
163
+ `[tokless 省流护栏] 目标文件共 ${skeleton.totalLines} 行(超过 ${maxLines} 行全量读取阈值),已拦截盲目全量读取以保护上下文额度。\n` +
164
+ `请根据下方该文件的语法骨架与 [L起-L止] 行号范围,${rangeHint}精准读取所需片段:\n\n` +
165
+ `${skeleton.formatted}`;
166
+
167
+ return { decision: 'deny', reason, host };
168
+ }
169
+
170
+ const effectiveStart = hasStart ? Math.max(1, startNum) : 1;
171
+ const requestedEnd = hasEnd ? endNum : skeleton.totalLines;
172
+
173
+ if (effectiveStart <= 2 && requestedEnd >= skeleton.totalLines - 2) {
174
+ const reason =
175
+ `[tokless 省流护栏] 目标文件共 ${skeleton.totalLines} 行,检测到 L${effectiveStart}-L${requestedEnd} 覆盖全文首尾的假切片全读,已拦截以保护上下文额度。\n` +
176
+ `请根据下方该文件的语法骨架与 [L起-L止] 行号范围,${rangeHint}精准读取真实需要的函数或逻辑块:\n\n` +
177
+ `${skeleton.formatted}`;
178
+
179
+ return { decision: 'deny', reason, host };
180
+ }
181
+
182
+ return { decision: 'allow', host };
183
+ } catch (_) {
184
+ return { decision: 'allow', host: 'antigravity' };
185
+ }
186
+ }
187
+
188
+ function buildPreToolUseHookConfig(options = {}) {
189
+ const scriptPath = options.scriptPath || READ_GUARD_SCRIPT_PATH;
190
+ const nodeExec = options.nodeExec || 'node';
191
+ const timeout = Number.isInteger(options.timeout) && options.timeout > 0 ? options.timeout : 10;
192
+ return {
193
+ 'read-file-guard': {
194
+ enabled: true,
195
+ PreToolUse: [
196
+ {
197
+ matcher: 'read_file|view_file',
198
+ hooks: [
199
+ {
200
+ type: 'command',
201
+ command: `${nodeExec} ${JSON.stringify(scriptPath)}`,
202
+ timeout,
203
+ },
204
+ ],
205
+ },
206
+ ],
207
+ },
208
+ };
209
+ }
210
+
211
+ function buildClaudePreToolUseHookConfig(options = {}) {
212
+ const scriptPath = options.scriptPath || READ_GUARD_SCRIPT_PATH;
213
+ const nodeExec = options.nodeExec || 'node';
214
+ const timeout = Number.isInteger(options.timeout) && options.timeout > 0 ? options.timeout : 10;
215
+ return {
216
+ PreToolUse: [
217
+ {
218
+ matcher: 'Read',
219
+ hooks: [
220
+ {
221
+ type: 'command',
222
+ command: `${nodeExec} ${JSON.stringify(scriptPath)}`,
223
+ timeout,
224
+ },
225
+ ],
226
+ },
227
+ ],
228
+ };
229
+ }
230
+
231
+ function readStdin() {
232
+ return new Promise((resolve) => {
233
+ const chunks = [];
234
+ process.stdin.on('data', (chunk) => chunks.push(chunk));
235
+ process.stdin.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
236
+ process.stdin.on('error', () => resolve(''));
237
+ });
238
+ }
239
+
240
+ async function main() {
241
+ const rawInput = await readStdin();
242
+ const verdict = evaluateReadGuard(rawInput);
243
+ const outObj = formatHookResponse(verdict, verdict.host === 'claude');
244
+ process.stdout.write(JSON.stringify(outObj) + '\n');
245
+ }
246
+
247
+ if (require.main === module) {
248
+ main();
249
+ }
250
+
251
+ module.exports = {
252
+ GUARDED_CODE_EXTS,
253
+ READ_GUARD_SCRIPT_PATH,
254
+ HOOKS_CONFIG_PATH,
255
+ PLUGIN_MANIFEST_PATH,
256
+ scriptPath: READ_GUARD_SCRIPT_PATH,
257
+ hooksConfigPath: HOOKS_CONFIG_PATH,
258
+ pluginManifestPath: PLUGIN_MANIFEST_PATH,
259
+ getMaxLinesThreshold,
260
+ parseLineArg,
261
+ formatHookResponse,
262
+ evaluateReadGuard,
263
+ checkReadGuard: evaluateReadGuard,
264
+ buildPreToolUseHookConfig,
265
+ buildClaudePreToolUseHookConfig,
266
+ };
@@ -0,0 +1,34 @@
1
+ ---
2
+ name: code-skeleton
3
+ description: 提取代码文件或目录的紧凑语法骨架(仅保留类名、函数签名、导出接口与精确 [L起-L止] 行号,剥离具体实现代码)。在探索代码库、排查 Bug 或读取超过 200 行的大文件前使用此技能快速定位行号,可减少 85%~97% 的探索期 Token 消耗。
4
+ ---
5
+
6
+ # 代码骨架极速提取指南 (code-skeleton)
7
+
8
+ 为了避免调用 `read_file` 或 `Read` 盲目全量读取几百行代码导致后续每一轮对话背负高额的 Cache Read 滚雪球成本,请先提取带 `[L起-L止]` 行号的语法骨架。
9
+
10
+ ## 使用方法
11
+
12
+ > 注:若已全局安装 `tokless` 包,可直接运行 `tokless skeleton <路径> [--depth 2]`(兼容 `repo-skeleton`)。Antigravity 仅向 Hook / MCP 进程注入 `PLUGIN_ROOT`,不会注入到常规 `run_command` 终端中,未全局安装 CLI 时请直接使用下方插件路径:
13
+
14
+ ### macOS / Linux (bash / zsh)
15
+
16
+ ```bash
17
+ # 1. 扫描源码目录(自动排除 node_modules/.git/dist/target 等,默认深度 2),一步拿到全局函数与行号地图
18
+ node "$HOME/.gemini/config/plugins/agy-tokless/tools/repo-skeleton/cli.js" <目录路径> --depth 2
19
+
20
+ # 2. 提取单个大文件的函数/类签名与起止行号
21
+ node "$HOME/.gemini/config/plugins/agy-tokless/tools/repo-skeleton/cli.js" <文件路径>
22
+ ```
23
+
24
+ ### Windows (PowerShell)
25
+
26
+ ```powershell
27
+ # 1. 扫描源码目录(自动排除 node_modules/.git/dist/target 等,默认深度 2),一步拿到全局函数与行号地图
28
+ node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\repo-skeleton\cli.js" <目录路径> --depth 2
29
+
30
+ # 2. 提取单个大文件的函数/类签名与起止行号
31
+ node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\repo-skeleton\cli.js" <文件路径>
32
+ ```
33
+
34
+ 拿到目标函数的 `[L起-L止]` 行号后,直接调用 `read_file(Path, StartLine, EndLine)`(或 Claude Code `Read(file_path, offset, limit)`)按需完整读取对应代码段(无单次行数跨度限制,严禁不带行号盲读或传 `1~EOF` 假切片)。