@grimoire-cc/router 1.1.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.
Files changed (81) hide show
  1. package/dist/args.d.ts +18 -0
  2. package/dist/args.d.ts.map +1 -0
  3. package/dist/args.js +45 -0
  4. package/dist/args.js.map +1 -0
  5. package/dist/bin.d.ts +3 -0
  6. package/dist/bin.d.ts.map +1 -0
  7. package/dist/bin.js +4 -0
  8. package/dist/bin.js.map +1 -0
  9. package/dist/enforce.d.ts +25 -0
  10. package/dist/enforce.d.ts.map +1 -0
  11. package/dist/enforce.js +140 -0
  12. package/dist/enforce.js.map +1 -0
  13. package/dist/filtering.d.ts +20 -0
  14. package/dist/filtering.d.ts.map +1 -0
  15. package/dist/filtering.js +30 -0
  16. package/dist/filtering.js.map +1 -0
  17. package/dist/formatting.d.ts +23 -0
  18. package/dist/formatting.d.ts.map +1 -0
  19. package/dist/formatting.js +88 -0
  20. package/dist/formatting.js.map +1 -0
  21. package/dist/index.d.ts +24 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +24 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/input.d.ts +40 -0
  26. package/dist/input.d.ts.map +1 -0
  27. package/dist/input.js +88 -0
  28. package/dist/input.js.map +1 -0
  29. package/dist/logging.d.ts +27 -0
  30. package/dist/logging.d.ts.map +1 -0
  31. package/dist/logging.js +58 -0
  32. package/dist/logging.js.map +1 -0
  33. package/dist/main.d.ts +27 -0
  34. package/dist/main.d.ts.map +1 -0
  35. package/dist/main.js +247 -0
  36. package/dist/main.js.map +1 -0
  37. package/dist/manifest.d.ts +13 -0
  38. package/dist/manifest.d.ts.map +1 -0
  39. package/dist/manifest.js +127 -0
  40. package/dist/manifest.js.map +1 -0
  41. package/dist/matching.d.ts +47 -0
  42. package/dist/matching.d.ts.map +1 -0
  43. package/dist/matching.js +185 -0
  44. package/dist/matching.js.map +1 -0
  45. package/dist/normalize.d.ts +17 -0
  46. package/dist/normalize.d.ts.map +1 -0
  47. package/dist/normalize.js +33 -0
  48. package/dist/normalize.js.map +1 -0
  49. package/dist/output.d.ts +13 -0
  50. package/dist/output.d.ts.map +1 -0
  51. package/dist/output.js +19 -0
  52. package/dist/output.js.map +1 -0
  53. package/dist/scoring.d.ts +15 -0
  54. package/dist/scoring.d.ts.map +1 -0
  55. package/dist/scoring.js +106 -0
  56. package/dist/scoring.js.map +1 -0
  57. package/dist/signals.d.ts +17 -0
  58. package/dist/signals.d.ts.map +1 -0
  59. package/dist/signals.js +57 -0
  60. package/dist/signals.js.map +1 -0
  61. package/dist/skill-content.d.ts +12 -0
  62. package/dist/skill-content.d.ts.map +1 -0
  63. package/dist/skill-content.js +33 -0
  64. package/dist/skill-content.js.map +1 -0
  65. package/dist/tool-formatting.d.ts +13 -0
  66. package/dist/tool-formatting.d.ts.map +1 -0
  67. package/dist/tool-formatting.js +47 -0
  68. package/dist/tool-formatting.js.map +1 -0
  69. package/dist/tool-input.d.ts +26 -0
  70. package/dist/tool-input.d.ts.map +1 -0
  71. package/dist/tool-input.js +108 -0
  72. package/dist/tool-input.js.map +1 -0
  73. package/dist/tool-output.d.ts +13 -0
  74. package/dist/tool-output.d.ts.map +1 -0
  75. package/dist/tool-output.js +20 -0
  76. package/dist/tool-output.js.map +1 -0
  77. package/dist/types.d.ts +225 -0
  78. package/dist/types.d.ts.map +1 -0
  79. package/dist/types.js +5 -0
  80. package/dist/types.js.map +1 -0
  81. package/package.json +44 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"input.js","sourceRoot":"","sources":["../src/input.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAS1E;;;;;;;;;GASG;AACH,MAAM,UAAU,eAAe,CAAC,UAAkB;IAChD,IAAI,CAAC,UAAU,IAAI,CAAC,UAAU,CA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EAAE,CAAC,CAAC;IACjE,CAAC;IAED,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;IAED,MAAM,KAAK,GAAG,IAA+B,CAAC;IAE9C,6BAA6B;IAC7B,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,SAAS,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,IAAI,EAAE,CAAC;QAC9D,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IAED,IAAI,OAAO,KAAK,CAAC,QAAQ,CAAC,KAAK,QAAQ,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IACxD,CAAC;IAED,qCAAqC;IACrC,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC;QACvB,UAAU,EACR,OAAO,KAAK,CAAC,YAAY,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,SAAS;QAC3E,SAAS,EACP,OAAO,KAAK,CAAC,WAAW,CAAC,KAAK,QAAQ;YACpC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC;YACpB,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KAC/B,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,SAAS;IACvB,IAAI,CAAC;QACH,OAAO,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;IAClC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Logging functions
3
+ */
4
+ import type { LogEntry, LogOutcome, ExtractedSignals, SkillScoreResult } from './types.js';
5
+ interface BuildLogEntryParams {
6
+ sessionId: string;
7
+ promptRaw: string;
8
+ promptNormalized: string;
9
+ signals: ExtractedSignals;
10
+ skillsEvaluated: number;
11
+ matchedSkills: SkillScoreResult[];
12
+ threshold: number;
13
+ startTime: number;
14
+ outcome: LogOutcome;
15
+ }
16
+ /**
17
+ * Builds a structured log entry.
18
+ */
19
+ export declare function buildLogEntry(params: BuildLogEntryParams): LogEntry;
20
+ /**
21
+ * Writes a log entry to the specified file.
22
+ * Creates directory and file if they don't exist.
23
+ * Silently fails on write errors (non-blocking).
24
+ */
25
+ export declare function writeLog(entry: unknown, logPath: string): void;
26
+ export {};
27
+ //# sourceMappingURL=logging.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logging.d.ts","sourceRoot":"","sources":["../src/logging.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EACV,QAAQ,EACR,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAEjB,MAAM,YAAY,CAAC;AAIpB,UAAU,mBAAmB;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,EAAE,gBAAgB,CAAC;IAC1B,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,gBAAgB,EAAE,CAAC;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,UAAU,CAAC;CACrB;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,mBAAmB,GAAG,QAAQ,CAmCnE;AAED;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAc9D"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Logging functions
3
+ */
4
+ import { appendFileSync, mkdirSync } from 'fs';
5
+ import { dirname } from 'path';
6
+ const MAX_PROMPT_LENGTH = 500;
7
+ /**
8
+ * Builds a structured log entry.
9
+ */
10
+ export function buildLogEntry(params) {
11
+ const executionTimeMs = Date.now() - params.startTime;
12
+ // Truncate raw prompt if too long
13
+ const promptRaw = params.promptRaw.length > MAX_PROMPT_LENGTH
14
+ ? params.promptRaw.slice(0, MAX_PROMPT_LENGTH)
15
+ : params.promptRaw;
16
+ // Convert matched skills to log format
17
+ const skillsMatched = params.matchedSkills.map((result) => ({
18
+ name: result.skill.name,
19
+ path: result.skill.path,
20
+ score: result.score,
21
+ matched_signals: result.matchedSignals,
22
+ }));
23
+ return {
24
+ timestamp: new Date().toISOString(),
25
+ session_id: params.sessionId,
26
+ prompt_raw: promptRaw,
27
+ prompt_normalized: params.promptNormalized,
28
+ signals_extracted: {
29
+ words_count: params.signals.words.size,
30
+ extensions: Array.from(params.signals.extensions),
31
+ paths: params.signals.paths,
32
+ },
33
+ skills_evaluated: params.skillsEvaluated,
34
+ skills_matched: skillsMatched,
35
+ threshold: params.threshold,
36
+ execution_time_ms: executionTimeMs,
37
+ outcome: params.outcome,
38
+ };
39
+ }
40
+ /**
41
+ * Writes a log entry to the specified file.
42
+ * Creates directory and file if they don't exist.
43
+ * Silently fails on write errors (non-blocking).
44
+ */
45
+ export function writeLog(entry, logPath) {
46
+ try {
47
+ // Ensure directory exists
48
+ mkdirSync(dirname(logPath), { recursive: true });
49
+ // Append JSON line
50
+ const line = JSON.stringify(entry) + '\n';
51
+ appendFileSync(logPath, line, 'utf-8');
52
+ }
53
+ catch (error) {
54
+ // Log to stderr but don't throw - never block user
55
+ console.error(`[Skill Router Error] Failed to write log: ${error instanceof Error ? error.message : String(error)}`);
56
+ }
57
+ }
58
+ //# sourceMappingURL=logging.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logging.js","sourceRoot":"","sources":["../src/logging.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAS/B,MAAM,i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;AAED;;;;GAIG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAc,EAAE,OAAe;IACtD,IAAI,CAAC;QACH,0BAA0B;QAC1B,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAEjD,mBAAmB;QACnB,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;QAC1C,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IACzC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mDAAmD;QACnD,OAAO,CAAC,KAAK,CACX,6CAA6C,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CACtG,CAAC;IACJ,CAAC;AACH,CAAC"}
package/dist/main.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Main execution flow for the Router
3
+ */
4
+ import type { HookInput, HookOutput, PreToolUseInput, PreToolUseOutput } from './types.js';
5
+ /**
6
+ * Processes a prompt and returns hook output if skills match.
7
+ *
8
+ * @param input - Parsed hook input
9
+ * @param manifestPath - Path to the skill manifest
10
+ * @param projectDir - Optional project directory for SKILL.md content injection
11
+ * @returns HookOutput if skills matched, null otherwise
12
+ */
13
+ export declare function processPrompt(input: HookInput, manifestPath: string, projectDir?: string): HookOutput | null;
14
+ /**
15
+ * Processes a PreToolUse hook event and returns output if skills match.
16
+ *
17
+ * @param input - Parsed PreToolUse input
18
+ * @param manifestPath - Path to the skill manifest
19
+ * @param projectDir - Project directory for path stripping
20
+ * @returns PreToolUseOutput if skills matched, null otherwise
21
+ */
22
+ export declare function processToolUse(input: PreToolUseInput, manifestPath: string, projectDir: string): PreToolUseOutput | null;
23
+ /**
24
+ * Main entry point - reads from stdin, processes, writes to stdout.
25
+ */
26
+ export declare function main(): Promise<void>;
27
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAoB,SAAS,EAAE,UAAU,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAmB7G;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,SAAS,EAChB,YAAY,EAAE,MAAM,EACpB,UAAU,CAAC,EAAE,MAAM,GAClB,UAAU,GAAG,IAAI,CA6FnB;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,eAAe,EACtB,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,GACjB,gBAAgB,GAAG,IAAI,CA6FzB;AAED;;GAEG;AACH,wBAAsB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CA4E1C"}
package/dist/main.js ADDED
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Main execution flow for the Router
3
+ */
4
+ import { normalizePrompt } from './normalize.js';
5
+ import { extractSignals } from './signals.js';
6
+ import { scoreSkill } from './scoring.js';
7
+ import { filterByThreshold, sortDescendingByScore } from './filtering.js';
8
+ import { formatContext } from './formatting.js';
9
+ import { formatToolUseContext } from './tool-formatting.js';
10
+ import { loadManifest } from './manifest.js';
11
+ import { readSkillBody } from './skill-content.js';
12
+ import { parseStdinInput, readStdin } from './input.js';
13
+ import { buildLogEntry, writeLog } from './logging.js';
14
+ import { buildHookOutput } from './output.js';
15
+ import { buildPreToolUseOutput } from './tool-output.js';
16
+ import { extractToolSignals } from './tool-input.js';
17
+ import { parseArgs } from './args.js';
18
+ import { runEnforce, runSubagentStart, runSubagentStop } from './enforce.js';
19
+ const DEFAULT_PRETOOLUSE_THRESHOLD = 1.5;
20
+ /**
21
+ * Processes a prompt and returns hook output if skills match.
22
+ *
23
+ * @param input - Parsed hook input
24
+ * @param manifestPath - Path to the skill manifest
25
+ * @param projectDir - Optional project directory for SKILL.md content injection
26
+ * @returns HookOutput if skills matched, null otherwise
27
+ */
28
+ export function processPrompt(input, manifestPath, projectDir) {
29
+ const startTime = Date.now();
30
+ let logPath = '.claude/logs/grimoire-router.log';
31
+ try {
32
+ // Skip empty/whitespace prompts
33
+ if (!input.prompt.trim()) {
34
+ return null;
35
+ }
36
+ // Load manifest
37
+ const manifest = loadManifest(manifestPath);
38
+ logPath = manifest.config.log_path ?? logPath;
39
+ // Normalize prompt
40
+ const normalized = normalizePrompt(input.prompt);
41
+ if (!normalized) {
42
+ return null;
43
+ }
44
+ // Extract signals
45
+ const signals = extractSignals(normalized);
46
+ // Score all skills
47
+ const results = manifest.skills.map((skill) => scoreSkill(skill, signals, normalized, manifest.config.weights));
48
+ // Filter and sort
49
+ const matched = sortDescendingByScore(filterByThreshold(results, manifest.config.activation_threshold));
50
+ // Determine outcome
51
+ const outcome = matched.length > 0 ? 'activated' : 'no_match';
52
+ // Build and write log entry
53
+ const logEntry = buildLogEntry({
54
+ sessionId: input.session_id,
55
+ promptRaw: input.prompt,
56
+ promptNormalized: normalized,
57
+ signals,
58
+ skillsEvaluated: manifest.skills.length,
59
+ matchedSkills: matched,
60
+ threshold: manifest.config.activation_threshold,
61
+ startTime,
62
+ outcome,
63
+ });
64
+ writeLog(logEntry, logPath);
65
+ // Return output if skills matched
66
+ if (matched.length > 0) {
67
+ // Read SKILL.md content when projectDir is available
68
+ let skillContents;
69
+ if (projectDir) {
70
+ skillContents = new Map();
71
+ for (const result of matched) {
72
+ const body = readSkillBody(result.skill.path, projectDir);
73
+ if (body) {
74
+ skillContents.set(result.skill.path, body);
75
+ }
76
+ }
77
+ }
78
+ const context = formatContext(matched, skillContents);
79
+ return buildHookOutput(context);
80
+ }
81
+ return null;
82
+ }
83
+ catch (error) {
84
+ // Log error but don't throw - never block user
85
+ const errorMessage = error instanceof Error ? error.message : String(error);
86
+ console.error(`[Router Error] ${errorMessage}`);
87
+ // Try to write error log
88
+ try {
89
+ writeLog({
90
+ timestamp: new Date().toISOString(),
91
+ level: 'error',
92
+ message: errorMessage,
93
+ error_type: error instanceof Error ? error.name : 'Unknown',
94
+ stack_trace: error instanceof Error ? error.stack : null,
95
+ }, logPath);
96
+ }
97
+ catch {
98
+ // Ignore logging errors
99
+ }
100
+ return null;
101
+ }
102
+ }
103
+ /**
104
+ * Processes a PreToolUse hook event and returns output if skills match.
105
+ *
106
+ * @param input - Parsed PreToolUse input
107
+ * @param manifestPath - Path to the skill manifest
108
+ * @param projectDir - Project directory for path stripping
109
+ * @returns PreToolUseOutput if skills matched, null otherwise
110
+ */
111
+ export function processToolUse(input, manifestPath, projectDir) {
112
+ const startTime = Date.now();
113
+ let logPath = '.claude/logs/grimoire-router.log';
114
+ try {
115
+ // Load manifest
116
+ const manifest = loadManifest(manifestPath);
117
+ logPath = manifest.config.log_path ?? logPath;
118
+ // Extract signals from tool input (file path)
119
+ const signals = extractToolSignals(input.tool_input, projectDir);
120
+ // Score all skills — only file_extensions and file_paths are meaningful for
121
+ // PreToolUse (keywords match path components, not user intent; patterns need
122
+ // a prompt). Empty words disables keywords; empty string disables patterns.
123
+ const fileOnlySignals = {
124
+ words: new Set(),
125
+ extensions: signals.extensions,
126
+ paths: signals.paths,
127
+ };
128
+ const results = manifest.skills.map((skill) => scoreSkill(skill, fileOnlySignals, '', manifest.config.weights));
129
+ // Filter by pretooluse_threshold
130
+ const threshold = manifest.config.pretooluse_threshold ?? DEFAULT_PRETOOLUSE_THRESHOLD;
131
+ const matched = sortDescendingByScore(filterByThreshold(results, threshold));
132
+ // Determine outcome
133
+ const outcome = matched.length > 0 ? 'activated' : 'no_match';
134
+ // Build and write log entry
135
+ const logEntry = buildLogEntry({
136
+ sessionId: input.session_id,
137
+ promptRaw: `[PreToolUse:${input.tool_name}] ${typeof input.tool_input['file_path'] === 'string' ? input.tool_input['file_path'] : ''}`,
138
+ promptNormalized: '',
139
+ signals: fileOnlySignals,
140
+ skillsEvaluated: manifest.skills.length,
141
+ matchedSkills: matched,
142
+ threshold,
143
+ startTime,
144
+ outcome,
145
+ });
146
+ writeLog({ ...logEntry, hook_event: 'PreToolUse', tool_name: input.tool_name }, logPath);
147
+ // Return output if skills matched
148
+ if (matched.length > 0) {
149
+ // Read SKILL.md content for injection (same pattern as processPrompt)
150
+ const skillContents = new Map();
151
+ for (const result of matched) {
152
+ const body = readSkillBody(result.skill.path, projectDir);
153
+ if (body) {
154
+ skillContents.set(result.skill.path, body);
155
+ }
156
+ }
157
+ const context = formatToolUseContext(matched, input.tool_name, skillContents);
158
+ return buildPreToolUseOutput(context);
159
+ }
160
+ return null;
161
+ }
162
+ catch (error) {
163
+ const errorMessage = error instanceof Error ? error.message : String(error);
164
+ console.error(`[Router Error] ${errorMessage}`);
165
+ try {
166
+ writeLog({
167
+ timestamp: new Date().toISOString(),
168
+ level: 'error',
169
+ message: errorMessage,
170
+ error_type: error instanceof Error ? error.name : 'Unknown',
171
+ stack_trace: error instanceof Error ? error.stack : null,
172
+ }, logPath);
173
+ }
174
+ catch {
175
+ // Ignore logging errors
176
+ }
177
+ return null;
178
+ }
179
+ }
180
+ /**
181
+ * Main entry point - reads from stdin, processes, writes to stdout.
182
+ */
183
+ export async function main() {
184
+ try {
185
+ const args = parseArgs(process.argv);
186
+ // Read stdin
187
+ const stdinContent = readStdin();
188
+ // Skip if empty
189
+ if (!stdinContent.trim()) {
190
+ process.exit(0);
191
+ }
192
+ // Dispatch enforce / subagent registry modes
193
+ if (args.enforce || args.subagentStart || args.subagentStop) {
194
+ let data;
195
+ try {
196
+ data = JSON.parse(stdinContent);
197
+ }
198
+ catch {
199
+ process.exit(0);
200
+ }
201
+ const obj = (data && typeof data === 'object' ? data : {});
202
+ const sessionId = typeof obj['session_id'] === 'string' ? obj['session_id'] : 'unknown';
203
+ if (args.enforce) {
204
+ // Parse as PreToolUseInput for enforcement check
205
+ const stdinInput = parseStdinInput(stdinContent);
206
+ if (stdinInput.kind === 'tooluse') {
207
+ runEnforce(stdinInput.input);
208
+ }
209
+ process.exit(0);
210
+ }
211
+ if (args.subagentStart) {
212
+ runSubagentStart({ session_id: sessionId });
213
+ // runSubagentStart calls process.exit internally
214
+ }
215
+ if (args.subagentStop) {
216
+ runSubagentStop({ session_id: sessionId });
217
+ // runSubagentStop calls process.exit internally
218
+ }
219
+ process.exit(0);
220
+ }
221
+ // Get manifest path from environment
222
+ const projectDir = process.env['CLAUDE_PROJECT_DIR'] ?? process.cwd();
223
+ const manifestPath = `${projectDir}/.claude/skills-manifest.json`;
224
+ // Parse and dispatch based on input type
225
+ const stdinInput = parseStdinInput(stdinContent);
226
+ let output;
227
+ if (stdinInput.kind === 'tooluse') {
228
+ // PreToolUse hook
229
+ output = processToolUse(stdinInput.input, manifestPath, projectDir);
230
+ }
231
+ else {
232
+ // UserPromptSubmit mode
233
+ output = processPrompt(stdinInput.input, manifestPath, projectDir);
234
+ }
235
+ // Write output if skills matched
236
+ if (output) {
237
+ process.stdout.write(JSON.stringify(output));
238
+ }
239
+ process.exit(0);
240
+ }
241
+ catch (error) {
242
+ // Log error but always exit 0
243
+ console.error(`[Router Error] ${error instanceof Error ? error.message : String(error)}`);
244
+ process.exit(0);
245
+ }
246
+ }
247
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,eA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OAAO,CAAC,KAAK,CACX,kBAAkB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAC3E,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Manifest loading and validation
3
+ */
4
+ import type { SkillManifest } from './types.js';
5
+ /**
6
+ * Loads and validates a skill manifest from the filesystem.
7
+ *
8
+ * @param manifestPath - Absolute path to the manifest JSON file
9
+ * @returns Validated SkillManifest
10
+ * @throws Error if file not found, invalid JSON, or schema validation fails
11
+ */
12
+ export declare function loadManifest(manifestPath: string): SkillManifest;
13
+ //# sourceMappingURL=manifest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAE,aAAa,EAA+B,MAAM,YAAY,CAAC;AAI7E;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,aAAa,CA2EhE"}
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Manifest loading and validation
3
+ */
4
+ import { readFileSync } from 'fs';
5
+ const DEFAULT_LOG_PATH = '.claude/logs/grimoire-router.log';
6
+ /**
7
+ * Loads and validates a skill manifest from the filesystem.
8
+ *
9
+ * @param manifestPath - Absolute path to the manifest JSON file
10
+ * @returns Validated SkillManifest
11
+ * @throws Error if file not found, invalid JSON, or schema validation fails
12
+ */
13
+ export function loadManifest(manifestPath) {
14
+ // Read file
15
+ let content;
16
+ try {
17
+ content = readFileSync(manifestPath, 'utf-8');
18
+ }
19
+ catch (error) {
20
+ const message = error instanceof Error ? error.message : String(error);
21
+ throw new Error(`Manifest file not found: ${manifestPath} - ${message}`);
22
+ }
23
+ // Parse JSON
24
+ let data;
25
+ try {
26
+ data = JSON.parse(content);
27
+ }
28
+ catch (error) {
29
+ const message = error instanceof Error ? error.message : String(error);
30
+ throw new Error(`Failed to parse manifest JSON: ${message}`);
31
+ }
32
+ // Validate structure
33
+ if (!data || typeof data !== 'object') {
34
+ throw new Error('Manifest must be an object');
35
+ }
36
+ const manifest = data;
37
+ // Validate version
38
+ if (!manifest['version'] || typeof manifest['version'] !== 'string') {
39
+ throw new Error('Manifest must have a version field');
40
+ }
41
+ // Validate config
42
+ if (!manifest['config'] || typeof manifest['config'] !== 'object') {
43
+ throw new Error('Manifest must have a config object');
44
+ }
45
+ const config = manifest['config'];
46
+ // Validate weights
47
+ if (!config['weights'] || typeof config['weights'] !== 'object') {
48
+ throw new Error('Manifest config must have weights object');
49
+ }
50
+ // Validate activation_threshold
51
+ if (typeof config['activation_threshold'] !== 'number') {
52
+ throw new Error('Manifest config must have activation_threshold number');
53
+ }
54
+ // Validate skills array
55
+ if (!Array.isArray(manifest['skills'])) {
56
+ throw new Error('Manifest must have skills array');
57
+ }
58
+ // Apply defaults and normalize skills
59
+ const skills = manifest['skills'].map((skill) => normalizeSkill(skill));
60
+ // Parse optional agents section
61
+ const agents = parseAgentsSection(manifest['agents']);
62
+ return {
63
+ version: manifest['version'],
64
+ config: {
65
+ weights: config['weights'],
66
+ activation_threshold: config['activation_threshold'],
67
+ pretooluse_threshold: typeof config['pretooluse_threshold'] === 'number'
68
+ ? config['pretooluse_threshold']
69
+ : undefined,
70
+ log_path: config['log_path'] || DEFAULT_LOG_PATH,
71
+ },
72
+ skills,
73
+ agents,
74
+ };
75
+ }
76
+ /**
77
+ * Parses the optional agents section of the manifest.
78
+ */
79
+ function parseAgentsSection(agents) {
80
+ if (agents === undefined || agents === null) {
81
+ return undefined;
82
+ }
83
+ if (typeof agents !== 'object' || Array.isArray(agents)) {
84
+ throw new Error('Manifest agents must be an object');
85
+ }
86
+ const agentsMap = agents;
87
+ const result = {};
88
+ for (const [agentName, agentConfig] of Object.entries(agentsMap)) {
89
+ if (!agentConfig || typeof agentConfig !== 'object') {
90
+ throw new Error(`Agent "${agentName}" config must be an object`);
91
+ }
92
+ const cfg = agentConfig;
93
+ const entry = {};
94
+ if (cfg['file_patterns'] !== undefined) {
95
+ if (!Array.isArray(cfg['file_patterns'])) {
96
+ throw new Error(`Agent "${agentName}" file_patterns must be an array`);
97
+ }
98
+ entry.file_patterns = cfg['file_patterns'];
99
+ }
100
+ if (cfg['enforce'] !== undefined) {
101
+ if (typeof cfg['enforce'] !== 'boolean') {
102
+ throw new Error(`Agent "${agentName}" enforce must be a boolean`);
103
+ }
104
+ entry.enforce = cfg['enforce'];
105
+ }
106
+ result[agentName] = entry;
107
+ }
108
+ return result;
109
+ }
110
+ /**
111
+ * Normalizes a skill definition, applying defaults for missing fields.
112
+ */
113
+ function normalizeSkill(skill) {
114
+ const triggers = skill['triggers'] || {};
115
+ return {
116
+ path: skill['path'],
117
+ name: skill['name'],
118
+ description: skill['description'],
119
+ triggers: {
120
+ keywords: triggers['keywords'] || [],
121
+ file_extensions: triggers['file_extensions'] || [],
122
+ patterns: triggers['patterns'] || [],
123
+ file_paths: triggers['file_paths'] || [],
124
+ },
125
+ };
126
+ }
127
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAGlC,MAAM,gBAAgB,GAAG,kCAAkC,CAAC;AAE5D;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAAC,YAAoB;IAC/C,YAAY;IACZ,IAAI,OAAe,CAAC;IACpB,IAAI,CAAC;QACH,OAAO,GAAG,YAAY,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IAChD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OA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AE,CAAC;IAEtE,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,MAAM,CAAW;QAC7B,IAAI,EAAE,KAAK,CAAC,MAAM,CAAW;QAC7B,WAAW,EAAE,KAAK,CAAC,aAAa,CAAuB;QACvD,QAAQ,EAAE;YACR,QAAQ,EAAG,QAAQ,CAAC,UAAU,CAAc,IAAI,EAAE;YAClD,eAAe,EAAG,QAAQ,CAAC,iBAAiB,CAAc,IAAI,EAAE;YAChE,QAAQ,EAAG,QAAQ,CAAC,UAAU,CAAc,IAAI,EAAE;YAClD,UAAU,EAAG,QAAQ,CAAC,YAAY,CAAc,IAAI,EAAE;SACvD;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Stemming and fuzzy matching for keyword scoring
3
+ */
4
+ /** Discount factor applied to fuzzy match scores */
5
+ export declare const FUZZY_DISCOUNT = 0.8;
6
+ /**
7
+ * Match quality in priority order: exact > stem > fuzzy
8
+ */
9
+ export type MatchQuality = 'exact' | 'stem' | 'fuzzy';
10
+ export interface KeywordMatchResult {
11
+ matched: boolean;
12
+ quality: MatchQuality;
13
+ matchedWord: string;
14
+ }
15
+ /**
16
+ * Lightweight suffix-stripping stemmer.
17
+ * Words shorter than 4 characters are returned unchanged.
18
+ */
19
+ export declare function stem(word: string): string;
20
+ /**
21
+ * Levenshtein distance with early termination.
22
+ * Uses O(min(m,n)) space via single-row DP.
23
+ *
24
+ * @returns Edit distance, or maxDistance+1 if distance exceeds maxDistance
25
+ */
26
+ export declare function levenshteinDistance(a: string, b: string, maxDistance: number): number;
27
+ /**
28
+ * Returns the maximum allowed edit distance for a keyword of a given length.
29
+ * Short words (1-3 chars) get no fuzzy matching to avoid false positives.
30
+ */
31
+ export declare function fuzzyThreshold(wordLength: number): number;
32
+ /**
33
+ * Pre-computes a map from stemmed form → original word for all prompt words.
34
+ * Used once per scoring call to avoid redundant stem() calls.
35
+ */
36
+ export declare function buildStemmedWordMap(words: Set<string>): Map<string, string>;
37
+ /**
38
+ * Matches a single keyword against prompt words using the priority chain:
39
+ * exact → stem → fuzzy.
40
+ *
41
+ * @param keywordLower - The keyword in lowercase
42
+ * @param words - Set of normalized prompt words
43
+ * @param stemmedWords - Pre-computed stem → original word map
44
+ * @returns Match result with quality level and the matched word
45
+ */
46
+ export declare function matchKeyword(keywordLower: string, words: Set<string>, stemmedWords: Map<string, string>): KeywordMatchResult;
47
+ //# sourceMappingURL=matching.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matching.d.ts","sourceRoot":"","sources":["../src/matching.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,oDAAoD;AACpD,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC;AAEtD,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,YAAY,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;CACrB;AAQD;;;GAGG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAyDzC;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,MAAM,EACT,WAAW,EAAE,MAAM,GAClB,MAAM,CA4CR;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAIzD;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAU3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,EAClB,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAChC,kBAAkB,CAiCpB"}