Pasek nad promptem: kontekst, odliczanie cache, koszt sesji, przyciski Handoff i Wyczyść i kontynuuj

Tu leży wszystko, co rozdaję na kanale. Za darmo, bez zapisywania się na cokolwiek.
Jak pobrać: kliknij zielony przycisk Code u góry, potem Download ZIP. Rozpakuj na pulpit. Nie musisz wiedzieć, co to GitHub — wystarczy ten jeden przycisk.
Skill to instrukcja, którą AI wykona. W czymkolwiek ściągniętym z internetu może być napisane wszystko. Sprawdzaj każdą paczkę, zanim ją wrzucisz. Moją też.
Paczka leży jeszcze w zwykłym folderze na pulpicie, więc otwórz nową rozmowę z AI w tym folderze i wklej:
Zanim tego użyję: przeczytaj te pliki jak zwykły tekst i powiedz mi po ludzku,
co ta instrukcja każe robić. Czy każe coś kasować, wysyłać gdzieś dane,
uruchamiać komendy albo grzebać poza swoim folderem?
Zasada kciuka: jeśli w instrukcji jest „wyślij", „skasuj" albo „uruchom" coś, czego nie rozumiesz — nie instalujesz. Nie musisz rozumieć wszystkiego. Wystarczy, że wiesz, kiedy powiedzieć „nie".
To nie jest kontrola pancerna, ale wyłapuje zdecydowaną większość śmieci. Różnica jak między wzięciem cukierka od obcego a przeczytaniem składu.
| Folder | Co to robi | Odcinek |
|---|---|---|
ghost/ | AI pisze maile i wiadomości twoim stylem, a nie jak robot | „Nauczyłem AI pisać jak ja" |
handoff/ | Kończysz rozmowę tak, żeby nowa wiedziała, na czym stanęliście — mniej zużytego limitu | „Znowu masz limit" |
krotko/ | Jedno słowo i z długiej odpowiedzi AI zostaje kilka zdań po ludzku | „AI gada za dużo" |
mody-limit/ | Trzech pomocników w Claude Code: pasek zużycia w kolorach, przycinanie gadatliwych wyników, stop dla AI kręcącego się w kółko | (odcinek w przygotowaniu) |
Każdy folder ma własny README.md z instrukcją krok po kroku.
Napisz w komentarzu pod odcinkiem — czytam wszystkie i z powtarzających się pytań robię następne filmy.
hooks/register.tsx 283 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, FsEntry, Register, RenderSurface } from 'claude-code'
3
4import type { Handoff } from '../types'
5
6// Cache promptu w tej sesji żyje 60 min od ostatniego zapytania.
7// Po wygaśnięciu następna wiadomość płaci za cały kontekst od nowa.
8const CACHE_TTL_MS = 60 * 60 * 1000
9const WARN_BEFORE_MS = 5 * 60 * 1000
10const MINUTE_MS = 60 * 1000
11
12const lastActivity = atom({ plugin: 'straznik-cache', key: 'lastActivity' } as const, null)
13const tick = atom({ plugin: 'straznik-cache', key: 'tick' } as const, 0)
14const isWarned = atom({ plugin: 'straznik-cache', key: 'isWarned' } as const, false)
15const isHidden = atom({ plugin: 'straznik-cache', key: 'isHidden' } as const, false)
16const handoff = atom({ plugin: 'straznik-cache', key: 'handoff' } as const, null)
17
18// Progi kolorów: zielony → pomarańczowy → czerwony.
19const CONTEXT_ORANGE_PERCENT = 50
20const CONTEXT_RED_PERCENT = 75
21const CACHE_ORANGE_MS = 15 * 60 * 1000
22const LIMIT_ORANGE_PERCENT = 60
23const LIMIT_RED_PERCENT = 85
24
25// Klucze motywu: same dopasowują się do jasnego i ciemnego trybu.
26type Level = 'success' | 'warning' | 'error'
27const byPercent = (percent: number, orange: number, red: number): Level =>
28 percent >= red ? 'error' : percent >= orange ? 'warning' : 'success'
29const byTimeLeft = (left: number): Level =>
30 left <= WARN_BEFORE_MS ? 'error' : left <= CACHE_ORANGE_MS ? 'warning' : 'success'
31
32const thousands = (tokens: number) => `${Math.round(tokens / 1000)}k`
33
34export const register: Register = on => {
35 on('session.start', async ($, e, next) => {
36 // Nowy proces wznowionej sesji: $.state jest pusty, ale cache na serwerze żyje dalej.
37 if ((await read($, lastActivity)) === null) {
38 const saved = await recallLastAnswer($)
39 if (saved !== null) {
40 await update($, lastActivity, () => saved)
41 }
42 }
43
44 await $.command.register({
45 name: 'straznik',
46 description: 'Pokaż albo schowaj pasek Strażnika cache',
47 })
48
49 $.clock.every(MINUTE_MS, async () => {
50 await update($, tick, n => n + 1)
51
52 const last = await read($, lastActivity)
53 if (last === null || (await read($, isWarned))) {
54 return
55 }
56
57 const left = last + CACHE_TTL_MS - (await $.clock.now())
58 if (left > 0 && left <= WARN_BEFORE_MS) {
59 await update($, isWarned, () => true)
60 const { context } = await $.session.usage()
61 const size = context.tokens ? ` (${thousands(context.tokens)} tokenów)` : ''
62 const text = `Cache tej sesji${size} wygasa za ${Math.ceil(left / MINUTE_MS)} min. Napisz coś albo zrób handoff.`
63 $.ui.toast(text, { timeoutMs: 15000 })
64 // Powiadomienie systemowe bywa niedostępne (np. bez terminala) — toast wystarczy.
65 try {
66 await $.ui.notify(text, { title: 'Strażnik cache' })
67 } catch {}
68 }
69 })
70
71 return next(e)
72 })
73
74 on('command.run', { command: 'straznik' }, async $ => {
75 const hidden = await update($, isHidden, was => !was)
76
77 return { text: hidden ? 'Pasek Strażnika schowany.' : 'Pasek Strażnika widoczny.' }
78 })
79
80 on('session.end', async ($, e, next) => {
81 if (e.reason === 'clear') {
82 isCleared = true
83 }
84
85 return next(e)
86 })
87
88 on('turn.complete', async ($, e, next) => {
89 if (e.agentId !== undefined) {
90 return next(e)
91 }
92
93 const now = await $.clock.now()
94 await update($, lastActivity, () => now)
95 await update($, isWarned, () => false)
96 await rememberLastAnswer($, now)
97
98 const pending = await read($, handoff)
99 if (pending !== null && pending.file === null) {
100 const file = await newestHandoff($, pending.requestedAt)
101 if (file !== null) {
102 await update($, handoff, () => ({ ...pending, file }))
103 }
104 }
105
106 return next(e)
107 })
108
109 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
110 if (e.props.hasSurvey || (await read($, isHidden))) {
111 return next(e)
112 }
113
114 await read($, tick)
115 // last === null: sesja jeszcze bez odpowiedzi — pasek już jest, ale cache nie liczy.
116 const last = await read($, lastActivity)
117
118 const { Box, Button, Text } = $.ui.resolve(e)
119 const { context, cost, rateLimits } = await $.session.usage()
120 const left = last === null ? 0 : last + CACHE_TTL_MS - (await $.clock.now())
121 const pending = await read($, handoff)
122
123 // level === undefined: kawałek bez koloru (koszt sesji), przygaszony.
124 const parts: { text: string; level?: Level }[] = []
125 if (context.percent !== undefined && context.tokens !== undefined) {
126 parts.push({
127 text: `kontekst ${context.percent}% (${thousands(context.tokens)})`,
128 level: byPercent(context.percent, CONTEXT_ORANGE_PERCENT, CONTEXT_RED_PERCENT),
129 })
130 }
131 parts.push(
132 last === null
133 ? { text: 'cache ruszy po pierwszej odpowiedzi' }
134 : {
135 text:
136 left > 0
137 ? `cache ${Math.ceil(left / MINUTE_MS)} min`
138 : 'cache wygasł — następna wiadomość czyta wszystko od nowa',
139 level: byTimeLeft(left),
140 },
141 )
142 if (cost !== undefined) {
143 parts.push({ text: `sesja $${cost.usd.toFixed(2)}` })
144 }
145 const fiveHour = rateLimits.find(limit => limit.kind === 'five_hour')
146 if (fiveHour !== undefined) {
147 parts.push({
148 text: `limit 5h ${fiveHour.percentUsed}%`,
149 level: byPercent(fiveHour.percentUsed, LIMIT_ORANGE_PERCENT, LIMIT_RED_PERCENT),
150 })
151 }
152
153 return (
154 <Box>
155 <Text>
156 {parts.flatMap((part, i) => [
157 ...(i > 0 ? [<Text dimColor>{' · '}</Text>] : []),
158 part.level === undefined
159 ? <Text dimColor>{part.text}</Text>
160 : <Text color={part.level}>{part.text}</Text>,
161 ])}{' '}
162 </Text>
163 {!e.props.isWorking && last !== null && pending?.file == null && (
164 <Button
165 key="handoff"
166 label="Handoff"
167 onPress={() => startHandoff($)}
168 />
169 )}
170 {!e.props.isWorking && pending?.file != null && (
171 <Button
172 key="clear"
173 label="Wyczyść i kontynuuj"
174 onPress={() => clearAndContinue($, e.surface, pending.file ?? '')}
175 />
176 )}
177 </Box>
178 )
179 })
180}
181
182// $.state ginie razem z procesem, a aplikacja usypia nieużywane sesje i budzi je
183// nowym procesem. Dlatego czas ostatniej odpowiedzi każdej sesji trzymamy też
184// w $.store; wpisy starsze niż cache i tak nic już nie mówią, więc je sprzątamy.
185const LAST_ANSWERS_KEY = 'ostatniaOdpowiedz'
186
187// Zapis to dodatek: gdy store albo id sesji zawiodą, pasek działa dalej jak dotąd.
188async function savedAnswers($: EngineInterface): Promise<Record<string, number>> {
189 const saved = await $.store.get(LAST_ANSWERS_KEY)
190 return typeof saved === 'object' && saved !== null ? (saved as Record<string, number>) : {}
191}
192
193async function rememberLastAnswer($: EngineInterface, now: number) {
194 try {
195 const id = await $.session.id()
196 const fresh = Object.entries(await savedAnswers($)).filter(([, at]) => now - at < CACHE_TTL_MS)
197 await $.store.set(LAST_ANSWERS_KEY, { ...Object.fromEntries(fresh), [id]: now })
198 } catch {}
199}
200
201async function recallLastAnswer($: EngineInterface): Promise<number | null> {
202 try {
203 const id = await $.session.id()
204 return (await savedAnswers($))[id] ?? null
205 } catch {
206 return null
207 }
208}
209
210// Ustawiane przez session.end, gdy /clear naprawdę wyczyścił rozmowę.
211let isCleared = false
212
213// prompt.submit nie przyjmuje tekstu zaczynającego się od „/”, więc skill
214// odpalamy jako komendę; gdyby nie przeszła, wysyłamy zwykłe zdanie.
215async function startHandoff($: EngineInterface) {
216 const now = await $.clock.now()
217 const pending = await read($, handoff)
218 if (pending !== null && pending.file === null && now - pending.requestedAt < 2 * MINUTE_MS) {
219 $.ui.toast('Handoff już się robi — poczekaj na kartkę.')
220 return
221 }
222
223 await update($, handoff, (): Handoff => ({ requestedAt: now, file: null }))
224 $.ui.toast('Robię handoff…')
225
226 const ran = await $.command.run({ command: 'handoff' }).catch(err => ({ error: String(err) }))
227 if (!('error' in ran)) {
228 return
229 }
230
231 const sent = await $.prompt
232 .submit({ text: 'Zrób handoff tej sesji (skill handoff).', asUser: true })
233 .catch(err => ({ error: String(err) }))
234 if ('error' in sent || sent.drop !== undefined) {
235 await update($, handoff, () => null)
236 $.ui.toast('Nie udało się uruchomić handoffu z paska — wpisz /handoff ręcznie.', { timeoutMs: 15000 })
237 }
238}
239
240async function clearAndContinue($: EngineInterface, surface: RenderSurface, file: string) {
241 const line = `Przeczytaj \`${file}\` i wracamy do roboty.`
242
243 // Schowek najpierw: to jest wyjście awaryjne, gdyby /clear z moda nie przeszedł.
244 await $.ui.copy({ text: line, surface }).catch(() => undefined)
245
246 isCleared = false
247 await $.command.run({ command: 'clear' }).catch(() => undefined)
248
249 if (!isCleared) {
250 $.ui.toast('Mod nie zdołał wyczyścić rozmowy. Linijka jest w schowku: wpisz /clear, potem wklej (Ctrl+V).', { timeoutMs: 20000 })
251 return
252 }
253
254 await update($, handoff, () => null)
255 await update($, lastActivity, () => null)
256 const sent = await $.prompt.submit({ text: line, asUser: true }).catch(err => ({ error: String(err) }))
257 if ('error' in sent || sent.drop !== undefined) {
258 await $.prompt.fill({ text: line }).catch(() => undefined)
259 }
260}
261
262// Najnowsza kartka zapisana po kliknięciu Handoff. Skill handoff zapisuje ją
263// w folderze projektu (`handoff\`) albo w `~/.claude/handoff` — szukamy w obu.
264async function newestHandoff($: EngineInterface, since: number): Promise<string | null> {
265 const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
266 const places = [
267 { dir: 'handoff', shown: 'handoff/' },
268 ...(home === undefined ? [] : [{ dir: `${home}/.claude/handoff`, shown: '~/.claude/handoff/' }]),
269 ]
270
271 const found: { path: string; mtimeMs: number }[] = []
272 for (const place of places) {
273 const entries: FsEntry[] = await $.fs.list(place.dir).catch(() => [])
274 for (const entry of entries) {
275 if (entry.kind === 'file' && entry.name.endsWith('.md') && entry.mtimeMs >= since) {
276 found.push({ path: `${place.shown}${entry.name}`, mtimeMs: entry.mtimeMs })
277 }
278 }
279 }
280
281 return found.sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.path ?? null
282}
283types/index.d.ts 22 lines1export type Handoff = {
2 /** Kiedy kliknięto Handoff (ms od epoki). */
3 requestedAt: number
4 /** Ścieżka kartki (`handoff/…md` w projekcie albo `~/.claude/handoff/…md`), gdy już powstała. */
5 file: string | null
6}
7
8declare module 'claude-code' {
9 interface PluginState {
10 'straznik-cache': {
11 /** Koniec ostatniej tury głównej rozmowy (ms od epoki); null przed pierwszą. */
12 lastActivity: number | null
13 /** Licznik minut, żeby pasek przerysował odliczanie. */
14 tick: number
15 /** Czy ostrzeżenie „cache wygasa” już poszło dla tej przerwy. */
16 isWarned: boolean
17 isHidden: boolean
18 handoff: Handoff | null
19 }
20 }
21}
22