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/model.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// The model calls.
|
|
2
|
+
// plan: selection + where you are → what it is called, related ideas, whether the web can help, code words,
|
|
3
|
+
// and whether it is math worth animating
|
|
4
|
+
// answer: selection + your code + what the context graph remembers + (maybe) web results → a short explanation
|
|
5
|
+
// math: (math only) the explanation → a formula and its parts, which src/visual.js animates with ManimGL
|
|
6
|
+
// Prompt builders and parsers are pure (test/pure.test.js); chat() talks to any OpenAI-compatible endpoint.
|
|
7
|
+
|
|
8
|
+
const MAX_SELECTION = 2000
|
|
9
|
+
|
|
10
|
+
function whereLine(where) {
|
|
11
|
+
if (!where) return 'unknown window'
|
|
12
|
+
const bits = [where.label || where.app]
|
|
13
|
+
if (where.kind === 'editor' && where.language) bits.push(`${where.language} file`)
|
|
14
|
+
if (where.root) bits.push(`project folder ${where.root}`)
|
|
15
|
+
return bits.filter(Boolean).join(', ')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function planMessages(selection, where) {
|
|
19
|
+
return [
|
|
20
|
+
{ role: 'system', content: [
|
|
21
|
+
'A student selected some text on their screen because they did not understand it. Plan how to explain it.',
|
|
22
|
+
'Reply with JSON only: {"concept": string, "related": string[], "web": boolean, "query": string, "code_terms": string[], "math": boolean}.',
|
|
23
|
+
'- concept: the name of the main thing to explain, 1 to 5 words (for example "RMSNorm" or "git rebase").',
|
|
24
|
+
'- related: up to 4 short names of ideas it connects to.',
|
|
25
|
+
'- web: true only when it is a general idea the web explains well (a library, an algorithm, jargon, an error message). false when it only means something inside their own project or notes (their file names, plans, todo items, their own variable names).',
|
|
26
|
+
'- query: a web search of at most 8 words when web is true, else "". Add the language or library when known.',
|
|
27
|
+
'- code_terms: up to 4 names or exact short phrases worth finding in their own project files, code AND notes or docs: a function, class or config name, or the key term itself ("Mixture-of-Experts", "shared expert"). Specific enough to find the right place; never common words such as exp, sum, max, data or value. Prefer short key terms of 1 to 3 words over long titles, so they also find the code and other notes about it. Give at least one whenever the window is a code editor, even for prose in a Markdown file.',
|
|
28
|
+
'- math: true only when the text is a formula, an equation or a math idea, and seeing the formula built up piece by piece would help. false for everything else, including ordinary code and words.',
|
|
29
|
+
'- Never put personal data, keys or file paths in the query.',
|
|
30
|
+
].join('\n') },
|
|
31
|
+
{ role: 'user', content: `Window: ${whereLine(where)}\nSelected text:\n"""\n${selection.slice(0, MAX_SELECTION)}\n"""` },
|
|
32
|
+
]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const IDENT = /[A-Za-z_][A-Za-z0-9_.]{2,}/g
|
|
36
|
+
const STOP = new Set(['the', 'and', 'for', 'with', 'this', 'that', 'from', 'are', 'was', 'not', 'you', 'your', 'return', 'const', 'let', 'var', 'def', 'self', 'true', 'false', 'null', 'none', 'import', 'function'])
|
|
37
|
+
|
|
38
|
+
// when the model is missing or returns something unusable
|
|
39
|
+
function fallbackPlan(selection, where) {
|
|
40
|
+
const words = selection.replace(/\s+/g, ' ').trim().split(' ')
|
|
41
|
+
const short = words.slice(0, 8).join(' ')
|
|
42
|
+
const lang = where && where.language && !new RegExp(where.language, 'i').test(short) ? ` ${where.language}` : ''
|
|
43
|
+
const idents = [...new Set((selection.match(IDENT) || []).filter((w) => !STOP.has(w.toLowerCase())))]
|
|
44
|
+
.sort((a, b) => b.length - a.length).slice(0, 3)
|
|
45
|
+
return { concept: words.slice(0, 5).join(' ').slice(0, 60), related: [], web: words.length <= 6,
|
|
46
|
+
query: `${words.length <= 4 ? 'what is ' : ''}${short}${lang}`.trim(), code_terms: idents, math: false, fallback: true }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The plan the answer starts from, made without the model, so the searches begin the moment you press the
|
|
50
|
+
// hotkey. The model's plan (planMessages) still runs alongside, for the graph, the math clip and the detail window.
|
|
51
|
+
const CODE_LIKE = /[{};=<>]|=>|^\s*(def|class|function|import|from|const|let|var|return|if|for)\b/m
|
|
52
|
+
function quickPlan(selection, where) {
|
|
53
|
+
const text = selection.replace(/[*_`#>]+/g, ' ').replace(/^\s*\d+[.)]\s+/gm, '').replace(/\s+/g, ' ').trim()
|
|
54
|
+
const words = text.split(' ').filter(Boolean)
|
|
55
|
+
// names worth finding in the project: Mixture-of-Experts, (MoE), globalShortcut.register, max_snippets
|
|
56
|
+
const phrases = (text.match(/\b[A-Za-z]+(?:-[A-Za-z]+)+\b|\([A-Z][A-Za-z]{1,6}\)/g) || []).map((p) => p.replace(/[()]/g, ''))
|
|
57
|
+
const idents = (selection.match(IDENT) || []).filter((w) => /[_.]|[a-z][A-Z]/.test(w) && !STOP.has(w.toLowerCase()))
|
|
58
|
+
let terms = [...new Set([...phrases, ...idents].map((t) => t.replace(/\.$/, '')))].filter((t) => t.length >= 3)
|
|
59
|
+
.sort((a, b) => b.length - a.length).slice(0, 4)
|
|
60
|
+
if (!terms.length && words.length <= 3) terms = [text]
|
|
61
|
+
const lang = where && where.language && words.length <= 2 && !/markdown|plain/i.test(where.language) ? ` ${where.language}` : ''
|
|
62
|
+
return { concept: words.slice(0, 6).join(' ').slice(0, 60), related: [], web: words.length <= 25 && !CODE_LIKE.test(selection),
|
|
63
|
+
query: `${words.slice(0, 10).join(' ')}${lang}`, code_terms: terms, math: false, quick: true }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const strList = (v, n, max) => (Array.isArray(v) ? v : []).map((t) => String(t).replace(/\s+/g, ' ').trim()).filter((t) => t.length >= 2 && t.length <= max).slice(0, n)
|
|
67
|
+
|
|
68
|
+
// JSON somewhere in the reply → object, or null
|
|
69
|
+
function parseJson(text) {
|
|
70
|
+
try { const m = /\{[\s\S]*\}/.exec(String(text || '')); return m ? JSON.parse(m[0]) : null } catch { return null }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function parsePlan(text, selection, where) {
|
|
74
|
+
const p = parseJson(text)
|
|
75
|
+
const concept = p ? String(p.concept || '').replace(/\s+/g, ' ').trim().slice(0, 60) : ''
|
|
76
|
+
if (!concept) return fallbackPlan(selection, where)
|
|
77
|
+
const query = String(p.query || '').replace(/\s+/g, ' ').trim().slice(0, 150)
|
|
78
|
+
return { concept, related: strList(p.related, 4, 60), web: p.web === true && !!query, query,
|
|
79
|
+
code_terms: strList(p.code_terms, 4, 120), math: p.math === true }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function answerMessages(selection, where, snippets, web, notes = []) {
|
|
83
|
+
const code = snippets.length
|
|
84
|
+
? snippets.map((s) => `\`${s.file}:${s.line}\`\n\`\`\`\n${s.code}\n\`\`\``).join('\n\n')
|
|
85
|
+
: '(none found)'
|
|
86
|
+
const sources = web.length ? web.map((w) => `- ${w.title} (${w.site}): ${w.snippet}`).join('\n') : '(not searched)'
|
|
87
|
+
return [
|
|
88
|
+
{ role: 'system', content: [
|
|
89
|
+
'You explain things to a student who learns by building. They selected text they did not understand.',
|
|
90
|
+
'Write in simple English: short sentences and everyday words, like talking to a friend. When you must use a technical word, say what it means in a few words.',
|
|
91
|
+
'At most 120 words, in this order:',
|
|
92
|
+
'1. One sentence: what it means.',
|
|
93
|
+
// with no snippets the step is left out: told "say nothing", Nemotron still wrote "Their code does not use this"
|
|
94
|
+
...(snippets.length ? ['2. How their own project uses or describes it, citing `path:line` from the snippets (their code and their notes). The first snippet is usually the place they selected from: use what is around it. Only when a snippet really is about this exact thing; otherwise skip this step without mentioning their project.'] : []),
|
|
95
|
+
`${snippets.length ? 3 : 2}. A tiny example or one more helpful detail.`,
|
|
96
|
+
'Use their code, the notes from earlier lookups and the web results together, as one explanation. Ignore any web result that is not about this exact thing. Never mention sources, searches, notes or models; just explain. If what you were given does not settle something, say so briefly instead of guessing.',
|
|
97
|
+
'Markdown allowed: **bold**, `code`, short lists, small fenced code blocks. No headings, no links. Write math as LaTeX between single $ signs ($L^2 d$) or $$...$$ on its own line; it is typeset. Never put math in `code`.',
|
|
98
|
+
].join('\n') },
|
|
99
|
+
{ role: 'user', content: [
|
|
100
|
+
`Window: ${whereLine(where)}`, '',
|
|
101
|
+
...(where && where.profile ? [`Project overview:\n${where.profile}`, ''] : []),
|
|
102
|
+
`Selected text:\n"""\n${selection.slice(0, MAX_SELECTION)}\n"""`, '',
|
|
103
|
+
...(snippets.length ? [`Their project files (code and notes; the first is usually where they selected from):\n${code}`, ''] : []),
|
|
104
|
+
`Notes from their earlier lookups:\n${notes.length ? notes.join('\n') : '(none)'}`, '',
|
|
105
|
+
`Web results:\n${sources}`,
|
|
106
|
+
].join('\n') },
|
|
107
|
+
]
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// A follow-up: the student read the explanation and still did not get it. `history` is their earlier follow-ups
|
|
111
|
+
// [{q, a}]. An empty question means "say it again, simpler". The explanation is sent as the model's own earlier reply.
|
|
112
|
+
function followupMessages(selection, where, snippets, web, notes, explanation, history, question) {
|
|
113
|
+
const [sys, user] = answerMessages(selection, where, snippets, web, notes)
|
|
114
|
+
const q = question.trim() || 'I did not understand. Explain it again in a simpler way.'
|
|
115
|
+
return [
|
|
116
|
+
{ role: 'system', content: [
|
|
117
|
+
sys.content.split('\n').slice(0, 2).join('\n'),
|
|
118
|
+
'The student read your explanation and is asking a follow-up because something is still unclear. Answer exactly what they ask, in at most 100 words.',
|
|
119
|
+
'Do not repeat the explanation. Use a different angle: a simpler word, a different everyday example, smaller steps, or a tiny number example. If they ask "why", give the reason; if they ask "how", give the steps.',
|
|
120
|
+
'If the question is not about the selected text or what you explained, answer it briefly anyway, or say you are not sure. Never mention sources, searches, notes or models. Never make things up: say what you do not know.',
|
|
121
|
+
'Markdown allowed: **bold**, `code`, short lists, small code blocks, math as $...$. No headings, no links.',
|
|
122
|
+
].join('\n') },
|
|
123
|
+
user,
|
|
124
|
+
{ role: 'assistant', content: String(explanation || '').slice(0, 6000) },
|
|
125
|
+
...history.slice(-4).flatMap((h) => [{ role: 'user', content: h.q || 'Explain it again, simpler.' }, { role: 'assistant', content: String(h.a || '').slice(0, 1500) }]),
|
|
126
|
+
{ role: 'user', content: q.slice(0, 500) },
|
|
127
|
+
]
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The "Explain in detail" window: the same inputs, a long explanation (1200-2000 words) under fixed sections.
|
|
131
|
+
// [heading, what goes in it, only when there are code snippets]
|
|
132
|
+
const DETAIL_SECTIONS = [
|
|
133
|
+
['In one line', 'a single sentence.'],
|
|
134
|
+
['The big picture', 'what it is, what problem it solves, and why people needed it. An everyday analogy that maps each part of the idea to something familiar.'],
|
|
135
|
+
['How it works', 'numbered steps, one idea per step, each with a sentence on why that step is there. Follow the data or the request from start to end.'],
|
|
136
|
+
['The math', 'the formula or numbers behind it, each symbol explained in words, then worked through with small real numbers. If there is no math, show the sizes, counts or costs involved instead.'],
|
|
137
|
+
['In your project', 'walk through their snippets (their code and notes) where they use or describe it, citing `path:line`, connect it to what the text around their selection says, and say what would change if they changed it. Leave this section out if no snippet really is about it.', true],
|
|
138
|
+
['Example', 'a small, complete code example or a worked example, with comments on every important line, and what it prints or produces.'],
|
|
139
|
+
['Compared with the alternatives', 'a short Markdown table of this idea against the two or three ideas it is usually compared with (what each does, when it wins, what it costs).'],
|
|
140
|
+
['Where it is used', 'real systems, libraries or models that use it, and what they get from it.'],
|
|
141
|
+
['Watch out for', 'common mistakes, limits and trade-offs, as a list, each with how to avoid it.'],
|
|
142
|
+
['Try it yourself', 'two or three small exercises or questions that check they really understood, with short answers.'],
|
|
143
|
+
['Related ideas', 'a list, one line each on how it connects and what to learn next.'],
|
|
144
|
+
['Recap', 'five short bullet points.'],
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
// Nemotron often drops the "## " and writes a section name as a plain line ("The math"), or as **The math:**.
|
|
148
|
+
// Any line that is just a section name becomes a ## heading again. Lines inside code blocks are left alone.
|
|
149
|
+
function fixHeadings(text) {
|
|
150
|
+
const names = new Map(DETAIL_SECTIONS.map(([h]) => [h.toLowerCase(), h]))
|
|
151
|
+
let inCode = false
|
|
152
|
+
return String(text || '').split('\n').map((line) => {
|
|
153
|
+
if (/^\s*```/.test(line)) { inCode = !inCode; return line }
|
|
154
|
+
if (inCode) return line
|
|
155
|
+
const bare = line.trim().replace(/^#{1,6}\s*/, '').replace(/^\*\*(.*)\*\*$/, '$1').replace(/:$/, '').trim().toLowerCase()
|
|
156
|
+
return names.has(bare) ? `## ${names.get(bare)}` : line
|
|
157
|
+
}).join('\n')
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function detailMessages(selection, where, snippets, web, notes = []) {
|
|
161
|
+
const [, user] = answerMessages(selection, where, snippets, web, notes)
|
|
162
|
+
return [
|
|
163
|
+
{ role: 'system', content: [
|
|
164
|
+
'You explain things to a student who learns by building. They selected text they did not understand and asked for the full, detailed explanation: everything worth knowing about this one idea, so they never need to look it up again.',
|
|
165
|
+
'Write in simple English: short sentences and everyday words. Explain every technical word the first time you use it, in a few words. Long is good here; vague is not. Every paragraph must teach something concrete.',
|
|
166
|
+
'Write 1200 to 2000 words with these ## headings, in this order. Start every section with its heading line, exactly as written here, beginning with "## ". Use ### subheadings inside a section when it has several parts.',
|
|
167
|
+
...DETAIL_SECTIONS.filter(([, , needsCode]) => !needsCode || snippets.length).map(([h, what]) => `## ${h}: ${what}`),
|
|
168
|
+
'Use their code, the notes from earlier lookups and the web results together. Ignore any web result that is not about this exact thing. Never mention sources, searches, notes or models. If what you were given does not settle something, say so instead of guessing.',
|
|
169
|
+
'Markdown: the headings above, ### subheadings, **bold**, `code`, lists, tables, fenced code blocks. No links. Write math as LaTeX between single $ signs inline ($L^2 d$), and each key formula as $$...$$ on its own line; it is typeset. Never put math in `code`.',
|
|
170
|
+
].join('\n') },
|
|
171
|
+
user,
|
|
172
|
+
]
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// The math clip's spec. These lines are the model-facing half of docs/CLIP_RULES.md; visual.checkSpec checks
|
|
176
|
+
// the reply, and the problems it finds come back here for one retry (R10).
|
|
177
|
+
function formulaMessages(concept, answer, selection = '', problems = []) {
|
|
178
|
+
return [
|
|
179
|
+
{ role: 'system', content: [
|
|
180
|
+
'You plan a short 3Blue1Brown-style animation that teaches one formula: it is typeset, written piece by piece, then each part in turn gets its own colour, a brace and a short note, and it ends on one takeaway line.',
|
|
181
|
+
'Reply with JSON only: {"title": string, "formula": string, "parts": [{"tex": string, "note": string}], "takeaway": string}.',
|
|
182
|
+
'Rules:',
|
|
183
|
+
'1. If the selected text contains a formula, the formula IS that formula, with the same symbols. Write it properly in LaTeX, but never swap in a different, simpler or "equivalent" formula. Only when the selection has no formula, use the standard formula for the idea.',
|
|
184
|
+
'2. formula: one line of LaTeX math, at most 110 characters, without $ signs. Use only: \\frac \\sqrt \\sum \\prod \\int \\log \\exp \\max \\min \\cdot \\times \\leq \\geq \\approx \\propto \\to \\in \\infty \\partial \\nabla \\top \\mathrm{} \\mathbf{} \\mathcal{} \\mathbb{} \\hat{} \\bar{} \\tilde{} \\vec{} and Greek letters. Names of functions go in \\mathrm{softmax}. Never write *, \\le, \\ge, \\left, \\right, \\text or \\operatorname.',
|
|
185
|
+
'3. parts: 1 to 4 pieces of the formula, in the order that teaches best (usually the piece that drives the result first). Each "tex" is copied character for character from the formula and is a whole group: a whole \\frac{..}{..}, a whole \\sqrt{..}, a symbol with its ^ and _ (N_L, d^2, x_i^2). Never a piece from inside { }, and parts never overlap.',
|
|
186
|
+
'4. note: at most 8 plain words saying what the part means or does ("every token looks at every other token"), never reading the symbols aloud ("L squared times d").',
|
|
187
|
+
'5. takeaway: one line, at most 70 characters, saying the consequence: how it scales, what it trades off, or what it guarantees. Not a summary title.',
|
|
188
|
+
'6. title: at most 5 words.',
|
|
189
|
+
'Example. Selected text: "Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) V". Reply:',
|
|
190
|
+
'{"title": "Scaled dot-product attention", "formula": "\\\\mathrm{softmax}(\\\\frac{QK^\\\\top}{\\\\sqrt{d_k}})V", "parts": [{"tex": "\\\\frac{QK^\\\\top}{\\\\sqrt{d_k}}", "note": "how well each query matches each key"}, {"tex": "\\\\mathrm{softmax}", "note": "scores become weights that add up to 1"}, {"tex": "V", "note": "mix the values using those weights"}], "takeaway": "Each token takes a weighted average of all values"}',
|
|
191
|
+
'(Same formula as the selection, now in LaTeX: softmax upright, the / as a \\\\frac, sqrt as \\\\sqrt, ^T as ^\\\\top.)',
|
|
192
|
+
'If the selected text has a formula, always reply with one; reply {"formula": ""} only when there is truly no formula to teach.',
|
|
193
|
+
].join('\n') },
|
|
194
|
+
{ role: 'user', content: [
|
|
195
|
+
`Topic: ${concept}`,
|
|
196
|
+
`Selected text:\n${String(selection).slice(0, 600)}`,
|
|
197
|
+
`Explanation:\n${String(answer).slice(0, 1500)}`,
|
|
198
|
+
...(problems.length ? [`Your last reply broke these rules; fix every one:\n${problems.map((p) => `- ${p.msg}`).join('\n')}`] : []),
|
|
199
|
+
].join('\n\n') },
|
|
200
|
+
]
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// reasoning models sometimes stream their thinking inside <think> tags; never show it
|
|
204
|
+
const hideThinking = (text) => String(text || '').replace(/<think>[\s\S]*?(<\/think>|$)/g, '').replace(/^\s+/, '')
|
|
205
|
+
|
|
206
|
+
// a failed reply → one plain sentence (Gemini wraps its error in a list, OpenAI-style APIs don't)
|
|
207
|
+
async function httpError(r) {
|
|
208
|
+
let e = {}
|
|
209
|
+
try { e = await r.json(); if (Array.isArray(e)) e = e[0] || {} } catch { /* not JSON */ }
|
|
210
|
+
const detail = (e.error && (e.error.status || e.error.code || e.error.message)) || ''
|
|
211
|
+
if (r.status === 402) return 'the free credit for this key has run out (HTTP 402). Run pocket-tutor doctor.'
|
|
212
|
+
if (r.status === 503) return 'the model is busy right now (HTTP 503). Try again in a minute.'
|
|
213
|
+
if (r.status === 429) return 'too many requests for this key (HTTP 429). Wait a minute and try again.'
|
|
214
|
+
if (r.status === 401 || r.status === 403 || /expired|invalid/i.test(detail)) return `the model key was refused (HTTP ${r.status}${detail ? `, ${detail}` : ''}). Run pocket-tutor doctor.`
|
|
215
|
+
return `HTTP ${r.status}${detail ? ` (${detail})` : ''}`
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// OpenAI-compatible chat. stream → onChunk(fullTextSoFar). json → asks for a JSON object where the API allows it.
|
|
219
|
+
// When the model stays busy, cfg.fallback_model gets one go; onFallback(name) says it was used.
|
|
220
|
+
async function chat(cfg, model, messages, opts = {}) {
|
|
221
|
+
const { json = false, onChunk = null, maxTokens = 700, timeoutMs = 60000, onFallback = null } = opts
|
|
222
|
+
const body = { model, messages, temperature: 0.2, max_tokens: maxTokens, stream: !!onChunk }
|
|
223
|
+
// keep thinking short. Only Groq's gpt-oss gets response_format; for the others parseJson finds the JSON in plain text
|
|
224
|
+
if (/^openai\/gpt-oss|^gemini/.test(model)) body.reasoning_effort = 'low'
|
|
225
|
+
// Nemotron through Vercel AI Gateway: thinking off. With effort "low" it still thought for ~500 tokens
|
|
226
|
+
// (up to 19 s) and on long prompts used the whole max_tokens, leaving the answer empty. Off: ~0.6 s.
|
|
227
|
+
if (/^nvidia\//.test(model)) body.reasoning = { enabled: false }
|
|
228
|
+
if (json && /^openai\/gpt-oss/.test(model)) body.response_format = { type: 'json_object' }
|
|
229
|
+
const ctl = new AbortController()
|
|
230
|
+
const timer = setTimeout(() => ctl.abort(), timeoutMs)
|
|
231
|
+
try {
|
|
232
|
+
let r
|
|
233
|
+
// "busy" (503) and "slow down" (429): with a fallback model, hand over at once; without one, try twice more
|
|
234
|
+
const canFallBack = !!cfg.fallback_model && cfg.fallback_model !== model
|
|
235
|
+
for (let attempt = 0; ; attempt++) {
|
|
236
|
+
r = await fetch(`${cfg.base_url.replace(/\/$/, '')}/chat/completions`, { method: 'POST', signal: ctl.signal,
|
|
237
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${cfg.llm_key}` }, body: JSON.stringify(body) })
|
|
238
|
+
// Servers differ on which parameters they accept. On a 400, read why, change that one parameter and ask again:
|
|
239
|
+
// newer OpenAI models want max_completion_tokens and a default temperature; some models refuse a reasoning setting.
|
|
240
|
+
if (r.status === 400 && attempt < 4) {
|
|
241
|
+
const why = await r.clone().text().catch(() => '')
|
|
242
|
+
if (/max_completion_tokens/.test(why) && body.max_tokens) { body.max_completion_tokens = body.max_tokens; delete body.max_tokens; continue }
|
|
243
|
+
if (/temperature/i.test(why) && 'temperature' in body) { delete body.temperature; continue }
|
|
244
|
+
if (/reasoning/i.test(why) && (body.reasoning || body.reasoning_effort)) { delete body.reasoning; delete body.reasoning_effort; continue }
|
|
245
|
+
if (/response_format/i.test(why) && body.response_format) { delete body.response_format; continue }
|
|
246
|
+
if (body.reasoning || body.reasoning_effort) { delete body.reasoning; delete body.reasoning_effort; continue }
|
|
247
|
+
}
|
|
248
|
+
if (r.ok || ![429, 503].includes(r.status) || canFallBack || attempt >= 2) break
|
|
249
|
+
await new Promise((res) => setTimeout(res, 1200 * (attempt + 1)))
|
|
250
|
+
}
|
|
251
|
+
if (!r.ok && [429, 503].includes(r.status) && canFallBack) {
|
|
252
|
+
clearTimeout(timer)
|
|
253
|
+
if (onFallback) onFallback(cfg.fallback_model)
|
|
254
|
+
return await chat(cfg, cfg.fallback_model, messages, opts)
|
|
255
|
+
}
|
|
256
|
+
if (!r.ok) throw new Error(await httpError(r))
|
|
257
|
+
// an empty reply is a failure, not a blank box
|
|
258
|
+
const nonEmpty = (t) => { const out = hideThinking(t); if (!out.trim()) throw new Error('the model sent back an empty reply. Try again.'); return out }
|
|
259
|
+
if (!onChunk) return nonEmpty((await r.json()).choices[0].message.content || '')
|
|
260
|
+
let text = '', buf = ''
|
|
261
|
+
const dec = new TextDecoder()
|
|
262
|
+
for await (const chunk of r.body) {
|
|
263
|
+
buf += dec.decode(chunk, { stream: true })
|
|
264
|
+
let nl
|
|
265
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
266
|
+
const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1)
|
|
267
|
+
if (!line.startsWith('data:')) continue
|
|
268
|
+
const data = line.slice(5).trim()
|
|
269
|
+
if (data === '[DONE]') return nonEmpty(text)
|
|
270
|
+
try {
|
|
271
|
+
const piece = JSON.parse(data).choices[0].delta.content || ''
|
|
272
|
+
if (piece) { text += piece; const shown = hideThinking(text); if (shown) onChunk(shown) }
|
|
273
|
+
} catch { /* keep-alive or partial line */ }
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return nonEmpty(text)
|
|
277
|
+
} catch (e) {
|
|
278
|
+
if (e.name === 'AbortError') throw new Error(`the model took longer than ${Math.round(timeoutMs / 1000)} s. Try again.`)
|
|
279
|
+
throw e
|
|
280
|
+
} finally { clearTimeout(timer) }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
module.exports = { planMessages, parsePlan, fallbackPlan, quickPlan, answerMessages, followupMessages, detailMessages, fixHeadings, formulaMessages, parseJson, hideThinking, chat, MAX_SELECTION }
|
package/src/native.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Talks to helper.ps1: one command line out, one JSON line back, in order.
|
|
2
|
+
const { spawn } = require('child_process')
|
|
3
|
+
const path = require('path')
|
|
4
|
+
const readline = require('readline')
|
|
5
|
+
|
|
6
|
+
class Native {
|
|
7
|
+
constructor(log = console.error) {
|
|
8
|
+
this.log = log
|
|
9
|
+
this.waiting = []
|
|
10
|
+
this.ready = new Promise((resolve) => { this._ready = resolve })
|
|
11
|
+
this._start()
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
_start() {
|
|
15
|
+
this.ps = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', path.join(__dirname, 'helper.ps1')],
|
|
16
|
+
{ windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] })
|
|
17
|
+
readline.createInterface({ input: this.ps.stdout }).on('line', (line) => {
|
|
18
|
+
let msg
|
|
19
|
+
try { msg = JSON.parse(line) } catch { return }
|
|
20
|
+
if (msg.ready) return this._ready()
|
|
21
|
+
const w = this.waiting.shift()
|
|
22
|
+
if (w) { clearTimeout(w.timer); msg.error ? w.reject(new Error(msg.error)) : w.resolve(msg) }
|
|
23
|
+
})
|
|
24
|
+
this.ps.stderr.on('data', (d) => this.log(`[helper] ${d.toString().trim()}`))
|
|
25
|
+
this.ps.on('exit', () => {
|
|
26
|
+
for (const w of this.waiting.splice(0)) { clearTimeout(w.timer); w.reject(new Error('helper stopped')) }
|
|
27
|
+
if (!this.stopped) { this.ready = new Promise((resolve) => { this._ready = resolve }); setTimeout(() => this._start(), 1000) }
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async call(cmd, timeoutMs = 4000) {
|
|
32
|
+
await this.ready
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
// a late answer would be handed to the next caller, so a timeout restarts the helper instead
|
|
35
|
+
const timer = setTimeout(() => {
|
|
36
|
+
this.waiting = this.waiting.filter((w) => w.timer !== timer)
|
|
37
|
+
reject(new Error(`helper timeout: ${cmd}`))
|
|
38
|
+
this.ps.kill()
|
|
39
|
+
}, timeoutMs)
|
|
40
|
+
this.waiting.push({ resolve, reject, timer })
|
|
41
|
+
this.ps.stdin.write(cmd + '\n')
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
foreground() { return this.call('fg') }
|
|
46
|
+
copy(terminal = false) { return this.call(terminal ? 'copyterminal' : 'copy') }
|
|
47
|
+
stop() { this.stopped = true; if (this.ps) this.ps.kill() }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
module.exports = { Native }
|
package/src/place.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Where the box goes and how big it is. Pure, tested in test/pure.test.js.
|
|
2
|
+
const GAP = 14
|
|
3
|
+
|
|
4
|
+
// just below-right of the cursor, flipped and clamped so it stays on the screen the cursor is on
|
|
5
|
+
function placeNear(cursor, size, area) {
|
|
6
|
+
let x = cursor.x + GAP
|
|
7
|
+
let y = cursor.y + GAP
|
|
8
|
+
if (x + size.w > area.x + area.width) x = cursor.x - GAP - size.w
|
|
9
|
+
if (y + size.h > area.y + area.height) y = cursor.y - GAP - size.h
|
|
10
|
+
x = Math.max(area.x, Math.min(x, area.x + area.width - size.w))
|
|
11
|
+
y = Math.max(area.y, Math.min(y, area.y + area.height - size.h))
|
|
12
|
+
return { x: Math.round(x), y: Math.round(y) }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// The box is always wider than tall and as long as the text needs.
|
|
16
|
+
// contentH: the content's height at the current width w. When it would be taller than RATIO × w, the box
|
|
17
|
+
// widens a step; the text reflows, the page reports again, and this runs again. Only at maxW does it scroll.
|
|
18
|
+
// work: the size it opens at and keeps while the answer is written (a typical answer ends up close to it)
|
|
19
|
+
const BOX = { minW: 420, maxW: 960, step: 90, ratio: 0.72, minH: 96, work: { w: 460, h: 250 } } // ratio: at most about 3:4 high, clearly landscape
|
|
20
|
+
|
|
21
|
+
function fitBox(contentH, w, maxW = BOX.maxW) {
|
|
22
|
+
const top = Math.max(BOX.minW, Math.min(maxW, BOX.maxW))
|
|
23
|
+
let width = Math.max(BOX.minW, Math.min(w, top))
|
|
24
|
+
if (contentH > width * BOX.ratio && width < top) width = Math.min(top, width + BOX.step)
|
|
25
|
+
const height = Math.round(Math.max(BOX.minH, Math.min(contentH, width * BOX.ratio)))
|
|
26
|
+
return { w: width, h: height }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
module.exports = { placeNear, fitBox, BOX }
|
package/src/preload.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The only things the box's page can ask the main process to do.
|
|
2
|
+
const { contextBridge, ipcRenderer } = require('electron')
|
|
3
|
+
|
|
4
|
+
contextBridge.exposeInMainWorld('lens', {
|
|
5
|
+
onState: (cb) => ipcRenderer.on('state', (_e, data) => cb(data)),
|
|
6
|
+
onMode: (cb) => ipcRenderer.on('mode', (_e, mode) => cb(mode === 'min' ? 'min' : 'full')),
|
|
7
|
+
openUrl: (url) => ipcRenderer.send('open-url', String(url)),
|
|
8
|
+
openCode: (file, line) => ipcRenderer.send('open-code', { file: String(file), line: Number(line) }),
|
|
9
|
+
close: () => ipcRenderer.send('close'),
|
|
10
|
+
fit: (height, width) => ipcRenderer.send('fit', { height: Number(height), width: Number(width) }),
|
|
11
|
+
minimize: () => ipcRenderer.send('minimize'),
|
|
12
|
+
restore: () => ipcRenderer.send('restore'),
|
|
13
|
+
openDetail: () => ipcRenderer.send('detail'),
|
|
14
|
+
ask: (question, view) => ipcRenderer.send('ask', { question: String(question || ''), view: view === 'detail' ? 'detail' : 'box' }),
|
|
15
|
+
onDetail: (cb) => ipcRenderer.on('detail', (_e, data) => cb(data)),
|
|
16
|
+
closeDetail: () => ipcRenderer.send('detail-close'),
|
|
17
|
+
})
|
package/src/privacy.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// What Pocket Tutor refuses to read, and what it masks before anything leaves the laptop.
|
|
2
|
+
// Pure functions, tested in test/privacy.test.js.
|
|
3
|
+
|
|
4
|
+
// apps whose selected text is never copied
|
|
5
|
+
const BLOCKED_APPS = new Set(['1password', 'keepass', 'keepassxc', 'bitwarden', 'dashlane', 'lastpass', 'enpass', 'keeper', 'proton pass', 'protonpass'])
|
|
6
|
+
const PRIVATE_TITLE = /\b(InPrivate|Incognito|Private Browsing)\b/i
|
|
7
|
+
|
|
8
|
+
function blocked(app, title) {
|
|
9
|
+
if (BLOCKED_APPS.has(String(app || '').toLowerCase())) return 'a password manager'
|
|
10
|
+
if (PRIVATE_TITLE.test(String(title || ''))) return 'a private browser window'
|
|
11
|
+
return null
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// files whose contents never go into the code context
|
|
15
|
+
const SECRET_FILE = /(^|[\\/])(\.env(\..*)?|.*\.(pem|key|p12|pfx|keystore|jks)|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|credentials(\.json)?|secrets?\.(json|ya?ml|toml)|\.npmrc|\.pypirc|\.netrc)$/i
|
|
16
|
+
|
|
17
|
+
function secretFile(file) {
|
|
18
|
+
return SECRET_FILE.test(String(file || ''))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const MASKS = [
|
|
22
|
+
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[private key]'],
|
|
23
|
+
[/\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}\b/g, '[token]'], // JWT
|
|
24
|
+
[/\b(sk|gsk|pk|rk)[-_](live_|test_|proj-|ant-)?[A-Za-z0-9_-]{16,}\b/g, '[key]'], // OpenAI, Groq, Stripe, Anthropic style
|
|
25
|
+
[/\b(ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_]{20,}\b/g, '[key]'],
|
|
26
|
+
[/\bAKIA[0-9A-Z]{16}\b/g, '[key]'],
|
|
27
|
+
[/\bAIza[0-9A-Za-z_-]{30,}\b/g, '[key]'],
|
|
28
|
+
[/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g, '[key]'],
|
|
29
|
+
[/\b((?:api[_-]?key|secret|token|password|passwd|pwd)\s*[:=]\s*)(["']?)[^\s"']{6,}\2/gi, '$1$2[hidden]$2'],
|
|
30
|
+
[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '[email]'],
|
|
31
|
+
[/\b[A-Fa-f0-9]{40,}\b/g, '[hex]'],
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
function mask(text) {
|
|
35
|
+
let s = String(text || '')
|
|
36
|
+
for (const [re, to] of MASKS) s = s.replace(re, to)
|
|
37
|
+
return s
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
module.exports = { blocked, secretFile, mask }
|