pocket-tutor 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +185 -2
- package/bin/pocket-tutor.js +127 -0
- package/config.example.json +12 -0
- package/docs/CLIP_RULES.md +38 -0
- package/package.json +74 -4
- package/scripts/build-ui.mjs +25 -0
- package/scripts/clip-judge.js +106 -0
- package/scripts/doctor.js +58 -0
- package/scripts/setup-visuals.js +27 -0
- package/scripts/visual_scene.py +279 -0
- package/src/astryx-themes.js +18 -0
- package/src/browser.js +38 -0
- package/src/config.js +84 -0
- package/src/graph.js +114 -0
- package/src/helper.ps1 +67 -0
- package/src/main.js +526 -0
- package/src/model.js +283 -0
- package/src/native.js +50 -0
- package/src/place.js +29 -0
- package/src/preload.js +17 -0
- package/src/privacy.js +40 -0
- package/src/project.js +252 -0
- package/src/search.js +111 -0
- package/src/setup.js +60 -0
- package/src/themes/lens/lens.css +1165 -0
- package/src/themes/lens/lens.css.d.ts +9 -0
- package/src/themes/lens/lens.d.ts +14 -0
- package/src/themes/lens/lens.fonts.css +2 -0
- package/src/themes/lens/lens.js +627 -0
- package/src/themes/lens/lens.variants.d.ts +22 -0
- package/src/themes/lens/lensTheme.doc.mjs +10 -0
- package/src/themes/lens/lensTheme.ts +2 -0
- package/src/tools.js +102 -0
- package/src/ui/app.jsx +268 -0
- package/src/ui/dist/assets/KaTeX_AMS-Regular-CYEKBG2K.woff +0 -0
- package/src/ui/dist/assets/KaTeX_AMS-Regular-JKX5W2C4.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_AMS-Regular-U6PRYMIZ.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-5QL5CMTE.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-WZ3QSGD3.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-ZTS3R3HK.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-3LKEU76G.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-A7XRTZ5Q.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-KX5MEWCF.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Fraktur-Bold-2QVFK6NQ.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Fraktur-Bold-T4SWXBMT.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Fraktur-Bold-WGHVTYOR.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Fraktur-Regular-2PEIFJSJ.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Fraktur-Regular-5U4OPH2X.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Fraktur-Regular-PQMHCIK6.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Bold-2GA4IZIN.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Bold-W5FBVCZM.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Bold-YP5VVQRP.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Main-BoldItalic-4P4C7HJH.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Main-BoldItalic-N4V3DX7S.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Main-BoldItalic-ODMLBJJQ.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Italic-I43T2HSR.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Italic-RELBIK7M.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Italic-SASNQFN2.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Regular-ARRPAO67.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Regular-P5I74A2A.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Main-Regular-W74P5G27.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Math-BoldItalic-6EBV3DK5.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Math-BoldItalic-K4WTGH3J.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Math-BoldItalic-VB447A4D.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Math-Italic-6KGCHLFN.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Math-Italic-KKK3USB2.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Math-Italic-SON4MRCA.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Bold-RRNVJFFW.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Bold-STQ6RXC7.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Bold-X5M5EMOD.woff +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Italic-HMPFTM52.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Italic-PSN4QKYX.woff +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Italic-WTBAZBGY.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Regular-2TL3USAE.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Regular-OQCII6EP.woff +0 -0
- package/src/ui/dist/assets/KaTeX_SansSerif-Regular-XIQ62X4E.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Script-Regular-72OLXYNA.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Script-Regular-A5IFOEBS.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Script-Regular-APUWIHLP.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Size1-Regular-4HRHTS65.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Size1-Regular-5LRUTBFT.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Size1-Regular-7K6AASVL.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Size2-Regular-222HN3GT.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Size2-Regular-K5ZHAIS6.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Size2-Regular-LELKET5D.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Size3-Regular-TLFPAHDE.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Size3-Regular-UFCO6WCA.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Size3-Regular-WQRQ47UD.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Size4-Regular-7PGNVPQK.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Size4-Regular-CDMV7U5C.woff2 +0 -0
- package/src/ui/dist/assets/KaTeX_Size4-Regular-PKMWZHNC.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Typewriter-Regular-3F5K6SQ6.ttf +0 -0
- package/src/ui/dist/assets/KaTeX_Typewriter-Regular-MJMFSK64.woff +0 -0
- package/src/ui/dist/assets/KaTeX_Typewriter-Regular-VBYJ4NRC.woff2 +0 -0
- package/src/ui/dist/assets/figtree-latin-400-normal-PORFSHKN.woff2 +0 -0
- package/src/ui/dist/assets/figtree-latin-500-normal-AHYR5JKA.woff2 +0 -0
- package/src/ui/dist/assets/figtree-latin-600-normal-5C6Z7QEI.woff2 +0 -0
- package/src/ui/dist/assets/figtree-latin-700-normal-M33EANAW.woff2 +0 -0
- package/src/ui/dist/assets/figtree-latin-ext-400-normal-CK4ZBFIX.woff2 +0 -0
- package/src/ui/dist/assets/figtree-latin-ext-500-normal-M4H6A6MQ.woff2 +0 -0
- package/src/ui/dist/assets/figtree-latin-ext-600-normal-KUZFNAIE.woff2 +0 -0
- package/src/ui/dist/assets/figtree-latin-ext-700-normal-U3DQVDYX.woff2 +0 -0
- package/src/ui/dist/popup.css +1 -0
- package/src/ui/dist/popup.js +546 -0
- package/src/ui/popup.html +13 -0
- package/src/ui/state.js +89 -0
- package/src/visual.js +229 -0
package/src/project.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// "The codebase" = the project open in the window you selected from.
|
|
2
|
+
// 1. parseWindow: app + title → editor? which folder and file (VS Code / Cursor put "file - folder - Editor" in the title)
|
|
3
|
+
// 2. resolveFolder: folder name → a path (editor's recent-folder list, then a scan of the configured roots)
|
|
4
|
+
// 3. searchCode: the plan's code terms → a few snippets with file:line, never from secret files, masked
|
|
5
|
+
const fs = require('fs')
|
|
6
|
+
const os = require('os')
|
|
7
|
+
const path = require('path')
|
|
8
|
+
const { execFile } = require('child_process')
|
|
9
|
+
const { secretFile, mask } = require('./privacy')
|
|
10
|
+
|
|
11
|
+
const EDITORS = new Set(['code', 'code - insiders', 'cursor', 'windsurf', 'vscodium'])
|
|
12
|
+
const TERMINALS = new Set(['windowsterminal', 'cmd', 'powershell', 'pwsh', 'conhost', 'wezterm-gui', 'alacritty', 'mintty'])
|
|
13
|
+
|
|
14
|
+
const LANG = {
|
|
15
|
+
py: 'Python', ipynb: 'Python', js: 'JavaScript', mjs: 'JavaScript', cjs: 'JavaScript', jsx: 'JavaScript (React)',
|
|
16
|
+
ts: 'TypeScript', tsx: 'TypeScript (React)', rs: 'Rust', go: 'Go', java: 'Java', c: 'C', h: 'C', cpp: 'C++', cc: 'C++',
|
|
17
|
+
cs: 'C#', rb: 'Ruby', php: 'PHP', sql: 'SQL', r: 'R', md: 'Markdown', html: 'HTML', css: 'CSS', json: 'JSON',
|
|
18
|
+
yml: 'YAML', yaml: 'YAML', toml: 'TOML', sh: 'Shell', ps1: 'PowerShell', tex: 'LaTeX', kt: 'Kotlin', swift: 'Swift',
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function language(file) {
|
|
22
|
+
const m = /\.([A-Za-z0-9]+)$/.exec(file || '')
|
|
23
|
+
return m ? LANG[m[1].toLowerCase()] || m[1].toLowerCase() : null
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// editor titles start with unsaved/spinner markers and may end with "[Administrator]"
|
|
27
|
+
function cleanTitle(title = '') {
|
|
28
|
+
return String(title).replace(/^[\s●○◐◑◒◓⠁-⣿•*]+/u, '').replace(/\s+\[(Administrator|Extension Development Host)\]$/, '').trim()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function parseWindow(app, title) {
|
|
32
|
+
const a = String(app || '').toLowerCase()
|
|
33
|
+
const t = cleanTitle(title)
|
|
34
|
+
if (EDITORS.has(a)) {
|
|
35
|
+
const parts = t.split(' - ').map((s) => s.trim()).filter(Boolean)
|
|
36
|
+
parts.pop() // editor name
|
|
37
|
+
const folder = parts.length >= 2 ? parts[parts.length - 1] : parts[0] || null
|
|
38
|
+
const file = parts.length >= 2 ? parts[0] : null
|
|
39
|
+
return { kind: 'editor', app: a, folder, file, language: language(file), label: [folder, file].filter(Boolean).join(' · ') || t }
|
|
40
|
+
}
|
|
41
|
+
if (TERMINALS.has(a)) return { kind: 'terminal', app: a, label: t || a }
|
|
42
|
+
const browser = /^(chrome|msedge|brave|firefox|opera|vivaldi|arc)$/.test(a)
|
|
43
|
+
const page = t.replace(/\s+[-–—]\s+(Google Chrome|Microsoft?\s*Edge|Brave|Mozilla Firefox|Opera|Vivaldi)$/i, '')
|
|
44
|
+
return { kind: browser ? 'browser' : 'app', app: a, label: page || a }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ---- the workspace, found without asking ----------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
// Terminals often put the folder in the title (C:\Projects\app, PS C:\Projects\app>). Only a folder that exists counts.
|
|
50
|
+
function terminalFolder(title) {
|
|
51
|
+
const m = /[A-Za-z]:\\[^"*?<>|\r\n]*/.exec(String(title || ''))
|
|
52
|
+
if (!m) return null
|
|
53
|
+
let p = m[0].replace(/[>\s]+$/, '')
|
|
54
|
+
while (p.length > 3) {
|
|
55
|
+
try { if (fs.statSync(p).isDirectory()) return p } catch { /* try the parent */ }
|
|
56
|
+
p = path.dirname(p)
|
|
57
|
+
}
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The folder to search for the window you are in: the editor's project (from its title, else the folder it had open
|
|
62
|
+
// last), or a terminal's current folder. null for other apps.
|
|
63
|
+
function workspaceRoot(where, title, roots) {
|
|
64
|
+
if (where.kind === 'editor') return (where.folder && resolveFolder(where.folder, roots)) || (!where.folder ? editorFolders()[0] || null : null)
|
|
65
|
+
if (where.kind === 'terminal') return terminalFolder(title)
|
|
66
|
+
return null
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// A few lines about the project, so the model knows what it is even when no snippet matches: the README's start,
|
|
70
|
+
// package.json's name, description and dependencies, pyproject.toml's name. Masked like everything else.
|
|
71
|
+
function profile(root) {
|
|
72
|
+
if (!root) return ''
|
|
73
|
+
const read = (f, n = 4000) => { try { return fs.readFileSync(path.join(root, f), 'utf8').slice(0, n) } catch { return '' } }
|
|
74
|
+
const out = [`Folder: ${path.basename(root)}`]
|
|
75
|
+
try {
|
|
76
|
+
const p = JSON.parse(read('package.json', 20000))
|
|
77
|
+
out.push(`package.json: ${[p.name, p.description].filter(Boolean).join(': ')}`)
|
|
78
|
+
const deps = Object.keys({ ...p.dependencies, ...p.devDependencies }).slice(0, 15)
|
|
79
|
+
if (deps.length) out.push(`Dependencies: ${deps.join(', ')}`)
|
|
80
|
+
} catch { /* no package.json */ }
|
|
81
|
+
const py = /^name\s*=\s*"([^"]+)"/m.exec(read('pyproject.toml'))
|
|
82
|
+
if (py) out.push(`Python project: ${py[1]}`)
|
|
83
|
+
const readme = read('README.md').split(/\r?\n/).map((l) => l.trim()).filter(Boolean).slice(0, 8).join(' ').slice(0, 500)
|
|
84
|
+
if (readme) out.push(`README: ${readme}`)
|
|
85
|
+
return mask(out.join('\n'))
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---- folder name → path ---------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
function fileUriToPath(uri) {
|
|
91
|
+
if (!/^file:\/\//i.test(uri || '')) return null
|
|
92
|
+
let p = decodeURIComponent(uri.replace(/^file:\/\/\/?/i, ''))
|
|
93
|
+
if (/^[a-z]:/i.test(p)) p = p[0].toUpperCase() + p.slice(1)
|
|
94
|
+
return path.normalize(p)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// every folder the editors remember (VS Code and Cursor keep this in storage.json)
|
|
98
|
+
function editorFolders() {
|
|
99
|
+
const appdata = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
|
|
100
|
+
const out = []
|
|
101
|
+
for (const product of ['Code', 'Code - Insiders', 'Cursor', 'Windsurf', 'VSCodium']) {
|
|
102
|
+
let d
|
|
103
|
+
try { d = JSON.parse(fs.readFileSync(path.join(appdata, product, 'User', 'globalStorage', 'storage.json'), 'utf8')) } catch { continue }
|
|
104
|
+
const ws = d.windowsState || {}
|
|
105
|
+
const uris = [ws.lastActiveWindow && ws.lastActiveWindow.folder,
|
|
106
|
+
...(ws.openedWindows || []).map((w) => w.folder),
|
|
107
|
+
...((d.backupWorkspaces && d.backupWorkspaces.folders) || []).map((f) => f.folderUri)]
|
|
108
|
+
for (const u of uris) { const p = fileUriToPath(u); if (p) out.push(p) }
|
|
109
|
+
}
|
|
110
|
+
return out
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', '.venv', 'venv', '__pycache__', 'dist', 'build', '.next', 'target', '.cache'])
|
|
114
|
+
|
|
115
|
+
// breadth-first, depth ≤ 3, so a name under C:\Projects\my-app\... is found without walking whole trees
|
|
116
|
+
function scanRoots(name, roots, maxDepth = 3) {
|
|
117
|
+
const want = name.toLowerCase()
|
|
118
|
+
let level = roots.filter((r) => { try { return fs.statSync(r).isDirectory() } catch { return false } })
|
|
119
|
+
for (let depth = 0; depth <= maxDepth && level.length; depth++) {
|
|
120
|
+
const next = []
|
|
121
|
+
for (const dir of level) {
|
|
122
|
+
if (path.basename(dir).toLowerCase() === want) return dir
|
|
123
|
+
let entries = []
|
|
124
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { continue }
|
|
125
|
+
for (const e of entries) if (e.isDirectory() && !SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) next.push(path.join(dir, e.name))
|
|
126
|
+
}
|
|
127
|
+
level = next
|
|
128
|
+
}
|
|
129
|
+
return null
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const cache = new Map()
|
|
133
|
+
function resolveFolder(name, roots, folders = editorFolders()) {
|
|
134
|
+
if (!name) return null
|
|
135
|
+
if (cache.has(name)) return cache.get(name)
|
|
136
|
+
const exists = (p) => { try { return fs.statSync(p).isDirectory() } catch { return false } }
|
|
137
|
+
const hit = folders.find((p) => path.basename(p).toLowerCase() === name.toLowerCase() && exists(p)) || scanRoots(name, roots)
|
|
138
|
+
if (hit) cache.set(name, hit)
|
|
139
|
+
return hit
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ---- code search ----------------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
// "src/a.js:12:text" → { file, line, text }
|
|
145
|
+
function parseGrep(out) {
|
|
146
|
+
const hits = []
|
|
147
|
+
for (const raw of String(out || '').split(/\r?\n/)) {
|
|
148
|
+
const m = /^(.+?):(\d+):(.*)$/.exec(raw)
|
|
149
|
+
if (m) hits.push({ file: m[1], line: Number(m[2]), text: m[3] })
|
|
150
|
+
}
|
|
151
|
+
return hits
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function gitGrep(root, terms) {
|
|
155
|
+
// --untracked: new files you haven't committed yet count too (.gitignore still keeps node_modules etc. out)
|
|
156
|
+
const args = ['-C', root, 'grep', '--untracked', '-n', '-I', '-i', '-F', '--max-count=3', ...terms.flatMap((t) => ['-e', t]),
|
|
157
|
+
'--', '.', ':(exclude)*.lock', ':(exclude)package-lock.json', ':(exclude)*.min.*', ':(exclude)*.map']
|
|
158
|
+
return new Promise((resolve) => {
|
|
159
|
+
execFile('git', args, { timeout: 4000, maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (err, stdout, stderr) => {
|
|
160
|
+
if (err && err.code === 1) return resolve([]) // no matches
|
|
161
|
+
if (err && /not a git repository/i.test(stderr || '')) return resolve(null)
|
|
162
|
+
resolve(err && !stdout ? null : parseGrep(stdout))
|
|
163
|
+
})
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const TEXT_EXT = /\.(py|ipynb|js|mjs|cjs|jsx|ts|tsx|rs|go|java|c|h|cpp|cc|cs|rb|php|sql|r|md|html|css|json|ya?ml|toml|sh|ps1|tex|kt|swift|txt)$/i
|
|
168
|
+
|
|
169
|
+
// for folders that aren't git repositories: a bounded walk
|
|
170
|
+
function walkGrep(root, terms, limitFiles = 3000) {
|
|
171
|
+
const want = terms.map((t) => t.toLowerCase())
|
|
172
|
+
const hits = []
|
|
173
|
+
const stack = [root]
|
|
174
|
+
let seen = 0
|
|
175
|
+
while (stack.length && seen < limitFiles && hits.length < 60) {
|
|
176
|
+
const dir = stack.pop()
|
|
177
|
+
let entries = []
|
|
178
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { continue }
|
|
179
|
+
for (const e of entries) {
|
|
180
|
+
const p = path.join(dir, e.name)
|
|
181
|
+
if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) stack.push(p); continue }
|
|
182
|
+
if (!TEXT_EXT.test(e.name) || secretFile(p)) continue
|
|
183
|
+
seen++
|
|
184
|
+
let text
|
|
185
|
+
try { if (fs.statSync(p).size > 300 * 1024) continue; text = fs.readFileSync(p, 'utf8') } catch { continue }
|
|
186
|
+
const lines = text.split(/\r?\n/)
|
|
187
|
+
let n = 0
|
|
188
|
+
for (let i = 0; i < lines.length && n < 3; i++) {
|
|
189
|
+
const l = lines[i].toLowerCase()
|
|
190
|
+
if (want.some((t) => l.includes(t))) { hits.push({ file: path.relative(root, p), line: i + 1, text: lines[i] }); n++ }
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return hits
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// pick snippets: the exact selected line first (in the open file, if it is there), then one hit per file
|
|
198
|
+
function pickHits(hits, terms, exact, max, openFile = null) {
|
|
199
|
+
const open = openFile ? String(openFile).toLowerCase() : null
|
|
200
|
+
const score = (h) => {
|
|
201
|
+
const l = h.text.toLowerCase()
|
|
202
|
+
let s = terms.filter((t) => l.includes(t.toLowerCase())).length
|
|
203
|
+
if (exact && l.includes(exact.toLowerCase())) s += 10
|
|
204
|
+
if (open && path.basename(h.file).toLowerCase() === open) s += 3
|
|
205
|
+
if (/(^|[\\/])(test|tests|__tests__|spec)[\\/]/i.test(h.file)) s -= 0.5
|
|
206
|
+
// real source beats notes about it
|
|
207
|
+
if (/\.(py|js|mjs|cjs|jsx|ts|tsx|rs|go|java|c|h|cpp|cc|cs|rb|php|kt|swift|sh|ps1)$/i.test(h.file)) s += 1
|
|
208
|
+
if (/(^|[\\/])(archive|docs?|notes?|third_party|vendor)[\\/]/i.test(h.file)) s -= 1
|
|
209
|
+
return s
|
|
210
|
+
}
|
|
211
|
+
const seenFile = new Set()
|
|
212
|
+
return hits
|
|
213
|
+
.filter((h) => !secretFile(h.file))
|
|
214
|
+
.sort((a, b) => score(b) - score(a))
|
|
215
|
+
.filter((h) => (seenFile.has(h.file) ? false : seenFile.add(h.file)))
|
|
216
|
+
.slice(0, max)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function withContext(root, hit, around = 3) {
|
|
220
|
+
try {
|
|
221
|
+
const lines = fs.readFileSync(path.join(root, hit.file), 'utf8').split(/\r?\n/)
|
|
222
|
+
const from = Math.max(1, hit.line - around)
|
|
223
|
+
const to = Math.min(lines.length, hit.line + around)
|
|
224
|
+
return { file: hit.file.replace(/\\/g, '/'), line: hit.line, from, code: mask(lines.slice(from - 1, to).join('\n')).slice(0, around > 3 ? 3000 : 1200) }
|
|
225
|
+
} catch {
|
|
226
|
+
return { file: hit.file.replace(/\\/g, '/'), line: hit.line, from: hit.line, code: mask(hit.text).slice(0, 400) }
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// A folder made of git submodules (a repo made of submodules) keeps its code in other repos. git grep doesn't
|
|
231
|
+
// look inside them, and --recurse-submodules can't be combined with --untracked, so each is searched on its own.
|
|
232
|
+
function submodulePaths(root) {
|
|
233
|
+
try {
|
|
234
|
+
const text = fs.readFileSync(path.join(root, '.gitmodules'), 'utf8')
|
|
235
|
+
return [...text.matchAll(/^\s*path\s*=\s*(.+?)\s*$/gm)].map((m) => m[1].replace(/\\/g, '/'))
|
|
236
|
+
.filter((p) => !p.includes('..') && fs.existsSync(path.join(root, p, '.git'))).slice(0, 16)
|
|
237
|
+
} catch { return [] }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function searchCode(root, terms, { exact = null, max = 6, openFile = null } = {}) {
|
|
241
|
+
const all = [...new Set([exact, ...terms].filter((t) => t && t.trim().length >= 2).map((t) => t.trim().slice(0, 120)))].slice(0, 6)
|
|
242
|
+
if (!root || !all.length) return []
|
|
243
|
+
const subs = submodulePaths(root)
|
|
244
|
+
const found = await Promise.all([gitGrep(root, all), ...subs.map((sub) =>
|
|
245
|
+
gitGrep(path.join(root, sub), all).then((h) => h && h.map((x) => ({ ...x, file: `${sub}/${x.file}` }))))])
|
|
246
|
+
let hits = found[0] === null && !subs.length ? walkGrep(root, all) : found.flatMap((h) => h || [])
|
|
247
|
+
// the line you selected gets more of the text around it: that's where you are reading
|
|
248
|
+
return pickHits(hits, all, exact, max, openFile).map((h) =>
|
|
249
|
+
withContext(root, h, exact && h.text.toLowerCase().includes(exact.toLowerCase()) ? 10 : 3))
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
module.exports = { terminalFolder, workspaceRoot, profile, parseWindow, cleanTitle, language, fileUriToPath, resolveFolder, scanRoots, parseGrep, pickHits, searchCode, submodulePaths, EDITORS, TERMINALS }
|
package/src/search.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Web results from DuckDuckGo's plain HTML page (no key, the default), Brave or a SearXNG instance.
|
|
2
|
+
// The results are never shown: they only feed the explanation, and only when the planner says the
|
|
3
|
+
// selection is a general idea worth looking up. relevant() drops results that don't share the query's words.
|
|
4
|
+
const UA = 'pocket-tutor/0.3 (desktop lookup tool)'
|
|
5
|
+
const BRAVE = 'https://api.search.brave.com/res/v1'
|
|
6
|
+
|
|
7
|
+
const ENT = { quot: '"', amp: '&', lt: '<', gt: '>', nbsp: ' ', '#39': "'", '#x27': "'" }
|
|
8
|
+
const stripTags = (s) => String(s || '').replace(/<[^>]+>/g, '')
|
|
9
|
+
.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (m, e) => ENT[e.toLowerCase()] ??
|
|
10
|
+
(e[0] === '#' ? String.fromCodePoint(e[1].toLowerCase() === 'x' ? parseInt(e.slice(2), 16) : Number(e.slice(1))) : m))
|
|
11
|
+
.replace(/\s+/g, ' ').trim()
|
|
12
|
+
|
|
13
|
+
function site(url) {
|
|
14
|
+
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return '' }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const isVideo = (url) => /^https?:\/\/(www\.|m\.)?(youtube\.com\/(watch|shorts)|youtu\.be\/|vimeo\.com\/\d)/.test(url)
|
|
18
|
+
|
|
19
|
+
async function get(url, { headers = {}, timeoutMs = 8000, json = false } = {}) {
|
|
20
|
+
const ctl = new AbortController()
|
|
21
|
+
const timer = setTimeout(() => ctl.abort(), timeoutMs)
|
|
22
|
+
try {
|
|
23
|
+
const r = await fetch(url, { signal: ctl.signal, headers: { 'user-agent': UA, accept: 'text/html,application/json', 'accept-language': 'en', ...headers } })
|
|
24
|
+
if (!r.ok) throw new Error(`${site(url)}: HTTP ${r.status}`)
|
|
25
|
+
return json ? await r.json() : await r.text()
|
|
26
|
+
} finally { clearTimeout(timer) }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ---- DuckDuckGo (no key) --------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
// DuckDuckGo answers a bare request (no accept headers) with a captcha page, so get() always sends them.
|
|
32
|
+
// DuckDuckGo wraps each link as //duckduckgo.com/l/?uddg=<real url>
|
|
33
|
+
function unwrap(href) {
|
|
34
|
+
const h = stripTags(href)
|
|
35
|
+
try {
|
|
36
|
+
const u = new URL(h, 'https://duckduckgo.com')
|
|
37
|
+
return u.searchParams.get('uddg') || (u.hostname.endsWith('duckduckgo.com') ? null : u.href)
|
|
38
|
+
} catch { return null }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// html.duckduckgo.com page → [{title, url, site, snippet}], ads dropped
|
|
42
|
+
function parseDdg(html) {
|
|
43
|
+
const out = []
|
|
44
|
+
const blocks = String(html || '').split(/<div[^>]+class="[^"]*\bresult\b/).slice(1)
|
|
45
|
+
for (const b of blocks) {
|
|
46
|
+
if (/result--ad\b/.test(b.slice(0, 200))) continue
|
|
47
|
+
const a = /class="result__a"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/.exec(b)
|
|
48
|
+
if (!a) continue
|
|
49
|
+
const url = unwrap(a[1])
|
|
50
|
+
if (!url || /duckduckgo\.com\/y\.js/.test(url)) continue
|
|
51
|
+
const sn = /class="result__snippet"[^>]*>([\s\S]*?)<\/a>/.exec(b)
|
|
52
|
+
out.push({ title: stripTags(a[2]), url, site: site(url), snippet: sn ? stripTags(sn[1]).slice(0, 400) : '' })
|
|
53
|
+
}
|
|
54
|
+
return out
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function ddgSearch(query) {
|
|
58
|
+
const html = await get(`https://html.duckduckgo.com/html/?${new URLSearchParams({ q: query, kl: 'wt-wt' })}`)
|
|
59
|
+
if (/anomaly|captcha/i.test(html) && !/result__a/.test(html)) throw new Error('DuckDuckGo asked for a captcha; try again in a minute')
|
|
60
|
+
return parseDdg(html)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---- Brave (optional key) -------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
function normalizeBrave(d) {
|
|
66
|
+
return ((d && d.web && d.web.results) || []).map((x) => ({ title: stripTags(x.title), url: x.url, site: site(x.url), snippet: stripTags(x.description).slice(0, 400) }))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ---- SearXNG: your own instance, with the JSON format switched on ---------------------------------
|
|
70
|
+
|
|
71
|
+
function normalizeSearxng(d) {
|
|
72
|
+
return ((d && d.results) || []).map((x) => ({ title: stripTags(x.title), url: x.url, site: site(x.url), snippet: stripTags(x.content).slice(0, 400) }))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---- relevance ------------------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
const STOP = new Set(['the', 'and', 'for', 'with', 'what', 'how', 'does', 'why', 'is', 'are', 'in', 'of', 'to', 'a', 'an', 'on', 'it', 'its', 'explained', 'meaning', 'example', 'use', 'using'])
|
|
78
|
+
const words = (s) => (String(s || '').toLowerCase().match(/[a-z0-9_+#.]{2,}/g) || []).map((w) => w.replace(/\.+$/, '')).filter((w) => w.length >= 2 && !STOP.has(w))
|
|
79
|
+
|
|
80
|
+
// keep a result only if it shares enough of the query's words: one for a short query, two for a longer one.
|
|
81
|
+
// A rough net only. The real guard against off-topic results (a search for a made-up project name once
|
|
82
|
+
// brought back unrelated shops) is the planner: for words that only mean something in your own project it
|
|
83
|
+
// says web: false, and no search runs.
|
|
84
|
+
function relevant(results, query) {
|
|
85
|
+
const q = [...new Set(words(query))]
|
|
86
|
+
if (!q.length) return results
|
|
87
|
+
const need = q.length >= 3 ? 2 : 1
|
|
88
|
+
return results.filter((r) => {
|
|
89
|
+
const text = new Set(words(`${r.title} ${r.snippet} ${r.url}`))
|
|
90
|
+
return q.filter((w) => text.has(w)).length >= need
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---- what main.js calls ---------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
// cfg: the settings (search_engine, brave_key, searxng_url). A search that fails falls back
|
|
97
|
+
// to DuckDuckGo once, so a wrong key or a quota limit doesn't leave the answer without web context.
|
|
98
|
+
async function webSearch(query, cfg = {}, count = 5) {
|
|
99
|
+
const engine = cfg.search_engine || 'duckduckgo'
|
|
100
|
+
const run = async () => {
|
|
101
|
+
if (engine === 'brave') return normalizeBrave(await get(`${BRAVE}/web/search?${new URLSearchParams({ q: query, count: String(count + 3), result_filter: 'web', safesearch: 'moderate' })}`,
|
|
102
|
+
{ json: true, headers: { accept: 'application/json', 'x-subscription-token': cfg.brave_key } }))
|
|
103
|
+
if (engine === 'searxng') return normalizeSearxng(await get(`${String(cfg.searxng_url).replace(/\/$/, '')}/search?${new URLSearchParams({ q: query, format: 'json' })}`, { json: true }))
|
|
104
|
+
return ddgSearch(query)
|
|
105
|
+
}
|
|
106
|
+
let all
|
|
107
|
+
try { all = await run() } catch (e) { if (engine === 'duckduckgo') throw e; all = await ddgSearch(query) }
|
|
108
|
+
return relevant(all.filter((r) => !isVideo(r.url)), query).slice(0, count)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
module.exports = { webSearch, parseDdg, normalizeBrave, normalizeSearxng, relevant, stripTags, isVideo }
|
package/src/setup.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// pocket-tutor setup: ask which model to use, test it, save ~/.pocket-tutor/config.json. No JSON editing.
|
|
2
|
+
const fs = require('fs')
|
|
3
|
+
const readline = require('readline')
|
|
4
|
+
const config = require('./config')
|
|
5
|
+
const model = require('./model')
|
|
6
|
+
|
|
7
|
+
const CHOICES = [
|
|
8
|
+
{ id: 'vercel', label: 'Vercel AI Gateway (free Nemotron model)', key: 'vercel_api_key', hint: 'free key at https://vercel.com/ai-gateway' },
|
|
9
|
+
{ id: 'openai', label: 'OpenAI', key: 'openai_api_key', hint: 'https://platform.openai.com/api-keys' },
|
|
10
|
+
{ id: 'openrouter', label: 'OpenRouter', key: 'openrouter_api_key', hint: 'https://openrouter.ai/keys' },
|
|
11
|
+
{ id: 'gemini', label: 'Google Gemini', key: 'gemini_api_key', hint: 'https://aistudio.google.com/apikey' },
|
|
12
|
+
{ id: 'groq', label: 'Groq', key: 'groq_api_key', hint: 'https://console.groq.com/keys' },
|
|
13
|
+
{ id: 'ollama', label: 'Ollama on this computer (no key)', key: null, hint: 'install from https://ollama.com, then: ollama pull llama3.2' },
|
|
14
|
+
{ id: 'custom', label: 'Another OpenAI-compatible server (you give the address)', key: 'llm_api_key', hint: '' },
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
// the settings file content for an answer, kept pure so it can be tested
|
|
18
|
+
function buildSettings(existing, choice, { key = '', baseUrl = '', modelName = '' } = {}) {
|
|
19
|
+
const next = { ...existing, provider: choice.id }
|
|
20
|
+
if (choice.key && key) next[choice.key] = key
|
|
21
|
+
if (choice.id === 'custom') next.base_url = baseUrl
|
|
22
|
+
if (modelName) next.model = modelName
|
|
23
|
+
return next
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function run() {
|
|
27
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
28
|
+
const ask = (q) => new Promise((res) => rl.question(q, (a) => res(a.trim())))
|
|
29
|
+
try {
|
|
30
|
+
console.log('Pocket Tutor setup\n\nWhich model should answer?')
|
|
31
|
+
CHOICES.forEach((c, i) => console.log(` ${i + 1}. ${c.label}`))
|
|
32
|
+
const pick = CHOICES[Number(await ask('\nNumber: ')) - 1]
|
|
33
|
+
if (!pick) { console.log('No choice made. Run pocket-tutor setup again.'); return 2 }
|
|
34
|
+
if (pick.hint) console.log(`\nKey: ${pick.hint}`)
|
|
35
|
+
const opts = {}
|
|
36
|
+
if (pick.id === 'custom') opts.baseUrl = await ask('Server address (it ends in /v1), for example http://localhost:1234/v1: ')
|
|
37
|
+
if (pick.key) opts.key = await ask('Paste the key (it is saved only in your settings file): ')
|
|
38
|
+
opts.modelName = await ask('Model name (Enter for the default): ')
|
|
39
|
+
let existing = {}
|
|
40
|
+
try { existing = JSON.parse(fs.readFileSync(config.FILE, 'utf8')) } catch { /* new file */ }
|
|
41
|
+
const settings = buildSettings(existing, pick, opts)
|
|
42
|
+
|
|
43
|
+
const cfg = config.resolve(settings, {})
|
|
44
|
+
if (!cfg.llm_key) { console.log('\nThat needs a key. Nothing saved. Run pocket-tutor setup again.'); return 2 }
|
|
45
|
+
process.stdout.write('\nTesting the model... ')
|
|
46
|
+
try {
|
|
47
|
+
await model.chat(cfg, cfg.model, [{ role: 'user', content: 'Reply with the single word: ready' }], { maxTokens: 20, timeoutMs: 30000 })
|
|
48
|
+
console.log('it answered.')
|
|
49
|
+
} catch (e) {
|
|
50
|
+
console.log(`failed: ${e.message}\nNothing saved. Check the key, the address and the model name, then run setup again.`)
|
|
51
|
+
return 1
|
|
52
|
+
}
|
|
53
|
+
fs.mkdirSync(config.HOME, { recursive: true })
|
|
54
|
+
fs.writeFileSync(config.FILE, JSON.stringify(settings, null, 2) + '\n', { mode: 0o600 })
|
|
55
|
+
console.log(`Saved to ${config.FILE}.\nNext: pocket-tutor (then select text anywhere and press Ctrl+Alt+Space)`)
|
|
56
|
+
return 0
|
|
57
|
+
} finally { rl.close() }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { run, buildSettings, CHOICES }
|