Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

intent-claude-gate.mjs

278 lines9.4 KB

1#!/usr/bin/env node
2import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
3import { execFileSync } from 'node:child_process'
4import { tmpdir } from 'node:os'
5import { dirname, join, relative, sep } from 'node:path'
6import { createHash } from 'node:crypto'
7import { performance } from 'node:perf_hooks'
8​
9const AGENT = "claude"
10const CATALOG_COMMAND = "pnpm exec intent list --json --no-notices"
11const LOAD_COMMAND = "pnpm exec intent load <package>#<skill>"
12const EDIT_TOOLS = new Set(["Edit","MultiEdit","NotebookEdit","Write"])
13const GATE_DENY_REASON = "Blocked: check TanStack guidance before editing. If a listed skill matches, load it, then retry the edit."
14const INTENT_INVOCATION_PATTERN = /(?:^|&&|\|\||;|\|)\s*((?:bunx\s+--no-install\s+--package\s+@tanstack\/intent\s+intent)|(?:npm\s+exec\s+--no\s+--\s+intent)|(?:yarn\s+exec\s+intent)|(?:bunx\s+@tanstack\/intent(?:@latest)?)|(?:pnpm\s+exec\s+intent)|(?:pnpm\s+dlx\s+@tanstack\/intent(?:@latest)?)|(?:npx\s+@tanstack\/intent(?:@latest)?)|(?:yarn\s+dlx\s+@tanstack\/intent(?:@latest)?)|(?:(?:[^\s|;&]*[\\/])?intent))\s+(list|load)(?:\s+([^\s|;&]+))?/i
15​
16try {
17 await main()
18} catch {
20​
21process.exit(0)
22​
23async function main() {
24 const event = readEventFromStdin()
25​
26 if (isSessionStartEvent(event)) {
27 const stateFile = stateFileForEvent(event)
28 const additionalContext = await createSessionCatalogContext(rootForEvent(event))
29 appendObservation(stateFile, { action: 'list', raw: CATALOG_COMMAND })
30 if (additionalContext) {
31 process.stdout.write(JSON.stringify(sessionStartOutput(additionalContext)))
32 }
33 return
34 }
35​
36 const stateFile = stateFileForEvent(event)
37 const observation = observationFromEvent(event)
38​
39 if (observation) {
40 appendObservation(stateFile, observation)
41 }
42​
43 const toolName = event?.tool_name ?? event?.toolName
44 if (typeof toolName === 'string' && EDIT_TOOLS.has(toolName) && !hasIntentCheck(stateFile)) {
45 process.stdout.write(JSON.stringify(denyOutput()))
46 }
48​
49function readEventFromStdin() {
50 try {
51 return JSON.parse(readFileSync(0, 'utf8'))
52 } catch {
53 return {}
54 }
56​
57function isSessionStartEvent(event) {
58 return (event?.hook_event_name ?? event?.hookEventName) === 'SessionStart'
60​
61function rootForEvent(event) {
62 return typeof event?.cwd === 'string' && event.cwd ? event.cwd : process.cwd()
64​
65async function createSessionCatalogContext(root) {
66 try {
67 const start = performance.now()
68 const localCli = resolveLocalIntentCli(root)
69 const result = readIntentList(root, localCli)
70 const durationMs = performance.now() - start
71 console.error(
72 `[intent-${AGENT}-session-catalog] listIntentSkills found ${result.skills.length} skills from ${result.packages.length} packages in ${formatDuration(durationMs)} (packageJsonReadCount=${result.debug?.scan.packageJsonReadCount ?? 'unknown'})`,
73 )
74 return formatSessionCatalog(result, loadCommandForLocalCli(root, localCli))
75 } catch {
76 return ''
77 }
79​
80// The package-manager runner in CATALOG_COMMAND (npx, pnpm dlx, ...) resolves
81// @tanstack/intent@latest against the registry on every run, which costs one
82// to four seconds per session start. When the project has the package
83// installed, run its CLI directly with this Node binary instead. Returns the
84// CLI path and the node_modules directory it was found in, or null.
85function resolveLocalIntentCli(root) {
86 let dir = root
87 let prev
88 while (dir !== prev) {
89 const nodeModulesDir = join(dir, 'node_modules')
90 const packageJsonPath = join(nodeModulesDir, '@tanstack', 'intent', 'package.json')
91 if (existsSync(packageJsonPath)) {
92 try {
93 const bin = JSON.parse(readFileSync(packageJsonPath, 'utf8')).bin
94 const relativeBin = typeof bin === 'string' ? bin : bin && bin.intent
95 if (typeof relativeBin === 'string') {
96 const cli = join(dirname(packageJsonPath), relativeBin)
97 if (existsSync(cli)) return { cli, nodeModulesDir }
98 }
99 } catch {
100 }
101 return null
102 }
103 prev = dir
104 dir = dirname(dir)
105 }
106 return null
108​
109// The load command shown to the agent. When the catalog came from a local
110// install that also has a bin shim, suggest that shim (same installation, no
111// registry lookup); otherwise suggest the package-manager runner.
112function loadCommandForLocalCli(root, localCli) {
113 if (!localCli) return LOAD_COMMAND
114 const bin = join(localCli.nodeModulesDir, '.bin', 'intent')
115 if (!existsSync(bin)) return LOAD_COMMAND
116 return relative(root, bin).split(sep).join('/') + ' load <package>#<skill>'
118​
119function readIntentList(root, localCli) {
120 const options = {
121 cwd: root,
122 encoding: 'utf8',
123 env: { ...process.env, INTENT_AUDIENCE: 'agent' },
124 maxBuffer: 1024 * 1024,
125 stdio: ['ignore', 'pipe', 'pipe'],
126 timeout: 9000,
127 }
128 const output = localCli
129 ? execFileSync(process.execPath, [localCli.cli, 'list', '--json', '--no-notices'], options)
130 : execFileSync(CATALOG_COMMAND, { ...options, shell: true })
131 return JSON.parse(output)
133​
134function formatDuration(durationMs) {
135 return `${durationMs.toFixed(1)}ms`
137​
138function formatSessionCatalog(result, loadCommand) {
139 if (!Array.isArray(result.skills) || result.skills.length === 0) return ''
140​
141 return [
142 'TanStack Intent skills are available in this repository.',
143 '',
144 'These are Intent skills, not native agent skills.',
145 'Load a matching skill with: `' + loadCommand + '`.',
146 '',
147 'Before substantial work, check whether one listed skill clearly matches the user task. If one clearly matches, load that full skill guidance with the Intent CLI before proceeding.',
148 '',
149 'If no skill clearly matches, continue normally. Do not load a skill just to improve phrasing or gather nonessential context.',
150 '',
151 'Available local Intent skills:',
152 formatSkillCatalog(result.skills),
153 formatWarnings(result),
154 ]
155 .filter(Boolean)
156 .join('\n')
158​
159function formatSkillCatalog(skills) {
160 return skills
161 .map((skill) => `- ${skill.use}: ${normalizeDescription(skill.description)}`)
162 .join('\n')
164​
165function normalizeDescription(description) {
166 return typeof description === 'string' ? description.replace(/\s+/g, ' ').trim() : ''
168​
169function formatWarnings(result) {
170 const warnings = [
171 ...(Array.isArray(result.warnings) ? result.warnings : []),
172 ...(Array.isArray(result.conflicts)
173 ? result.conflicts.map(
174 (conflict) =>
175 `Version conflict for ${conflict.packageName}; using ${conflict.chosen.version}`,
176 )
177 : []),
178 ]
179​
180 if (warnings.length === 0) return ''
181 return `\nWarnings:\n${warnings.map((warning) => `- ${warning}`).join('\n')}`
183​
184function sessionStartOutput(additionalContext) {
185 if (AGENT === 'copilot') {
186 return { additionalContext }
187 }
188​
189 return {
190 hookSpecificOutput: {
191 hookEventName: 'SessionStart',
192 additionalContext,
193 },
194 }
196​
197function stateFileForEvent(event) {
198 const sessionId = typeof event?.session_id === 'string' ? event.session_id : 'unknown'
199 const cwd = typeof event?.cwd === 'string' ? event.cwd : process.cwd()
200 const key = createHash('sha256').update(AGENT + '\0' + cwd + '\0' + sessionId).digest('hex')
201 return join(tmpdir(), 'tanstack-intent-hooks', key + '.jsonl')
203​
204function parseIntentInvocation(command) {
205 if (typeof command !== 'string') return undefined
206 const match = command.match(INTENT_INVOCATION_PATTERN)
207 if (!match?.[1] || !match[2]) return undefined
208 const action = match[2].toLowerCase()
209 if (action !== 'list' && action !== 'load') return undefined
210 const skillUse = action === 'load' ? match[3] : undefined
211 if (action === 'load' && !skillUse) return undefined
212 return action === 'load' ? { action, skillUse } : { action }
214​
215function observationFromEvent(event) {
216 if (!event || typeof event !== 'object') return undefined
217 const toolName = event.tool_name ?? event.toolName
218 const toolInput = event.tool_input ?? event.toolArgs
219 if (toolName !== 'Bash') return undefined
220 const command = typeof toolInput === 'string' ? safeCommandFromString(toolInput) : commandFromObject(toolInput)
221 const parsed = parseIntentInvocation(command)
222 if (!parsed || typeof command !== 'string') return undefined
223 return { action: parsed.action, skillUse: parsed.skillUse, raw: command }
225​
226function commandFromObject(value) {
227 return value && typeof value === 'object' ? value.command : undefined
229​
230function safeCommandFromString(value) {
231 try {
232 const command = commandFromObject(JSON.parse(value))
233 return typeof command === 'string' ? command : value
234 } catch {
235 return value
236 }
238​
239function appendObservation(stateFile, observation) {
240 try {
241 mkdirSync(dirname(stateFile), { recursive: true })
242 appendFileSync(stateFile, JSON.stringify({ ts: new Date().toISOString(), ...observation }) + '\n')
243 } catch {
244 }
246​
247function hasIntentCheck(stateFile) {
248 if (!existsSync(stateFile)) return false
249 try {
250 return readFileSync(stateFile, 'utf8')
251 .split('\n')
252 .filter(Boolean)
253 .some((line) => {
254 try {
255 const action = JSON.parse(line).action
256 return action === 'list' || action === 'load'
257 } catch {
258 return false
259 }
260 })
261 } catch {
262 return false
263 }
265​
266function denyOutput() {
267 if (AGENT === 'copilot') {
268 return { permissionDecision: 'deny', permissionDecisionReason: GATE_DENY_REASON }
269 }
270​
271 return {
272 hookSpecificOutput: {
273 hookEventName: 'PreToolUse',
274 permissionDecision: 'deny',
275 permissionDecisionReason: GATE_DENY_REASON,
276 },
277 }