SLOPSHOPPER

tokenbreak

Opt-in ads for Claude Code: a banner above the prompt and a Theater pane while Claude works. Unofficial, not affiliated with Anthropic.

panebandcommandtoaststatusnetwork
v0.6.0MITupdated 2026-10-13steven-3/tokenbreak/plugins/tokenbreak
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · tokenbreak
│ ┃ tokenbreak-theater ✕ › fix the failing auth test and add an audit log call │ ┃ ▣ Tokenbreak: Your brand here, while Claude │ ┃ ⏺ Read(src/auth.ts) │ ┃ Tokenbreak Ad ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ Your brand here, while Claude works. ⎿ Added 2 lines, removed 1 line │ ┃ Founding slots open. ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ https://tokenbreak.dev/formats │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ Closes when Claude finishes · /ads pause │ ┃ hides ads ✻ Worked for 42s · done 4:20 PM │ │ › /ads │ ⎿ tokenbreak: Tokenbreak · on │ ⎿ tokenbreak: Account: signed out. /ads login links your GitHub ac │ ⎿ tokenbreak: Showing: nothing │ ⎿ tokenbreak: Ads from: built-in house ads (ad server unreachable) │ ⎿ tokenbreak: Banner: during turns and 30s after; none under 80 co │ ⎿ tokenbreak: Version: 0.6.0, the latest │ │ ▚ Tokenbreak is signed out. Run /ads login to show ads and earn. ✕ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▚ Tokenbreak is signed out. Run /ads login to show ads and earn. ✕
Pane · tokenbreak-theater
▣ Tokenbreak: Your brand here, while Claude works. Founding Tokenbreak Ad Your brand here, while Claude works. Founding slots open. https://tokenbreak.dev/formats Closes when Claude finishes · /ads pause hides ads
README

Tokenbreak for Claude Code

Opt-in ads in Claude Code. Tokenbreak is unofficial and not affiliated with Anthropic.

  • Prompt Banner: a one-line ad above the prompt, a blank row above it, that rotates every 20, 40 or 90 seconds. It shows while Claude works on a turn and for 30 seconds after the turn ends, then hides until your next prompt, so there's no ad above a prompt you're typing. Terminals under 80 columns get no banner at all. The brand's logo (a tiny 36×36 picture, or a colored character where pictures are off) and its name and headline open the ad, beside a call-to-action button in the brand's color (the advertiser's pick, Learn more by default), a dim Ad label and ✕. On a narrow terminal only the headline gives way, cut with …; the band stays one row.
  • ✕ hides that advertiser on this machine for 30 days and moves to the next ad. The hide stays in the plugin's local store with its end date, and the server gets a hide report (advertisers see a count). To turn every ad off, use /ads pause.
  • Theater: a pane beside the transcript while Claude works. It only opens in the fullscreen layout, at 144+ columns, once a turn has run for 3 seconds, and it closes when the turn ends. If you close it yourself, it stays away for 30 minutes. It shows the current banner brand's Theater ad when there is one. A video ad can come in several cuts (vertical, landscape); the Theater plays the one that fills the pane best, stacked over the text or beside it. The Theater never plays sound.
  • /ads: login, logout, status, update, next, style [pill|rule|card], pause [1h|30m|2h|today], resume, report [scam|misleading|offensive|broken|other] [note].
  • report sends the paid ad on screen (or the last one that was) to Tokenbreak for a person to review, with the reason (other when you don't give one) and any note you type. Reports of one campaign from three developers within 7 days pause it until it's reviewed. Offline, the report waits on this machine and goes once the server can be reached.
  • status says whether this version is current, and how to turn on auto-update.

Signing in

Tokenbreak shows ads only to a signed-in account. Until you run /ads login, the band above the prompt shows one dim line saying so (✕ hides it for the day), the Theater stays shut, and nothing is fetched or counted.

/ads login asks the site for a short code and prints a link. Open it, sign in with GitHub, check the code matches and approve; the mod polls the site meanwhile and picks up the session within seconds. The session token stays in the plugin's store on this machine and lasts 30 days from last use. /ads logout sends what's queued, ends the session on the site and forgets it. If the site stops honoring the token, the mod signs itself out.

The first sign-in on a machine opens with a welcome card in the banner's place: what ✕ does, /ads pause, where your earnings show (tokenbreak.dev/dashboard/earn) and how to turn on auto-update. It stays until the end of your next turn (and its 30 seconds after), or until you press its ✕, and it never comes back on that machine. It's Tokenbreak's own card, so it pays nothing and nothing is counted.

During the launch beta only the first developers hold an earning seat. Until yours is granted, the server sends Tokenbreak's own house ads, and a line under the banner says: "You're on the list for an earning seat. Ads you see now don't pay yet." House ads are never counted.

What it never does

Tokenbreak hooks no event that reads or shapes the conversation: no prompt.compose, session.append, tool.call, tool.check or turn.step. It makes no call that reads files, prompts or the transcript. From turn.start it reads the turn's id; from turn.complete, the turn's id and whether it was a subagent's (those are skipped). Nothing else. tests/privacy.test.ts checks this against the engine's own scan of the module, and fails if the mod ever hooks an event not on its list.

It doesn't step aside for permission prompts either. Claude Code's mod API has no event for "a dialog is open" that leaves the conversation out: the only ones (the classic PermissionRequest and Notification hooks) carry the tool's input or the prompt's text. Reading them to hide an ad would break this promise, so the mod doesn't.

Ads never enter the model's context, so they cost you no tokens.

What it sends

Every request carries your session token as Authorization: Bearer. The token ties what's sent to your account. deviceId is a random UUID created on first run, which tells your machines apart. Nothing else about you, your code or your conversation is sent.

  • GET {endpoint}/api/v1/ads?formats=banner,theater fetches ads, at session start and when the batch runs out (10 minutes by default). Headers: X-Tokenbreak-Device (the deviceId), X-Tokenbreak-Version (this build's version) and X-Tokenbreak-Surface (terminal, or desktop for the desktop app's Code tab).
  • POST {endpoint}/api/v1/turns sends { deviceId, surface }, with the same headers, when one of your turns starts. The server answers with a signed turn token, so it knows a real turn began and when. Paid impressions need one.
  • It never holds your turn up. It's sent in the background, and an answer later than 3 seconds is ignored.
  • A turn with no token (offline, an error, or a 429 because turns came too fast) still shows ads. It just reports nothing paid.
  • It isn't sent within 10 seconds of the last one (the server refuses those anyway), while ads are paused, or while you're waiting for an earning seat.
  • POST {endpoint}/api/v1/impressions sends { deviceId, modVersion, impressions: [{ adId, format, at, turnId, serveToken, turnToken, surface, shownMs }] }, in batches of up to 200, once 20 are queued or every 5 minutes.
  • Counted when the turn ends: at most one banner (the paid one on screen longest) and one Theater ad per turn.
  • A banner counts after 1 continuous second on screen and the Theater after 2 (the MRC display standard is one second). shownMs is the longest continuous stretch during the turn. The 30 seconds after a turn never count.
  • shownMs is what the mod itself knows: it runs from the moment the mod draws the ad until it draws something else, or the Theater from when its pane opens until it closes. The mod can't see past that: a collapsed band, a window behind another, or a screen you've walked away from all look the same to it. The server checks each impression against when it issued the turn's token.
  • serveToken is the server's own signed receipt for the paid ad that was shown, handed back as it came, so the server credits only ads it really served to this account and device. turnToken is the turn's token from above.
  • House ads (the built-in ones shown when the server can't be reached, the welcome card, and the server's own house ads) are never reported.
  • Impressions still queued after 24 hours are dropped, not sent: they earn nothing.
  • POST {endpoint}/api/v1/reports sends { adId, serveToken, reason, note }: from /ads report (with the reason and any note you typed), or from ✕ (reason hide, no note). Reports that can't be sent wait on this machine (up to 50) and go later.
  • /ads login and /ads logout talk to {endpoint}/api/auth/device/code, /device/token, /get-session and /sign-out.

Settings (/config)

FieldDefault
endpointhttps://tokenbreak.devUse http://localhost:3000 while running the site locally
frequencynormalchill 90s, normal 40s, max 20s
theateronoff never opens the pane
picturesonBanner logos, Theater images and video; off keeps ads text only

Install

/plugin marketplace add steven-3/tokenbreak
/plugin install tokenbreak@tokenbreak

Then turn on updates: /plugin → Marketplaces → tokenbreak → Enable auto-update. Claude Code leaves auto-update off for every marketplace outside Anthropic's own. With it on, Claude Code checks within ten minutes of your first prompt in a session and installs new versions on disk. Run /reload-plugins to switch to the new version at once; otherwise it loads the next time you start Claude Code.

Updates

The ad server tells the mod its newest release and the oldest one that still earns; the mod compares them with its own version on your machine and sends nothing extra. When an update is out, you get one notice. When your version is too old to earn, the banner shows an update notice in place of ads and the mod reports nothing, and the server credits nothing from it either. /ads update prints the steps, and /ads status says whether you're current. Each ad request and impression report carries the mod's version.

If a version turns out to be broken or unsafe, the server can switch it off. A switched-off version shows nothing at all and reports nothing. /ads keeps working and says the version has been switched off and to update.

For development: claude --plugin-dir plugins/tokenbreak.

Develop

claude plugin validate plugins/tokenbreak
claude plugin test plugins/tokenbreak
tsc -p plugins/tokenbreak   # once Claude Code has loaded it and written .claude-plugin/types/

The wire types in types/index.d.ts mirror the ad server's API schemas. Change both together.

Built against Claude Code 2.1.292. The mod API is early access, so re-run validate and test after every Claude Code update.

Source 3 files
hooks/register.tsx 1718 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ImageSource, PluginOptions, Register, RenderInput, Timer } from 'claude-code'
3
4import type {
5  Account,
6  Ad,
7  AdReport,
8  AdSource,
9  AdSurface,
10  AdVideo,
11  BannerStyle,
12  Impression,
13  ModRelease,
14  Seat,
15  TheaterShowing,
16  TurnGrant,
17  UpdateState,
18} from '../types'
19import {
20  activeHides,
21  AD_LABEL,
22  AUTO_UPDATE_STEPS,
23  BANNER_LINGER_MS,
24  BANNER_MIN_COLUMNS,
25  BANNER_STYLES,
26  bannerStyleOf,
27  cacheable,
28  canDockTheater,
29  capQueue,
30  currentBanner,
31  cutsOf,
32  describeWait,
33  DEVICE_GRANT,
34  EARNINGS_URL,
35  endStretch,
36  FLUSH_AT,
37  FLUSH_EVERY_MS,
38  formatUserCode,
39  FORMATS,
40  freshOf,
41  HIDE_CAMPAIGN_DAYS,
42  HIDE_CAMPAIGN_MS,
43  hideKeyOf,
44  HOUSE_ADS,
45  impressionKey,
46  isHex,
47  tint,
48  UPDATE_STEPS,
49  updateStateOf,
50  linkable,
51  longestPaid,
52  MIN_SHOWN_MS,
53  MOD_CLIENT_ID,
54  MOD_HEADERS,
55  MOD_VERSION,
56  noteDrawn,
57  posterOf,
58  parseBatch,
59  parseDeviceCode,
60  parseDevicePoll,
61  parseGrant,
62  pauseUntil,
63  queueOf,
64  REPORT_QUEUE_CAP,
65  reportArgsOf,
66  reportQueueOf,
67  rotationMs,
68  rotationOf,
69  shownOf,
70  surfaceOf,
71  THEATER_DELAY_MS,
72  THEATER_MIN_COLUMNS,
73  THEATER_PANE,
74  THEATER_SNOOZE_MS,
75  theaterArt,
76  theaterLayout,
77  theaterOf,
78  trackerOf,
79  TURN_MIN_GAP_MS,
80  TURN_TIMEOUT_MS,
81  WAITING_NOTICE,
82  WELCOME_LINES,
83  withoutFrames,
84  type QueuedReport,
85  type Seen,
86  type Shown,
87  type ShownTracker,
88} from './core'
89
90// Privacy rule: Tokenbreak never hooks prompt.compose, session.append,
91// tool.call, turn.step or anything else that reads or shapes the conversation.
92// Of turn.start and turn.complete it reads the turn's id (and, at the end,
93// whether it was a subagent's) and nothing else. tests/privacy.test.ts holds it
94// to that. Nor does it hook the permission prompt: the only events that say one
95// is open (classic PermissionRequest and Notification) carry the tool's input
96// or the prompt's text, so ads can't step aside for it without reading them.
97
98const ads = atom({ plugin: 'tokenbreak', key: 'ads' } as const, [] as Ad[])
99const source = atom({ plugin: 'tokenbreak', key: 'source' } as const, 'built-in' as AdSource)
100const bannerIndex = atom({ plugin: 'tokenbreak', key: 'bannerIndex' } as const, 0)
101const pausedUntil = atom({ plugin: 'tokenbreak', key: 'pausedUntil' } as const, null as number | null)
102const theater = atom({ plugin: 'tokenbreak', key: 'theater' } as const, null as TheaterShowing | null)
103const bannerStyle = atom({ plugin: 'tokenbreak', key: 'bannerStyle' } as const, 'pill' as BannerStyle)
104const theaterSound = atom({ plugin: 'tokenbreak', key: 'theaterSound' } as const, false)
105const updateState = atom({ plugin: 'tokenbreak', key: 'update' } as const, { kind: 'current' } as UpdateState)
106const account = atom({ plugin: 'tokenbreak', key: 'account' } as const, { kind: 'out' } as Account)
107const bannerUp = atom({ plugin: 'tokenbreak', key: 'bannerUp' } as const, false)
108const hidden = atom({ plugin: 'tokenbreak', key: 'hidden' } as const, {} as Record<string, number>)
109const seat = atom({ plugin: 'tokenbreak', key: 'seat' } as const, null as Seat | null)
110const welcome = atom({ plugin: 'tokenbreak', key: 'welcome' } as const, false)
111
112const FALLBACK_ACCENT = '#FFE600'
113const AD_YELLOW = '#FFE600'
114
115/** The module's own bookkeeping, set afresh by `register`: a reload starts it over. */
116type Run = {
117  endpoint: string
118  isTheaterOn: boolean
119  /** Whether ads draw pictures (banner logos, Theater images and video): the `pictures` option. */
120  arePicturesOn: boolean
121  /** Whether a video ad's sound plays when the Theater opens: the `sound` option. */
122  isSoundOnByDefault: boolean
123  rotationMs: number
124  deviceId: string
125  /** The session token `/ads login` got, sent as a bearer token; undefined while signed out. */
126  token?: string
127  /** Polls the site while `/ads login` waits for approval. */
128  loginTimer?: Timer
129  fetchedAt: number
130  ttlMs: number
131  isRefreshing: boolean
132  isFlushing: boolean
133  runningTurn?: string
134  theaterTimer?: Timer
135  resumeTimer?: Timer
136  theaterSnoozedUntil: number
137  /** What the band saw of the surface when it last drew. */
138  seen?: Seen
139  /** Where ads are drawn, as the last session start or band draw said. */
140  surface: AdSurface
141  /** The banner the band last drew; undefined while it shows none. */
142  drawnBanner?: Ad
143  /** The banner's time on screen this turn. */
144  banner: ShownTracker
145  /** The Theater ad while its pane is open and placed, since when. */
146  theaterOpen?: Omit<Shown, 'ms'> & { turnId: string; since: number }
147  /** How long the Theater stayed open in the turn it opened for. */
148  theaterShown?: Shown & { turnId: string }
149  /** The person's turn running or last run, and the server's grant for it once it came. */
150  turn?: { turnId: string; grant?: TurnGrant; pending?: Promise<TurnGrant | undefined>; note: string }
151  /** When the mod last asked for a turn token. */
152  turnAskedAt: number
153  /** Hides the banner once the linger after a turn runs out. */
154  lingerTimer?: Timer
155  /** Whether the welcome card has been on screen. */
156  isWelcomeDrawn: boolean
157  isSendingReports: boolean
158  /** The last paid ad on screen, which `/ads report` reports. */
159  lastPaid?: LastPaid
160  /** Why the Theater last opened or stayed shut, for `/ads status`. */
161  theaterNote: string
162  /** Each video cut's frames by `frameKey`; `$.state` holds the ads without them. */
163  frames: Map<string, readonly string[]>
164  /** The cut the Theater drew last, which playback steps through. */
165  drawnCut?: { adId: string; index: number }
166  /** The frame on screen; -1 restarts the loop on the next tick. */
167  frame?: number
168  /** Stops the Theater's sound; set while it plays. */
169  sound?: AbortController
170  /** Plays the Theater's video while the pane is open. */
171  videoTimer?: Timer
172  /** The last video's frame swaps, for `/ads status`. */
173  video: { swapped: number; refused: number; reason?: string }
174  timers: Timer[]
175}
176
177/** The paid ad `/ads report` names: its id, its serve token, and its brand to say back. */
178type LastPaid = Pick<AdReport, 'adId' | 'serveToken'> & { brand: string }
179
180function runOf(options: PluginOptions): Run {
181  return {
182    endpoint: String(options.endpoint ?? 'https://tokenbreak.dev').replace(/\/+$/, ''),
183    isTheaterOn: options.theater !== 'off',
184    arePicturesOn: options.pictures !== 'off',
185    isSoundOnByDefault: options.sound !== 'off',
186    rotationMs: rotationMs(options.frequency),
187    deviceId: '',
188    fetchedAt: 0,
189    ttlMs: 600_000,
190    isRefreshing: false,
191    isFlushing: false,
192    theaterSnoozedUntil: 0,
193    surface: 'terminal',
194    banner: trackerOf(),
195    turnAskedAt: Number.NEGATIVE_INFINITY,
196    isWelcomeDrawn: false,
197    isSendingReports: false,
198    theaterNote: 'no turn has run long enough yet',
199    video: { swapped: 0, refused: 0 },
200    frames: new Map(),
201    timers: [],
202  }
203}
204
205let run: Run = runOf({})
206
207/** The status line stays empty; an older build may have left a line there. */
208/** Puts `list` on screen: frames into module memory, the rest into `$.state`. */
209async function showAds($: EngineInterface, list: readonly Ad[]) {
210  run.frames = new Map(
211    list.flatMap(ad =>
212      cutsOf(ad).flatMap((cut, at) => (cut.frames.length === 0 ? [] : [[frameKey(ad.id, at), cut.frames] as const])),
213    ),
214  )
215  await update($, ads, () => withoutFrames(list))
216}
217
218/**
219 * Takes in the server's release info: a mod too old to earn shows an update notice
220 * in place of ads and reports nothing; an update that's merely out gets one toast
221 * per version.
222 */
223async function applyRelease($: EngineInterface, release: ModRelease | undefined) {
224  const state = updateStateOf(release)
225
226  await update($, updateState, () => state)
227
228  // A build switched off shows nothing at all, toasts included: /ads says why.
229  if ((state.kind === 'available' || state.kind === 'required') && (await $.store.get('toldVersion')) !== state.latest) {
230    await $.store.set('toldVersion', state.latest)
231    $.ui.toast(
232      state.kind === 'required'
233        ? `Tokenbreak ${state.latest} is required to keep earning. /ads update shows how.`
234        : `Tokenbreak ${state.latest} is out. /ads update shows how to get it.`,
235      { timeoutMs: 8000 },
236    )
237  }
238}
239
240/** Too old to earn, or switched off: either way nothing is counted. */
241const isUpdateRequired = async ($: EngineInterface) => {
242  const kind = (await read($, updateState)).kind
243
244  return kind === 'required' || kind === 'blocked'
245}
246
247const isBlocked = async ($: EngineInterface) => (await read($, updateState)).kind === 'blocked'
248
249/** `promise`, or undefined once `ms` pass first: nothing the mod sends may hold a turn or a command up. */
250function within<T>($: EngineInterface, promise: Promise<T>, ms = TURN_TIMEOUT_MS): Promise<T | undefined> {
251  return new Promise(resolve => {
252    const timer = $.clock.after(ms, () => resolve(undefined))
253
254    promise.then(
255      value => {
256        timer.cancel()
257        resolve(value)
258      },
259      () => {
260        timer.cancel()
261        resolve(undefined)
262      },
263    )
264  })
265}
266
267const isSignedIn = async ($: EngineInterface) => run.token !== undefined && (await read($, account)).kind === 'in'
268
269/** The bearer header for the ad server, empty while signed out. */
270const authHeaders = (): Record<string, string> => (run.token === undefined ? {} : { authorization: `Bearer ${run.token}` })
271
272/** Which install asks, which version, and where it draws: sent with `GET /api/v1/ads` and `POST /api/v1/turns`. */
273const modHeaders = (): Record<string, string> => ({
274  ...(run.deviceId !== '' && { [MOD_HEADERS.device]: run.deviceId }),
275  [MOD_HEADERS.version]: MOD_VERSION,
276  [MOD_HEADERS.surface]: run.surface,
277})
278
279/** Forgets the account on this machine: the token is gone or no longer good. */
280async function forgetAccount($: EngineInterface) {
281  stopLogin()
282  run.token = undefined
283  await $.store.delete('token')
284  await $.store.delete('login')
285  await update($, account, () => ({ kind: 'out' }) as Account)
286}
287
288function stopLogin() {
289  run.loginTimer?.cancel()
290  run.loginTimer = undefined
291}
292
293/** `/ads login`: asks the site for a code, then polls until the person approves it at /device. */
294async function startLogin($: EngineInterface): Promise<string> {
295  const current = await read($, account)
296
297  if (current.kind === 'in') {
298    return `Signed in as @${current.login}. /ads logout to switch accounts.`
299  }
300
301  stopLogin()
302
303  const response = await $.http
304    .fetch(`${run.endpoint}/api/auth/device/code`, {
305      method: 'POST',
306      headers: { 'content-type': 'application/json', accept: 'application/json' },
307      body: JSON.stringify({ client_id: MOD_CLIENT_ID }),
308    })
309    .catch(() => undefined)
310  const code = response?.ok === true ? parseDeviceCode(response.text) : undefined
311
312  if (code === undefined) {
313    await update($, account, () => ({ kind: 'out' }) as Account)
314
315    return `Couldn't start sign-in at ${run.endpoint}${response === undefined ? ' (unreachable)' : ` (HTTP ${response.status})`}. Try again in a minute.`
316  }
317
318  const userCode = formatUserCode(code.userCode)
319  const expiresAt = (await $.clock.now()) + code.expiresInMs
320  let intervalMs = code.intervalMs
321  let isPolling = false
322
323  await update($, account, () => ({ kind: 'pending', userCode, url: code.url }) as Account)
324
325  const poll = async () => {
326    if (isPolling) {
327      return
328    }
329
330    isPolling = true
331
332    try {
333      if ((await $.clock.now()) > expiresAt) {
334        await endLogin($, 'The sign-in code expired. Run /ads login for a new one.')
335
336        return
337      }
338
339      const answer = await $.http
340        .fetch(`${run.endpoint}/api/auth/device/token`, {
341          method: 'POST',
342          headers: { 'content-type': 'application/json', accept: 'application/json' },
343          body: JSON.stringify({ grant_type: DEVICE_GRANT, device_code: code.deviceCode, client_id: MOD_CLIENT_ID }),
344        })
345        .catch(() => undefined)
346      const outcome = answer === undefined ? { kind: 'wait' as const, slower: false } : parseDevicePoll(answer.status, answer.text)
347
348      if (outcome.kind === 'token') {
349        await finishLogin($, outcome.token)
350      } else if (outcome.kind === 'stop') {
351        await endLogin(
352          $,
353          outcome.reason === 'denied'
354            ? 'Sign-in was denied on the site. Run /ads login to try again.'
355            : outcome.reason === 'expired'
356              ? 'The sign-in code expired. Run /ads login for a new one.'
357              : 'Sign-in failed. Run /ads login to try again.',
358        )
359      } else if (outcome.slower) {
360        intervalMs += 5_000
361        run.loginTimer?.cancel()
362        run.loginTimer = $.clock.every(intervalMs, () => void poll())
363      }
364    } finally {
365      isPolling = false
366    }
367  }
368
369  run.loginTimer = $.clock.every(intervalMs, () => void poll())
370
371  return [
372    `To link Claude Code to your Tokenbreak account, open:`,
373    `  ${code.url}`,
374    `and approve code ${userCode} (signed in with GitHub). It lasts ${describeWait(code.expiresInMs)}.`,
375    `Tokenbreak waits here and starts once you approve.`,
376  ].join('\n')
377}
378
379async function endLogin($: EngineInterface, message: string) {
380  stopLogin()
381  await update($, account, () => ({ kind: 'out' }) as Account)
382  $.ui.toast(message, { timeoutMs: 8000 })
383}
384
385/** Keeps the token, learns the GitHub handle it belongs to, and starts ads. */
386async function finishLogin($: EngineInterface, token: string) {
387  stopLogin()
388  run.token = token
389
390  const session = await $.http
391    .fetch(`${run.endpoint}/api/auth/get-session`, { headers: { accept: 'application/json', ...authHeaders() } })
392    .catch(() => undefined)
393  let login = 'you'
394
395  try {
396    const user = (JSON.parse(session?.text ?? 'null') as { user?: { githubLogin?: unknown; name?: unknown } } | null)?.user
397    login = typeof user?.githubLogin === 'string' ? user.githubLogin : typeof user?.name === 'string' ? user.name : login
398  } catch {
399    // The handle is only for /ads status; the token is what matters.
400  }
401
402  await $.store.set('token', token)
403  await $.store.set('login', login)
404
405  // The first sign-in on this machine opens with the welcome card, once.
406  if ((await $.store.get('welcomed')) !== true) {
407    await $.store.set('welcome', true)
408    await update($, welcome, () => true)
409  }
410
411  await update($, account, () => ({ kind: 'in', login }) as Account)
412  $.ui.toast(`Tokenbreak: signed in as @${login}. Ads start on your next turn.`, { timeoutMs: 8000 })
413  run.fetchedAt = 0
414  void refresh($)
415}
416
417/** `/ads logout`: sends what's queued, ends the session on the site, and forgets it here. */
418async function logout($: EngineInterface): Promise<string> {
419  const current = await read($, account)
420
421  if (current.kind !== 'in' || run.token === undefined) {
422    stopLogin()
423    await update($, account, () => ({ kind: 'out' }) as Account)
424
425    return 'Not signed in. /ads login links your GitHub account.'
426  }
427
428  await flush($)
429  await $.http
430    .fetch(`${run.endpoint}/api/auth/sign-out`, {
431      method: 'POST',
432      headers: { 'content-type': 'application/json', ...authHeaders() },
433      body: '{}',
434    })
435    .catch(() => undefined)
436  await $.store.set('queue', [])
437  await forgetAccount($)
438
439  return `Signed out of @${current.login}. Tokenbreak shows no ads until /ads login.`
440}
441
442const frameKey = (adId: string, cut: number) => `${adId}#${cut}`
443
444/** How many frames a cut has: files the terminal reads, or PNGs held in memory. */
445const lengthOf = (ad: Ad, cut: number) =>
446  cutsOf(ad)[cut]?.files?.length ?? run.frames.get(frameKey(ad.id, cut))?.length ?? 0
447
448/** One frame of a cut as an Image source, undefined when the cut has none. */
449function frameSource(ad: Ad, cut: number, frame: number): ImageSource | undefined {
450  const file = cutsOf(ad)[cut]?.files?.[frame]
451
452  if (file !== undefined) {
453    return { file, format: 'png' }
454  }
455
456  const png = run.frames.get(frameKey(ad.id, cut))?.[frame]
457
458  return png === undefined ? undefined : { png }
459}
460
461const hasVideo = (ad: Ad) => cutsOf(ad).some((_, at) => lengthOf(ad, at) > 0)
462
463async function showStatus($: EngineInterface) {
464  $.ui.status(undefined)
465}
466
467async function setPause($: EngineInterface, until: number | null) {
468  run.resumeTimer?.cancel()
469  run.resumeTimer = undefined
470  await update($, pausedUntil, () => until)
471
472  if (until === null) {
473    await $.store.delete('pausedUntil')
474  } else {
475    await $.store.set('pausedUntil', until)
476    run.resumeTimer = $.clock.after(Math.max(0, until - (await $.clock.now())), () => void setPause($, null))
477  }
478
479  await showStatus($)
480}
481
482async function hideForToday($: EngineInterface) {
483  await setPause($, pauseUntil('today', await $.clock.now()) ?? null)
484}
485
486/**
487 * `✕` on an ad: hides its campaign on this machine for HIDE_CAMPAIGN_DAYS (the
488 * rotation moves on to the next ad), and tells the server with a `hide` report,
489 * without waiting for it.
490 */
491async function hideCampaign($: EngineInterface, ad: Ad) {
492  const now = await $.clock.now()
493  const hides = { ...activeHides(await read($, hidden), now), [hideKeyOf(ad)]: now + HIDE_CAMPAIGN_MS }
494
495  await update($, hidden, () => hides)
496  await $.store.set('hidden', hides)
497  $.ui.toast(`Tokenbreak: ${ad.brand} is hidden on this machine for ${HIDE_CAMPAIGN_DAYS} days. /ads pause stops all ads.`, {
498    timeoutMs: 6000,
499  })
500
501  if (!ad.isHouse) {
502    await queueReport($, { ...shownOf(ad), reason: 'hide', at: now })
503    void sendReports($)
504  }
505}
506
507/** The welcome card has done its job: it never shows again on this machine. */
508async function endWelcome($: EngineInterface) {
509  run.isWelcomeDrawn = false
510  await $.store.set('welcomed', true)
511  await $.store.delete('welcome')
512  await update($, welcome, () => false)
513}
514
515/** Keeps a report until the server has it; the oldest give way past REPORT_QUEUE_CAP. */
516async function queueReport($: EngineInterface, report: QueuedReport) {
517  const queue = [...reportQueueOf(await $.store.get('reportQueue')), report]
518
519  await $.store.set('reportQueue', queue.slice(-REPORT_QUEUE_CAP))
520}
521
522const sameReport = (a: QueuedReport, b: QueuedReport) => a.adId === b.adId && a.reason === b.reason && a.at === b.at
523
524/**
525 * Sends the queued reports in order, one `POST /api/v1/reports` each, each held to
526 * TURN_TIMEOUT_MS. One the server took, or refused as malformed, leaves the queue;
527 * unreachable, a 5xx, 401 or 429 stops the run and keeps the rest for later.
528 */
529async function sendReports($: EngineInterface) {
530  if (run.isSendingReports || !(await isSignedIn($))) {
531    return
532  }
533
534  run.isSendingReports = true
535
536  try {
537    for (const report of reportQueueOf(await $.store.get('reportQueue'))) {
538      const { at: _at, ...body } = report
539      const response = await within(
540        $,
541        $.http.fetch(`${run.endpoint}/api/v1/reports`, {
542          method: 'POST',
543          headers: { 'content-type': 'application/json', accept: 'application/json', ...authHeaders(), ...modHeaders() },
544          body: JSON.stringify(body satisfies AdReport),
545        }),
546      )
547
548      if (response === undefined || response.status >= 500 || response.status === 401 || response.status === 429) {
549        return
550      }
551
552      await $.store.set(
553        'reportQueue',
554        reportQueueOf(await $.store.get('reportQueue')).filter(one => !sameReport(one, report)),
555      )
556    }
557  } finally {
558    run.isSendingReports = false
559  }
560}
561
562/**
563 * Asks the server for this turn's token, without holding the turn up: the answer
564 * counts only if it comes within TURN_TIMEOUT_MS. No token (offline, an error, a
565 * 429) means the turn's ads still show and nothing paid is reported.
566 */
567async function askTurn($: EngineInterface, turnId: string) {
568  const now = await $.clock.now()
569  const skip = !(await isSignedIn($))
570    ? 'signed out'
571    : (await read($, pausedUntil)) !== null
572      ? 'ads are paused'
573      : (await isUpdateRequired($))
574        ? 'this version earns nothing'
575        : (await read($, seat)) === 'waiting'
576          ? 'waiting for an earning seat'
577          : now - run.turnAskedAt < TURN_MIN_GAP_MS
578            ? `under ${TURN_MIN_GAP_MS / 1000}s since the last turn`
579            : undefined
580
581  if (skip !== undefined) {
582    run.turn = { turnId, note: `no turn token: ${skip}` }
583
584    return
585  }
586
587  run.turnAskedAt = now
588
589  const pending = within(
590    $,
591    $.http.fetch(`${run.endpoint}/api/v1/turns`, {
592      method: 'POST',
593      headers: { 'content-type': 'application/json', accept: 'application/json', ...authHeaders(), ...modHeaders() },
594      body: JSON.stringify({ deviceId: run.deviceId, surface: run.surface }),
595    }),
596  ).then(response => {
597    const grant = response?.ok === true ? parseGrant(response.text) : undefined
598
599    if (run.turn?.turnId === turnId) {
600      run.turn = {
601        turnId,
602        ...(grant !== undefined && { grant }),
603        note:
604          grant !== undefined
605            ? 'turn token granted'
606            : `no turn token: ${response === undefined ? 'no answer within 3s' : `HTTP ${response.status}`}`,
607      }
608    }
609
610    return grant
611  })
612
613  run.turn = { turnId, pending, note: 'asking for a turn token' }
614}
615
616/** What the banner draws now: the mod's own record of what is on screen, for its time-on-screen count. */
617async function noteBanner($: EngineInterface, ad: Ad | undefined) {
618  if (ad === run.drawnBanner || (ad !== undefined && ad.id === run.drawnBanner?.id && ad.serveToken === run.drawnBanner.serveToken)) {
619    return
620  }
621
622  run.banner = noteDrawn(run.banner, ad, await $.clock.now())
623  run.drawnBanner = ad
624
625  if (ad !== undefined && !ad.isHouse) {
626    await rememberPaid($, ad)
627  }
628}
629
630async function rememberPaid($: EngineInterface, ad: Ad) {
631  if (run.lastPaid?.adId === ad.id && run.lastPaid.serveToken === ad.serveToken) {
632    return
633  }
634
635  run.lastPaid = { ...shownOf(ad), brand: ad.brand }
636  await $.store.set('lastPaid', run.lastPaid)
637}
638
639function lastPaidOf(raw: unknown): LastPaid | undefined {
640  const one = raw as Partial<LastPaid> | null | undefined
641
642  return typeof one?.adId === 'string' && typeof one.brand === 'string'
643    ? { adId: one.adId, brand: one.brand, ...(typeof one.serveToken === 'string' && { serveToken: one.serveToken }) }
644    : undefined
645}
646
647/** Ends the Theater's stretch on screen: when it closes, by the person or at the turn's end. */
648async function endTheater($: EngineInterface) {
649  const open = run.theaterOpen
650
651  if (open === undefined) {
652    return
653  }
654
655  const { since, ...shown } = open
656
657  run.theaterOpen = undefined
658  run.theaterShown = { ...shown, ms: Math.max(0, (await $.clock.now()) - since) }
659}
660
661/** The linger after a turn ran out: the banner hides until the next turn, and a welcome card that showed is done. */
662async function endLinger($: EngineInterface) {
663  run.lingerTimer = undefined
664  await update($, bannerUp, () => false)
665
666  if (run.isWelcomeDrawn) {
667    await endWelcome($)
668  }
669}
670
671async function refresh($: EngineInterface) {
672  // Signed out, the server has nothing to give: it serves ads only to an account.
673  if (run.isRefreshing || !(await isSignedIn($))) {
674    return
675  }
676
677  run.isRefreshing = true
678
679  try {
680    const response = await $.http.fetch(`${run.endpoint}/api/v1/ads?formats=${FORMATS.join(',')}`, {
681      headers: { accept: 'application/json', ...authHeaders(), ...modHeaders() },
682    })
683
684    if (response.status === 401) {
685      // Signed out on the site, or the session ran out: back to the sign-in hint.
686      await forgetAccount($)
687      $.ui.toast('Tokenbreak was signed out. /ads login to start again.', { timeoutMs: 8000 })
688
689      return
690    }
691
692    const batch = response.ok ? parseBatch(response.text) : undefined
693
694    if (batch?.mod?.blocked === true) {
695      // Switched off: show nothing, report nothing; the cached batch keeps it so across sessions.
696      run.fetchedAt = await $.clock.now()
697      run.ttlMs = batch.ttlSeconds * 1000
698      await applyRelease($, batch.mod)
699      await $.store.set('queue', [])
700      await $.store.set('batch', cacheable(batch))
701
702      return
703    }
704
705    if (batch !== undefined && batch.ads.length > 0) {
706      run.fetchedAt = await $.clock.now()
707      run.ttlMs = batch.ttlSeconds * 1000
708      await showAds($, batch.ads)
709      await applyRelease($, batch.mod)
710      await update($, seat, () => batch.seat ?? null)
711      await update($, source, () => 'server' as AdSource)
712      await $.store.set('batch', cacheable(batch))
713      await showStatus($)
714    }
715  } catch {
716    // Unreachable or refused: keep what is showing, house ads at worst.
717  } finally {
718    run.isRefreshing = false
719  }
720}
721
722async function flush($: EngineInterface) {
723  if (run.isFlushing || !(await isSignedIn($))) {
724    return
725  }
726
727  run.isFlushing = true
728
729  try {
730    if (await isBlocked($)) {
731      await $.store.set('queue', [])
732
733      return
734    }
735
736    const stored = queueOf(await $.store.get('queue'))
737    // Impressions too old to earn are dropped, not sent.
738    const queued = freshOf(stored, await $.clock.now())
739
740    if (queued.length < stored.length) {
741      await $.store.set('queue', queued)
742    }
743
744    if (queued.length === 0) {
745      return
746    }
747
748    const sent = queued.slice(0, 200)
749    const response = await $.http.fetch(`${run.endpoint}/api/v1/impressions`, {
750      method: 'POST',
751      headers: { 'content-type': 'application/json', ...authHeaders() },
752      body: JSON.stringify({ deviceId: run.deviceId, modVersion: MOD_VERSION, impressions: sent }),
753    })
754
755    if (response.status === 401) {
756      // The queue waits for the next sign-in rather than going to another account's ledger.
757      await forgetAccount($)
758
759      return
760    }
761
762    if (response.status === 426) {
763      // Too old to earn: nothing queued will be credited, so drop it and say so.
764      const min = (JSON.parse(response.text) as { minVersion?: unknown }).minVersion
765
766      await $.store.set('queue', [])
767      await applyRelease($, { latest: typeof min === 'string' ? min : MOD_VERSION, min: typeof min === 'string' ? min : MOD_VERSION })
768
769      return
770    }
771
772    if (!response.ok) {
773      return
774    }
775
776    const keys = new Set(sent.map(impressionKey))
777    const left = queueOf(await $.store.get('queue')).filter(impression => !keys.has(impressionKey(impression)))
778
779    await $.store.set('queue', left)
780  } catch {
781    // The queue stays for the next try.
782  } finally {
783    run.isFlushing = false
784  }
785}
786
787async function enqueue($: EngineInterface, impressions: readonly Impression[]) {
788  if (impressions.length === 0) {
789    return
790  }
791
792  const queue = capQueue([...queueOf(await $.store.get('queue')), ...impressions])
793
794  await $.store.set('queue', queue)
795
796  if (queue.length >= FLUSH_AT) {
797    $.clock.after(0, () => void flush($))
798  }
799}
800
801async function tick($: EngineInterface) {
802  const now = await $.clock.now()
803
804  if (now - run.fetchedAt > run.ttlMs) {
805    void refresh($)
806  }
807
808  const hides = await read($, hidden)
809  const active = activeHides(hides, now)
810
811  if (Object.keys(active).length < Object.keys(hides).length) {
812    await update($, hidden, () => active)
813    await $.store.set('hidden', active)
814  }
815
816  await update($, bannerIndex, index => index + 1)
817}
818
819async function openTheater($: EngineInterface, turnId: string) {
820  const now = await $.clock.now()
821
822  const shut =
823    run.runningTurn !== turnId
824      ? 'the turn ended within 3s'
825      : !canDockTheater(run.seen)
826        ? run.seen === undefined
827          ? "the band hasn't reported the terminal's size"
828          : run.seen.columns < THEATER_MIN_COLUMNS
829            ? `the terminal is ${run.seen.columns} columns, under ${THEATER_MIN_COLUMNS}`
830            : 'not the fullscreen layout'
831        : now < run.theaterSnoozedUntil
832          ? `snoozed for ${describeWait(run.theaterSnoozedUntil - now)} after you closed it`
833          : (await read($, pausedUntil)) !== null
834            ? 'ads are paused'
835            : !(await isSignedIn($))
836              ? 'signed out; /ads login'
837              : (await isBlocked($))
838                ? 'this version has been switched off; /ads update'
839                : (await isUpdateRequired($))
840                  ? 'this version is too old to earn; /ads update'
841                  : undefined
842
843  if (shut !== undefined) {
844    run.theaterNote = `stayed shut: ${shut}`
845
846    return
847  }
848
849  const list = rotationOf(await read($, ads), await read($, hidden), now, await read($, seat))
850  const ad = theaterOf(list, currentBanner(list, await read($, bannerIndex)))
851
852  await update($, theater, () => ({ ...shownOf(ad), turnId, isPlaced: false }))
853
854  const opened = await $.ui.open({ id: THEATER_PANE, title: 'Tokenbreak' }).catch((error: unknown) => {
855    run.theaterNote = `stayed shut: opening the pane failed (${String(error).slice(0, 120)})`
856
857    return undefined
858  })
859
860  if (opened === undefined) {
861    await update($, theater, () => null)
862
863    return
864  }
865
866  if (!opened.isPlaced || run.runningTurn !== turnId) {
867    run.theaterNote = opened.isPlaced ? 'stayed shut: the turn ended while it opened' : "stayed shut: Claude Code didn't place the pane"
868    // Never leave a pane waiting undrawn for a wider terminal.
869    await $.ui.close({ id: THEATER_PANE })
870    await update($, theater, () => null)
871
872    return
873  }
874
875  await update($, theater, () => ({ ...shownOf(ad), turnId, isPlaced: true }))
876  run.theaterOpen = { ...shownOf(ad), isHouse: ad.isHouse, turnId, since: await $.clock.now() }
877
878  if (!ad.isHouse) {
879    await rememberPaid($, ad)
880  }
881
882  run.theaterNote = `opened ${ad.brand}${
883    !hasVideo(ad)
884      ? ''
885      : arePicturesOn()
886        ? ` (video, ${cutsOf(ad).length} cut${cutsOf(ad).length === 1 ? '' : 's'}, ${lengthOf(ad, 0)} frames)`
887        : ' (text only: pictures are off in /config)'
888  }`
889  playVideo($, ad)
890
891  // Sound starts with the picture unless the person muted it once (`muted` in the store,
892  // kept across sessions) or set `sound` to off.
893  if (ad.audio !== undefined && run.isSoundOnByDefault && arePicturesOn() && (await $.store.get('muted')) !== true) {
894    await startSound($, ad)
895  }
896}
897
898/** Steps the Theater's Image through the cut it drew, until `stopVideo`. */
899function playVideo($: EngineInterface, ad: Ad) {
900  stopVideo()
901
902  const fps = Math.max(0, ...cutsOf(ad).map((cut: AdVideo) => cut.fps))
903
904  if (!hasVideo(ad) || fps === 0 || !arePicturesOn()) {
905    return
906  }
907
908  run.video = { swapped: 0, refused: 0 }
909  run.frame = undefined
910  run.videoTimer = $.clock.every(Math.round(1000 / fps), () => {
911    const drawn = run.drawnCut
912    const length = drawn?.adId === ad.id ? lengthOf(ad, drawn.index) : 0
913
914    if (drawn === undefined || length < 2) {
915      return
916    }
917
918    run.frame = ((run.frame ?? posterOf(length)) + 1) % length
919
920    const source = frameSource(ad, drawn.index, run.frame)
921
922    if (source === undefined) {
923      return
924    }
925
926    void $.ui
927      .blit({ requestId: THEATER_PANE, key: 'theater-image', source })
928      .then(result => {
929        if (result.deny === undefined) {
930          run.video.swapped += 1
931        } else {
932          run.video.refused += 1
933          run.video.reason = result.deny
934        }
935      })
936      .catch((error: unknown) => {
937        run.video.refused += 1
938        run.video.reason = String(error).slice(0, 160)
939      })
940  })
941}
942
943const arePicturesOn = () => run.arePicturesOn
944
945function stopVideo() {
946  run.videoTimer?.cancel()
947  run.videoTimer = undefined
948}
949
950/** The sound button: mutes (and remembers it), or unmutes and plays from the top of the loop. */
951async function toggleSound($: EngineInterface, ad: Ad) {
952  if (run.sound !== undefined) {
953    await stopSound($)
954    await $.store.set('muted', true)
955
956    return
957  }
958
959  await $.store.delete('muted')
960  await startSound($, ad)
961}
962
963/** Plays the ad's sound, looping with the picture, until `stopSound`. */
964async function startSound($: EngineInterface, ad: Ad) {
965  const audio = ad.audio
966
967  if (audio === undefined) {
968    return
969  }
970
971  const controller = new AbortController()
972
973  run.sound = controller
974  run.frame = -1
975  await update($, theaterSound, () => true)
976  void $.audio
977    .play('url' in audio ? { url: audio.url } : { asset: audio.asset }, { shouldLoop: true, signal: controller.signal })
978    .catch((error: unknown) => {
979      run.theaterNote = `${run.theaterNote}; sound failed: ${String(error).slice(0, 120)}`
980    })
981    .finally(() => {
982      if (run.sound === controller) {
983        run.sound = undefined
984        void update($, theaterSound, () => false)
985      }
986    })
987}
988
989async function stopSound($: EngineInterface) {
990  run.sound?.abort()
991  run.sound = undefined
992  await update($, theaterSound, () => false)
993}
994
995async function startSession($: EngineInterface, surface: unknown) {
996  for (const timer of run.timers.splice(0)) {
997    timer.cancel()
998  }
999
1000  run.surface = surfaceOf(surface)
1001  run.lingerTimer?.cancel()
1002  run.lingerTimer = undefined
1003
1004  stopVideo()
1005  await stopSound($)
1006
1007  stopLogin()
1008
1009  await $.command
1010    .register({
1011      name: 'ads',
1012      description: 'Tokenbreak ads: login, logout, status, update, next, style, pause [1h|30m|today], resume, report [reason] [note]',
1013      argumentHint: '[login|logout|status|update|next|style pill|pause 1h|resume|report scam]',
1014      immediate: true,
1015    })
1016    .catch(() => undefined)
1017
1018  // Ads need an account: a session token from /ads login, kept across sessions.
1019  const storedToken = await $.store.get('token')
1020  const storedLogin = await $.store.get('login')
1021
1022  run.token = typeof storedToken === 'string' && storedToken.length > 0 ? storedToken : undefined
1023  await update($, account, () =>
1024    (run.token === undefined ? { kind: 'out' } : { kind: 'in', login: typeof storedLogin === 'string' ? storedLogin : 'you' }) as Account,
1025  )
1026
1027  const storedId = await $.store.get('deviceId')
1028
1029  run.deviceId = typeof storedId === 'string' && storedId.length >= 8 ? storedId : crypto.randomUUID()
1030
1031  if (storedId !== run.deviceId) {
1032    await $.store.set('deviceId', run.deviceId)
1033  }
1034
1035  const cached = parseBatch(JSON.stringify((await $.store.get('batch')) ?? null))
1036  const storedStyle = await $.store.get('bannerStyle')
1037
1038  if (cached !== undefined && cached.ads.length > 0) {
1039    await showAds($, cached.ads)
1040    await applyRelease($, cached.mod)
1041    await update($, seat, () => cached.seat ?? null)
1042    await update($, source, () => 'cache' as AdSource)
1043  } else {
1044    await showAds($, HOUSE_ADS)
1045    await applyRelease($, cached?.mod)
1046    await update($, source, () => 'built-in' as AdSource)
1047  }
1048
1049  await update($, bannerStyle, () => bannerStyleOf(storedStyle))
1050
1051  const storedPause = await $.store.get('pausedUntil')
1052  const now = await $.clock.now()
1053  const hides = activeHides(await $.store.get('hidden'), now)
1054
1055  await update($, hidden, () => hides)
1056  await update($, bannerUp, () => false)
1057  const isWelcomeDue = (await $.store.get('welcome')) === true && (await $.store.get('welcomed')) !== true
1058
1059  await update($, welcome, () => isWelcomeDue)
1060  run.lastPaid = lastPaidOf(await $.store.get('lastPaid'))
1061
1062  await setPause($, typeof storedPause === 'number' && storedPause > now ? storedPause : null)
1063
1064  run.timers.push(
1065    $.clock.every(run.rotationMs, () => void tick($)),
1066    $.clock.every(FLUSH_EVERY_MS, () => {
1067      void flush($)
1068      void sendReports($)
1069    }),
1070    $.clock.after(0, () => void refresh($).then(() => sendReports($))),
1071  )
1072}
1073
1074/** What `/ads` says of this build: current, an update out, too old to earn, or switched off. */
1075function versionLine(state: UpdateState): string {
1076  switch (state.kind) {
1077    case 'current':
1078      return `Version: ${MOD_VERSION}, the latest`
1079    case 'available':
1080      return `Version: ${MOD_VERSION}; ${state.latest} is out (/ads update)`
1081    case 'required':
1082      return `Version: ${MOD_VERSION}, too old to earn; ${state.latest} is out (/ads update)`
1083    case 'blocked':
1084      return `Version: ${MOD_VERSION} has been switched off; update to ${state.latest} (/ads update)`
1085  }
1086}
1087
1088const SWITCHED_OFF = `This version of Tokenbreak (${MOD_VERSION}) has been switched off: it shows and counts no ads. Update it: /ads update`
1089
1090/** `/ads report [reason] [note]`: the last paid ad on screen goes to the server for a person to review. */
1091async function reportAd($: EngineInterface, words: readonly string[]): Promise<string> {
1092  // The paid banner on screen, else the last paid ad that was.
1093  const drawn = run.drawnBanner
1094  const ad = drawn !== undefined && !drawn.isHouse ? { ...shownOf(drawn), brand: drawn.brand } : run.lastPaid
1095
1096  if (ad === undefined) {
1097    return "No paid ad has shown on this machine yet, so there's nothing to report."
1098  }
1099
1100  const { reason, note } = reportArgsOf(words)
1101  const report: QueuedReport = {
1102    adId: ad.adId,
1103    ...(ad.serveToken !== undefined && { serveToken: ad.serveToken }),
1104    reason,
1105    ...(note !== undefined && { note }),
1106    at: await $.clock.now(),
1107  }
1108
1109  await queueReport($, report)
1110  await sendReports($)
1111
1112  const isSent = !reportQueueOf(await $.store.get('reportQueue')).some(one => sameReport(one, report))
1113
1114  return isSent
1115    ? `Reported ${ad.brand} (${reason}). It was sent to Tokenbreak for human review. Thanks.`
1116    : `Saved your report on ${ad.brand} (${reason}). It goes to Tokenbreak for human review as soon as ${
1117        (await isSignedIn($)) ? 'the server can be reached' : "you're signed in (/ads login)"
1118      }.`
1119}
1120
1121async function adsCommand($: EngineInterface, args: string): Promise<string> {
1122  const [verb = 'status'] = args.trim().split(/\s+/).filter(Boolean)
1123  const answer = await answerAds($, args)
1124
1125  // Switched off, every answer but the update steps and the status says so first.
1126  return (await isBlocked($)) && verb !== 'update' && verb !== 'status' ? `${SWITCHED_OFF}\n${answer}` : answer
1127}
1128
1129async function answerAds($: EngineInterface, args: string): Promise<string> {
1130  const [verb = 'status', ...rest] = args.trim().split(/\s+/).filter(Boolean)
1131  const now = await $.clock.now()
1132
1133  if (verb === 'login') {
1134    return startLogin($)
1135  }
1136
1137  if (verb === 'logout') {
1138    return logout($)
1139  }
1140
1141  if (verb === 'pause') {
1142    const until = pauseUntil(rest.join(' '), now)
1143
1144    if (until === undefined) {
1145      return 'Usage: /ads pause [1h|30m|2h|today]'
1146    }
1147
1148    await setPause($, until)
1149
1150    return `Tokenbreak paused for ${describeWait(until - now)}. /ads resume brings it back.`
1151  }
1152
1153  if (verb === 'update') {
1154    const state = await read($, updateState)
1155    const where =
1156      state.kind === 'current'
1157        ? `You're on ${MOD_VERSION}, the latest.`
1158        : state.kind === 'blocked'
1159          ? `You're on ${MOD_VERSION}, which has been switched off; ${state.latest} is out.`
1160          : `You're on ${MOD_VERSION}; ${state.latest} is out${state.kind === 'required' ? ' and needed to keep earning' : ''}.`
1161
1162    return `${where}\n${UPDATE_STEPS}`
1163  }
1164
1165  if (verb === 'next') {
1166    await update($, bannerIndex, index => index + 1)
1167
1168    const ad = currentBanner(rotationOf(await read($, ads), await read($, hidden), now, await read($, seat)), await read($, bannerIndex))
1169
1170    return ad === undefined ? 'No banners to show.' : `Showing ad ${ad.id}${(await read($, bannerUp)) ? '' : ' during your next turn'}.`
1171  }
1172
1173  if (verb === 'style') {
1174    const wanted = rest[0]
1175
1176    if (!BANNER_STYLES.includes(wanted as BannerStyle)) {
1177      return `Usage: /ads style [${BANNER_STYLES.join('|')}] (now ${await read($, bannerStyle)})`
1178    }
1179
1180    await update($, bannerStyle, () => wanted as BannerStyle)
1181    await $.store.set('bannerStyle', wanted)
1182
1183    return `Banner style: ${wanted}.`
1184  }
1185
1186  if (verb === 'resume') {
1187    await setPause($, null)
1188
1189    return 'Tokenbreak resumed.'
1190  }
1191
1192  if (verb === 'report') {
1193    return reportAd($, rest)
1194  }
1195
1196  if (verb !== 'status') {
1197    return 'Usage: /ads [login|logout|status|update|next|style pill|pause 1h|pause today|resume|report [scam|misleading|offensive|broken|other] [note]]'
1198  }
1199
1200  const until = await read($, pausedUntil)
hooks/core.ts 970 lines
1import type {
2  Ad,
3  AdBatch,
4  AdFormat,
5  AdReport,
6  AdReportReason,
7  AdSurface,
8  AdVideo,
9  BannerStyle,
10  Impression,
11  ModRelease,
12  Seat,
13  TurnGrant,
14  UpdateState,
15} from '../types'
16
17/**
18 * This build's version. A hooks module can't read its own plugin.json without
19 * reading a file, so it's written here too; tools/sync-public-mod.sh refuses to
20 * publish unless it equals plugin.json's and the server's MOD_LATEST_VERSION.
21 */
22export const MOD_VERSION = '0.6.0'
23
24/** What every ad says it is, in the banner and the Theater. Short on purpose: terminal columns go to the headline. */
25export const AD_LABEL = 'Ad'
26
27/**
28 * The headers `GET /api/v1/ads` and `POST /api/v1/turns` carry besides the
29 * session token: this install's random device id, the mod's version, and where
30 * ads are drawn (`terminal` or `desktop`), so the server can sign each serve for
31 * this device. Nothing else about the person.
32 */
33export const MOD_HEADERS = {
34  device: 'X-Tokenbreak-Device',
35  version: 'X-Tokenbreak-Version',
36  surface: 'X-Tokenbreak-Surface',
37} as const
38
39/**
40 * How long an ad must stay on screen, continuously, for the turn's end to report
41 * it: the MRC display standard's one second for the banner, two for the Theater.
42 */
43export const MIN_SHOWN_MS = { banner: 1_000, theater: 2_000 } as const satisfies Record<AdFormat, number>
44
45/** Impressions older than this earn nothing, so the mod drops them rather than send them. */
46export const IMPRESSION_MAX_AGE_MS = 24 * 60 * 60 * 1000
47
48/** The banner shows while a turn runs and this long after it ends, then hides until the next turn. */
49export const BANNER_LINGER_MS = 30_000
50
51/** Narrower terminals than this get no banner at all. */
52export const BANNER_MIN_COLUMNS = 80
53
54/** `✕` hides that campaign on this machine for this many days. */
55export const HIDE_CAMPAIGN_DAYS = 30
56export const HIDE_CAMPAIGN_MS = HIDE_CAMPAIGN_DAYS * 24 * 60 * 60 * 1000
57
58/** `POST /api/v1/turns` never holds a turn up: an answer later than this is ignored. */
59export const TURN_TIMEOUT_MS = 3_000
60
61/** The server grants no token to turns closer together than this on one device, so the mod doesn't ask. */
62export const TURN_MIN_GAP_MS = 10_000
63
64/** Reasons `/ads report` takes; `hide` is the `✕` button's own. */
65export const REPORT_REASONS = ['scam', 'misleading', 'offensive', 'broken', 'other'] as const satisfies readonly AdReportReason[]
66export const REPORT_NOTE_MAX = 280
67/** Reports wait here while the server can't be reached; the oldest give way past this. */
68export const REPORT_QUEUE_CAP = 50
69
70/** `terminal`, or `desktop` for every surface that isn't one (the desktop app's Code tab). */
71export const surfaceOf = (surface: unknown): AdSurface => (surface === 'terminal' ? 'terminal' : 'desktop')
72
73/** The longest serve token the mod keeps; a longer or empty one is dropped and the ad shows without it. */
74export const SERVE_TOKEN_MAX = 512
75
76export const THEATER_PANE = 'tokenbreak-theater'
77export const QUEUE_CAP = 200
78export const FLUSH_AT = 20
79export const FLUSH_EVERY_MS = 5 * 60_000
80/** Short turns never get a Theater: it opens once a turn has run this long. */
81export const THEATER_DELAY_MS = 3_000
82/** Below this the engine leaves an unasked pane undrawn, so Tokenbreak never asks. */
83export const THEATER_MIN_COLUMNS = 144
84/** Closing the Theater by hand keeps it away this long. */
85export const THEATER_SNOOZE_MS = 30 * 60_000
86export const FORMATS: readonly AdFormat[] = ['banner', 'theater']
87
88export const ROTATION_MS = { chill: 90_000, normal: 40_000, max: 20_000 } as const
89
90export function rotationMs(frequency: unknown): number {
91  return ROTATION_MS[frequency as keyof typeof ROTATION_MS] ?? ROTATION_MS.normal
92}
93
94/** Shown when the ad server can't be reached: Tokenbreak's own promos, never a third party's. */
95export const HOUSE_ADS: readonly Ad[] = [
96  {
97    id: 'house-rent',
98    format: 'banner',
99    brand: 'Tokenbreak',
100    glyph: '▚',
101    headline: 'This space for rent. Buy a break for your brand.',
102    accent: '#FFE600',
103    clickUrl: 'https://tokenbreak.dev/advertise',
104    isHouse: true,
105  },
106  {
107    id: 'house-earn',
108    format: 'banner',
109    brand: 'Tokenbreak',
110    glyph: '◆',
111    headline: 'Earn USDC while Claude thinks. Half of every paid ad.',
112    accent: '#8C91FF',
113    clickUrl: 'https://tokenbreak.dev/earn',
114    isHouse: true,
115  },
116  {
117    id: 'house-ui',
118    format: 'banner',
119    brand: 'Tokenbreak UI',
120    glyph: '▣',
121    headline: 'Free terminal-style shadcn components. One npx away.',
122    accent: '#F1EFE8',
123    clickUrl: 'https://tokenbreak.dev/ui',
124    isHouse: true,
125  },
126  {
127    id: 'house-theater',
128    format: 'theater',
129    brand: 'Tokenbreak',
130    glyph: '▚',
131    headline: 'Your brand here, while Claude works. Founding slots open.',
132    accent: '#FFE600',
133    clickUrl: 'https://tokenbreak.dev/formats',
134    isHouse: true,
135  },
136]
137
138const HEX = /^#[0-9a-fA-F]{6}$/
139
140/** The most a banner logo's PNG may weigh; a bigger one draws the glyph instead. */
141export const LOGO_MAX_BYTES = 768
142
143export const isHex = (value: unknown): value is string => typeof value === 'string' && HEX.test(value)
144
145/**
146 * The href a `Link` may carry, or undefined: https, or http on localhost,
147 * printable ASCII with no `@` or space, spelled as `new URL(href).href`.
148 */
149export function linkable(href: string): string | undefined {
150  try {
151    const url = new URL(href)
152    const isLocal = url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1')
153
154    if (url.protocol !== 'https:' && !isLocal) {
155      return undefined
156    }
157
158    const spelled = url.href
159
160    return spelled.length <= 2048 && /^[\x21-\x7e]+$/.test(spelled) && !spelled.includes('@') ? spelled : undefined
161  } catch {
162    return undefined
163  }
164}
165
166/**
167 * Server text made safe to draw: control characters (which could carry
168 * terminal escape sequences) become spaces and bidi overrides are dropped,
169 * then the result is cut to `max` characters.
170 */
171export const plain = (value: string, max: number): string =>
172  value
173    .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
174    .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '')
175    .slice(0, max)
176
177const PNG_SIGNATURE = '\x89PNG\r\n\x1a\n'
178
179/**
180 * Whether `base64` is a PNG the terminal takes: standard padded base64 that
181 * opens with the PNG signature and an IHDR of 1 to 4096 pixels a side. The
182 * engine refuses a whole drawing over one picture that isn't.
183 */
184export function isPng(base64: string): boolean {
185  if (base64.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {
186    return false
187  }
188
189  // The signature, the IHDR chunk's length and name, then its width and height: 24 bytes.
190  const head = atob(base64.slice(0, 32))
191  const side = (at: number) =>
192    ((head.charCodeAt(at) << 24) | (head.charCodeAt(at + 1) << 16) | (head.charCodeAt(at + 2) << 8) | head.charCodeAt(at + 3)) >>> 0
193
194  return (
195    head.length === 24 &&
196    head.startsWith(PNG_SIGNATURE) &&
197    head.slice(12, 16) === 'IHDR' &&
198    [side(16), side(20)].every(px => px >= 1 && px <= 4096)
199  )
200}
201
202/** A `{ png, width, height }` whose PNG decodes to at most `maxBytes`. */
203const isImage = (value: Record<string, unknown> | undefined, maxBytes: number): value is Record<string, unknown> =>
204  typeof value === 'object' &&
205  value !== null &&
206  typeof value.png === 'string' &&
207  value.png.length <= Math.ceil(maxBytes / 3) * 4 &&
208  typeof value.width === 'number' &&
209  typeof value.height === 'number'
210
211/** A loop of at most 240 frames and 8 MiB of PNG, its rate held to 1-30 fps; undefined when it isn't one. */
212function videoOf(raw: unknown): AdVideo | undefined {
213  if (typeof raw !== 'object' || raw === null) {
214    return undefined
215  }
216
217  const video = raw as Record<string, unknown>
218  const frames = video.frames
219
220  if (
221    !Array.isArray(frames) ||
222    frames.length === 0 ||
223    frames.length > 240 ||
224    !frames.every(frame => typeof frame === 'string') ||
225    frames.reduce((sum: number, frame: string) => sum + frame.length, 0) > Math.ceil((8 * 1024 * 1024) / 3) * 4 ||
226    typeof video.fps !== 'number' ||
227    typeof video.width !== 'number' ||
228    typeof video.height !== 'number'
229  ) {
230    return undefined
231  }
232
233  return { frames: frames as string[], fps: Math.min(30, Math.max(1, video.fps)), width: video.width, height: video.height }
234}
235
236const VERSION = /^\d+\.\d+\.\d+$/
237
238/** `a` compared with `b`, part by part: negative when older, 0 when equal. */
239export function compareVersions(a: string, b: string): number {
240  const [x, y] = [a, b].map(version => version.split('.').map(part => Number.parseInt(part, 10) || 0))
241
242  for (let at = 0; at < 3; at++) {
243    const diff = (x?.[at] ?? 0) - (y?.[at] ?? 0)
244
245    if (diff !== 0) {
246      return diff
247    }
248  }
249
250  return 0
251}
252
253/** The server's release info, when it sent a well-formed one. */
254function releaseOf(raw: unknown): ModRelease | undefined {
255  const mod = raw as { latest?: unknown; min?: unknown; blocked?: unknown } | undefined
256
257  return typeof mod?.latest === 'string' && typeof mod.min === 'string' && VERSION.test(mod.latest) && VERSION.test(mod.min)
258    ? { latest: mod.latest, min: mod.min, ...(mod.blocked === true && { blocked: true }) }
259    : undefined
260}
261
262/**
263 * Where `version` stands against the server's releases; current when the server
264 * didn't say. A build the server switched off is `blocked` whatever its number.
265 */
266export function updateStateOf(release: ModRelease | undefined, version = MOD_VERSION): UpdateState {
267  if (release?.blocked === true) {
268    return { kind: 'blocked', latest: release.latest }
269  }
270
271  if (release === undefined || compareVersions(version, release.latest) >= 0) {
272    return { kind: 'current' }
273  }
274
275  return compareVersions(version, release.min) < 0
276    ? { kind: 'required', latest: release.latest }
277    : { kind: 'available', latest: release.latest }
278}
279
280/**
281 * How to turn on auto-update for the tokenbreak marketplace, as Claude Code's
282 * docs give it (code.claude.com/docs/en/plugins/host-marketplace, "Turn on
283 * auto-update"): it's off for every marketplace outside Anthropic's own.
284 */
285export const AUTO_UPDATE_STEPS = 'Get updates automatically: /plugin → Marketplaces → tokenbreak → Enable auto-update.'
286
287/** What `/ads update` prints: how to update now, and how never to fall behind again. */
288export const UPDATE_STEPS = [
289  'Update Tokenbreak:',
290  '  /plugin marketplace update tokenbreak',
291  '  /plugin update tokenbreak@tokenbreak',
292  '  /reload-plugins',
293  AUTO_UPDATE_STEPS,
294].join('\n')
295
296const isFormat = (value: unknown): value is AdFormat => value === 'banner' || value === 'theater'
297
298export const isServeToken = (value: unknown): value is string =>
299  typeof value === 'string' && value.length > 0 && value.length <= SERVE_TOKEN_MAX
300
301function adOf(raw: unknown): Ad | undefined {
302  if (typeof raw !== 'object' || raw === null) {
303    return undefined
304  }
305
306  const ad = raw as Record<string, unknown>
307  const image = ad.image as Record<string, unknown> | undefined
308  const hasImage = isImage(image, 2 * 1024 * 1024)
309  const video = videoOf(ad.video)
310  const videos = Array.isArray(ad.videos)
311    ? ad.videos.slice(0, 3).flatMap(one => {
312        const cut = videoOf(one)
313
314        return cut === undefined ? [] : [cut]
315      })
316    : []
317  const logo = ad.logo as Record<string, unknown> | undefined
318  // A logo the terminal wouldn't take is dropped for the glyph: the engine would refuse
319  // the whole band over it, and the turn would still count the banner it never showed.
320  const hasLogo = isImage(logo, LOGO_MAX_BYTES) && isPng(logo.png as string)
321
322  if (
323    typeof ad.id !== 'string' ||
324    !isFormat(ad.format) ||
325    typeof ad.brand !== 'string' ||
326    typeof ad.headline !== 'string' ||
327    typeof ad.clickUrl !== 'string'
328  ) {
329    return undefined
330  }
331
332  return {
333    id: plain(ad.id, 64),
334    format: ad.format,
335    brand: plain(ad.brand, 24),
336    ...(typeof ad.glyph === 'string' && ad.glyph.length > 0 && { glyph: plain(ad.glyph, 2) }),
337    headline: plain(ad.headline, 80),
338    ...(typeof ad.cta === 'string' && ad.cta.trim().length > 0 && { cta: plain(ad.cta.trim(), 24) }),
339    accent: isHex(ad.accent) ? ad.accent : '#FFE600',
340    clickUrl: ad.clickUrl,
341    ...(hasImage && {
342      image: { png: image.png as string, width: image.width as number, height: image.height as number },
343    }),
344    ...(video !== undefined && { video }),
345    ...(videos.length > 0 && { videos }),
346    ...(hasLogo && { logo: { png: logo.png as string, width: logo.width as number, height: logo.height as number } }),
347    isHouse: ad.isHouse === true,
348    ...(typeof ad.campaignId === 'string' && ad.campaignId.length > 0 && { campaignId: plain(ad.campaignId, 64) }),
349    ...(isServeToken(ad.serveToken) && { serveToken: ad.serveToken }),
350  }
351}
352
353/**
354 * An `AdBatch` from the API's JSON, its malformed ads dropped; undefined when it
355 * isn't one. Ads never carry sound: the Theater is silent (FMT-03).
356 */
357export function parseBatch(text: string): AdBatch | undefined {
358  try {
359    const raw = JSON.parse(text) as Record<string, unknown>
360
361    if (!Array.isArray(raw.ads)) {
362      return undefined
363    }
364
365    const ads = raw.ads.map(one => adOf(one)).filter((ad): ad is Ad => ad !== undefined)
366    const ttl = typeof raw.ttlSeconds === 'number' && raw.ttlSeconds > 0 ? raw.ttlSeconds : 600
367
368    const mod = releaseOf(raw.mod)
369    const seat = raw.seat === 'earning' || raw.seat === 'waiting' ? (raw.seat as Seat) : undefined
370
371    return {
372      ads,
373      ttlSeconds: Math.min(ttl, 24 * 3600),
374      servedAt: typeof raw.servedAt === 'string' ? raw.servedAt : '',
375      ...(mod !== undefined && { mod }),
376      ...(seat !== undefined && { seat }),
377    }
378  } catch {
379    return undefined
380  }
381}
382
383/** The batch as it may sit in `$.store` (4 MiB in all): images dropped once it gets big. */
384export function cacheable(batch: AdBatch): AdBatch {
385  return JSON.stringify(batch).length <= 1_500_000
386    ? batch
387    : { ...batch, ads: batch.ads.map(({ image: _image, video: _video, ...ad }) => ad) }
388}
389
390export const bannersOf = (ads: readonly Ad[]) => ads.filter(ad => ad.format === 'banner')
391
392/**
393 * The ads as `$.state` holds them: each video's frames left out, its size and
394 * rate kept. A session's state takes 4 MiB of JSON; one video's frames can fill that.
395 */
396export const withoutFrames = (ads: readonly Ad[]): Ad[] =>
397  ads.map(ad => ({
398    ...ad,
399    ...(ad.video !== undefined && { video: { ...ad.video, frames: [] } }),
400    ...(ad.videos !== undefined && { videos: ad.videos.map(cut => ({ ...cut, frames: [] })) }),
401  }))
402
403/** Every cut of an ad's video: `videos` first, then `video`. */
404export const cutsOf = (ad: Ad): AdVideo[] => [...(ad.videos ?? []), ...(ad.video === undefined ? [] : [ad.video])]
405
406/** A terminal cell is about twice as tall as it is wide. */
407export const CELL_ASPECT = 2
408
409/** Rows the Theater card takes under a picture, and columns beside one. */
410export const CARD_ROWS = 9
411export const CARD_COLUMNS = 36
412
413export type TheaterLayout = {
414  /** `stack`: picture above the card; `side`: picture left of it. */
415  mode: 'stack' | 'side'
416  /** Which of the shapes it shows. */
417  shape: number
418  columns: number
419  rows: number
420}
421
422/**
423 * The layout that shows the biggest picture in a `columns` × `rows` pane: every
424 * shape, stacked over the card or beside it, fitted without distortion.
425 */
426export function theaterLayout(
427  columns: number,
428  rows: number,
429  shapes: readonly { width: number; height: number }[],
430): TheaterLayout {
431  const fit = (mode: TheaterLayout['mode'], shape: number, roomColumns: number, roomRows: number): TheaterLayout => {
432    const { width, height } = shapes[shape] ?? { width: 16, height: 9 }
433    // Cells across per cell down that keep the picture's own proportions.
434    const ratio = (width / height) * CELL_ASPECT
435    const across = Math.max(1, Math.min(255, roomColumns, Math.floor(Math.max(1, roomRows) * ratio)))
436
437    return { mode, shape, columns: across, rows: Math.max(1, Math.min(255, Math.round(across / ratio))) }
438  }
439  const options = (shapes.length === 0 ? [0] : shapes.map((_, at) => at)).flatMap(shape => [
440    fit('stack', shape, columns, rows - CARD_ROWS),
441    ...(columns - CARD_COLUMNS >= 20 ? [fit('side', shape, columns - CARD_COLUMNS - 2, rows - 1)] : []),
442  ])
443
444  return options.reduce((best, one) => (one.columns * one.rows > best.columns * best.rows ? one : best))
445}
446
447/** The frame a video shows before it plays: three quarters in, past any fade-in. */
448export const posterOf = (frameCount: number) => Math.floor(frameCount * 0.75)
449
450export const BANNER_STYLES = ['pill', 'rule', 'card'] as const
451
452export const bannerStyleOf = (value: unknown): BannerStyle =>
453  BANNER_STYLES.includes(value as BannerStyle) ? (value as BannerStyle) : 'pill'
454
455/** `hex` mixed into `base` by `amount` (0 to 1): a dark tint of a brand color for a button's ground. */
456export function tint(hex: string, amount: number, base = '#141414'): string {
457  const channel = (color: string, at: number) => parseInt(color.slice(at, at + 2), 16)
458
459  return `#${[1, 3, 5]
460    .map(at => Math.round(channel(base, at) + (channel(hex, at) - channel(base, at)) * amount))
461    .map(value => value.toString(16).padStart(2, '0'))
462    .join('')}`
463}
464
465/** Ink that reads on `hex`: near-black on light colors, white on dark ones. */
466export function inkOn(hex: string): string {
467  const [r, g, b] = [1, 3, 5].map(at => parseInt(hex.slice(at, at + 2), 16) / 255)
468  const linear = (c: number) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)
469  const luminance = 0.2126 * linear(r ?? 0) + 0.7152 * linear(g ?? 0) + 0.0722 * linear(b ?? 0)
470
471  return luminance > 0.4 ? '#141414' : '#FFFFFF'
472}
473
474/** The Theater ad: the banner brand's own when it has one, so one brand holds both slots; else the batch's first. */
475export const theaterOf = (ads: readonly Ad[], banner?: Ad): Ad =>
476  ads.find(ad => ad.format === 'theater' && ad.brand === banner?.brand) ??
477  ads.find(ad => ad.format === 'theater') ??
478  (HOUSE_ADS.find(ad => ad.format === 'theater') as Ad)
479
480export function currentBanner(ads: readonly Ad[], index: number): Ad | undefined {
481  const banners = bannersOf(ads)
482
483  return banners.length === 0 ? undefined : banners[((index % banners.length) + banners.length) % banners.length]
484}
485
486/** What `✕` hides: the ad's campaign, or the ad itself when the server names none. */
487export const hideKeyOf = (ad: Ad): string => ad.campaignId ?? ad.id
488
489/** The hides still in force at `now`, expired ones dropped; malformed ones too. */
490export function activeHides(raw: unknown, now: number): Record<string, number> {
491  if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
492    return {}
493  }
494
495  return Object.fromEntries(
496    Object.entries(raw as Record<string, unknown>).filter(
497      (entry): entry is [string, number] => typeof entry[1] === 'number' && entry[1] > now,
498    ),
499  )
500}
501
502const isHiddenAt = (ad: Ad, hidden: Readonly<Record<string, number>>, now: number) => (hidden[hideKeyOf(ad)] ?? 0) > now
503
504/**
505 * The ads rotation draws from: hidden campaigns skipped, and only house ads while
506 * the account waits for an earning seat. When that leaves no banner, the built-in
507 * house banners that aren't hidden stand in.
508 */
509export function rotationOf(
510  ads: readonly Ad[],
511  hidden: Readonly<Record<string, number>>,
512  now: number,
513  seat: Seat | null = null,
514): Ad[] {
515  const shown = ads.filter(ad => !isHiddenAt(ad, hidden, now) && (seat !== 'waiting' || ad.isHouse))
516
517  return bannersOf(shown).length > 0
518    ? shown
519    : [...shown, ...HOUSE_ADS.filter(ad => ad.format === 'banner' && !isHiddenAt(ad, hidden, now))]
520}
521
522/** The server's turn grant from its JSON; undefined when it isn't one. */
523export function parseGrant(text: string): TurnGrant | undefined {
524  try {
525    const raw = JSON.parse(text) as Record<string, unknown>
526
527    return typeof raw.turnId === 'string' &&
528      raw.turnId.length <= 64 &&
529      typeof raw.turnToken === 'string' &&
530      raw.turnToken.length > 0 &&
531      raw.turnToken.length <= 512 &&
532      typeof raw.issuedAt === 'number' &&
533      Number.isFinite(raw.issuedAt)
534      ? { turnId: raw.turnId, turnToken: raw.turnToken, issuedAt: raw.issuedAt }
535      : undefined
536  } catch {
537    return undefined
538  }
539}
540
541/** One ad's stretch on screen that hasn't ended yet. */
542export type Stretch = Pick<Impression, 'adId' | 'serveToken'> & { isHouse: boolean; since: number }
543
544/** The longest stretch an ad was on screen this turn. */
545export type Shown = Pick<Impression, 'adId' | 'serveToken'> & { isHouse: boolean; ms: number }
546
547/**
548 * What the mod knows of a format's time on screen this turn: the stretch running
549 * now, and each ad's longest finished one. It only counts between the turn's
550 * start and its end (`isCounting`); the banner's linger after the turn is never counted.
551 */
552export type ShownTracker = { isCounting: boolean; current?: Stretch; best: Record<string, Shown> }
553
554export const trackerOf = (isCounting = false): ShownTracker => ({ isCounting, best: {} })
555
556/** Ends the running stretch at `now`, keeping it if it's that ad's longest. */
557export function endStretch(tracker: ShownTracker, now: number): ShownTracker {
558  const { current } = tracker
559
560  if (current === undefined) {
561    return tracker
562  }
563
564  const ms = Math.max(0, now - current.since)
565  const kept = tracker.best[current.adId]
566  const best =
567    tracker.isCounting && (kept === undefined || ms > kept.ms)
568      ? {
569          ...tracker.best,
570          [current.adId]: {
571            adId: current.adId,
572            ...(current.serveToken !== undefined && { serveToken: current.serveToken }),
573            isHouse: current.isHouse,
574            ms,
575          },
576        }
577      : tracker.best
578
579  return { isCounting: tracker.isCounting, best }
580}
581
582/**
583 * The tracker after the mod drew `ad` (or nothing) at `now`: the same ad drawn
584 * again continues its stretch; any other change ends it and starts the next.
585 * Drawn means the mod handed the engine that tree: it can't see past that (a
586 * collapsed band, a window behind another), so a stretch runs from one draw to
587 * the next one that changes what shows.
588 */
589export function noteDrawn(tracker: ShownTracker, ad: Ad | undefined, now: number): ShownTracker {
590  const { current } = tracker
591
592  // A refreshed batch can hand the same ad a new serve token: the stretch goes on, under the newest one.
593  if (ad !== undefined && current?.adId === ad.id) {
594    const { serveToken: _old, ...rest } = current
595
596    return { ...tracker, current: { ...rest, ...(ad.serveToken !== undefined && { serveToken: ad.serveToken }) } }
597  }
598
599  const ended = endStretch(tracker, now)
600
601  return ad === undefined
602    ? ended
603    : { ...ended, current: { ...shownOf(ad), isHouse: ad.isHouse, since: now } }
604}
605
606/** The paid ad shown longest this turn, if it stayed at least `minMs`; house ads never count. */
607export function longestPaid(tracker: ShownTracker, minMs: number): Shown | undefined {
608  return Object.values(tracker.best)
609    .filter(one => !one.isHouse && one.ms >= minMs)
610    .reduce<Shown | undefined>((best, one) => (best === undefined || one.ms > best.ms ? one : best), undefined)
611}
612
613/** The queue without impressions too old to earn: the server would credit nothing from them. */
614export const freshOf = (queue: readonly Impression[], now: number): Impression[] =>
615  queue.filter(impression => now - impression.at <= IMPRESSION_MAX_AGE_MS)
616
617/** A report waiting to be sent, with when it was made. */
618export type QueuedReport = AdReport & { at: number }
619
620const isReason = (value: unknown): value is AdReportReason =>
621  value === 'hide' || (REPORT_REASONS as readonly unknown[]).includes(value)
622
623/** The report queue as the store holds it, malformed entries dropped. */
624export function reportQueueOf(raw: unknown): QueuedReport[] {
625  if (!Array.isArray(raw)) {
626    return []
627  }
628
629  return raw.flatMap((item: unknown) => {
630    const one = item as Partial<QueuedReport> | null
631
632    return typeof one === 'object' &&
633      one !== null &&
634      typeof one.adId === 'string' &&
635      one.adId.length > 0 &&
636      isReason(one.reason) &&
637      typeof one.at === 'number'
638      ? [
639          {
640            adId: one.adId,
641            ...(isServeToken(one.serveToken) && { serveToken: one.serveToken }),
642            reason: one.reason,
643            ...(typeof one.note === 'string' && one.note.length > 0 && { note: plain(one.note, REPORT_NOTE_MAX) }),
644            at: one.at,
645          },
646        ]
647      : []
648  })
649}
650
651/** `/ads report [reason] [note]`: the reason word (`other` when absent or unknown) and the rest as the note. */
652export function reportArgsOf(words: readonly string[]): { reason: Exclude<AdReportReason, 'hide'>; note?: string } {
653  const [first = '', ...rest] = words
654  const spoken = first.toLowerCase()
655  const isNamed = (REPORT_REASONS as readonly string[]).includes(spoken)
656  const note = plain((isNamed ? rest : words).join(' ').trim(), REPORT_NOTE_MAX).trim()
657
658  return {
659    reason: isNamed ? (spoken as Exclude<AdReportReason, 'hide'>) : 'other',
660    ...(note.length > 0 && { note }),
661  }
662}
663
664/** The welcome card the first sign-in shows once: Tokenbreak's own, never counted. */
665export const WELCOME_LINES = [
666  '✕ on an ad hides that advertiser for 30 days.',
667  '/ads pause stops ads (1h, 30m, 2h or today); /ads resume brings them back.',
668  'Your earnings: tokenbreak.dev/dashboard/earn',
669  'Turn on updates: /plugin → Marketplaces → tokenbreak → Enable auto-update.',
670] as const
671
672export const EARNINGS_URL = 'https://tokenbreak.dev/dashboard/earn'
673
674/** The line under the banner while the account waits for an earning seat. */
675export const WAITING_NOTICE = "You're on the list for an earning seat. Ads you see now don't pay yet."
676
677/** The newest `cap` impressions. */
678export const capQueue = (queue: readonly Impression[], cap = QUEUE_CAP): Impression[] =>
679  queue.length <= cap ? [...queue] : queue.slice(queue.length - cap)
680
681/**
682 * What an impression takes from the ad on screen: its id, and its own serve
683 * token when it has one, so a token only ever travels with the ad it was served for.
684 */
685export const shownOf = (ad: Ad): Pick<Impression, 'adId' | 'serveToken'> => ({
686  adId: ad.id,
687  ...(ad.serveToken !== undefined && { serveToken: ad.serveToken }),
688})
689
690export const impressionKey = (impression: Impression) =>
691  `${impression.adId}|${impression.format}|${impression.at}|${impression.turnId ?? ''}`
692
693/**
694 * The queue as the store holds it, malformed impressions dropped. A malformed
695 * serve token is left off rather than sent: the server would refuse the batch.
696 */
697export function queueOf(raw: unknown): Impression[] {
698  if (!Array.isArray(raw)) {
699    return []
700  }
701
702  return raw
703    .filter(
704      (item): item is Impression =>
705        typeof item === 'object' &&
706        item !== null &&
707        typeof (item as Impression).adId === 'string' &&
708        isFormat((item as Impression).format) &&
709        typeof (item as Impression).at === 'number',
710    )
711    .map(({ serveToken, turnToken, surface, shownMs, ...impression }) => ({
712      ...impression,
713      ...(isServeToken(serveToken) && { serveToken }),
714      ...(isServeToken(turnToken) && { turnToken }),
715      ...((surface === 'terminal' || surface === 'desktop') && { surface }),
716      ...(typeof shownMs === 'number' && Number.isInteger(shownMs) && shownMs >= 0 && { shownMs }),
717    }))
718}
719
720/** What the band saw of the surface the last time it drew. */
721export type Seen = {
722  columns: number
723  rows: number
724  isFullscreen?: boolean
725  maxRows: number
726}
727
728/**
729 * Whether a pane opened unasked would dock beside the transcript: the
730 * fullscreen layout at 144 columns or more. A build that doesn't say
731 * `isFullscreen` docks when the band's slot is shorter than the screen.
732 */
733export function canDockTheater(seen: Seen | undefined): boolean {
734  if (seen === undefined || seen.columns < THEATER_MIN_COLUMNS) {
735    return false
736  }
737
738  return seen.isFullscreen === true || (seen.isFullscreen === undefined && seen.maxRows < seen.rows)
739}
740
741/** When a pause asked for with `arg` ends: `1h` (the default), `30m`, `2h`, or `today` (local midnight). */
742export function pauseUntil(arg: string, now: number): number | undefined {
743  const spoken = arg.trim().toLowerCase()
744
745  if (spoken === '' || spoken === '1h') {
746    return now + 3_600_000
747  }
748
749  if (spoken === 'today') {
750    const midnight = new Date(now)
751
752    midnight.setHours(24, 0, 0, 0)
753
754    return midnight.getTime()
755  }
756
757  const match = /^(\d{1,3})\s*(m|min|h|hr)$/.exec(spoken)
758
759  if (match === null) {
760    return undefined
761  }
762
763  const amount = Number(match[1])
764  const ms = match[2]?.startsWith('h') ? amount * 3_600_000 : amount * 60_000
765
766  return amount > 0 ? now + Math.min(ms, 7 * 24 * 3_600_000) : undefined
767}
768
769export function describeWait(ms: number): string {
770  const minutes = Math.round(ms / 60_000)
771
772  if (minutes < 60) {
773    return `${minutes} min`
774  }
775
776  const hours = Math.floor(minutes / 60)
777  const rest = minutes % 60
778
779  return rest === 0 ? `${hours}h` : `${hours}h ${rest}min`
780}
781
782// The Theater's built-in picture: a yellow "THIS SPACE FOR RENT" slot on
783// Klein blue with crop marks, drawn as pixel art and scaled up 4x so the
784// terminal's scaling keeps it crisp.
785
786const GLYPHS: Record<string, readonly string[]> = {
787  A: ['010', '101', '111', '101', '101'],
788  B: ['110', '101', '110', '101', '110'],
789  C: ['011', '100', '100', '100', '011'],
790  E: ['111', '100', '110', '100', '111'],
791  F: ['111', '100', '110', '100', '100'],
792  H: ['101', '101', '111', '101', '101'],
793  I: ['111', '010', '010', '010', '111'],
794  K: ['101', '101', '110', '101', '101'],
795  N: ['101', '111', '111', '111', '101'],
796  O: ['010', '101', '101', '101', '010'],
797  P: ['110', '101', '110', '100', '100'],
798  R: ['110', '101', '110', '101', '101'],
799  S: ['011', '100', '010', '001', '110'],
800  T: ['111', '010', '010', '010', '010'],
801  ' ': ['000', '000', '000', '000', '000'],
802}
803
804type Rgb = readonly [number, number, number]
805
806const COBALT: Rgb = [26, 31, 208]
807const YELLOW: Rgb = [255, 230, 0]
808const CHARCOAL: Rgb = [20, 20, 20]
809const CREAM: Rgb = [241, 239, 232]
810
811const ART_W = 64
812const ART_H = 36
813const SCALE = 4
814
815let art: { rgba: string; width: number; height: number } | undefined
816
817function toBase64(bytes: Uint8Array): string {
818  let binary = ''
819
820  for (let i = 0; i < bytes.length; i += 0x8000) {
821    binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
822  }
823
824  return btoa(binary)
825}
826
827/** The fallback Theater picture as RGBA bytes (base64), built once. */
828export function theaterArt(): { rgba: string; width: number; height: number } {
829  if (art !== undefined) {
830    return art
831  }
832
833  const grid: Rgb[] = Array.from({ length: ART_W * ART_H }, () => COBALT)
834  const put = (x: number, y: number, color: Rgb) => {
835    if (x >= 0 && x < ART_W && y >= 0 && y < ART_H) {
836      grid[y * ART_W + x] = color
837    }
838  }
839  const text = (word: string, y: number, color: Rgb) => {
840    const x0 = Math.floor((ART_W - (word.length * 4 - 1)) / 2)
841
842    ;[...word].forEach((char, i) => {
843      ;(GLYPHS[char] ?? GLYPHS[' '])?.forEach((row, dy) => {
844        ;[...row].forEach((bit, dx) => bit === '1' && put(x0 + i * 4 + dx, y + dy, color))
845      })
846    })
847  }
848
849  // The slot, with a dashed charcoal edge.
850  for (let y = 4; y <= 23; y += 1) {
851    for (let x = 6; x <= 57; x += 1) {
852      const isEdge = x === 6 || x === 57 || y === 4 || y === 23
853
854      put(x, y, isEdge && (x + y) % 3 !== 0 ? CHARCOAL : YELLOW)
855    }
856  }
857
858  // Crop marks at the slot's corners.
859  for (const [cx, cy, sx, sy] of [
860    [6, 4, -1, -1],
861    [57, 4, 1, -1],
862    [6, 23, -1, 1],
863    [57, 23, 1, 1],
864  ] as const) {
865    for (let d = 2; d <= 4; d += 1) {
866      put(cx + sx * d, cy, CREAM)
867      put(cx, cy + sy * d, CREAM)
868    }
869  }
870
871  text('THIS SPACE', 8, CHARCOAL)
872  text('FOR RENT', 15, CHARCOAL)
873  text('TOKENBREAK', 28, CREAM)
874
875  const width = ART_W * SCALE
876  const height = ART_H * SCALE
877  const bytes = new Uint8Array(width * height * 4)
878
879  for (let y = 0; y < height; y += 1) {
880    for (let x = 0; x < width; x += 1) {
881      const [r, g, b] = grid[Math.floor(y / SCALE) * ART_W + Math.floor(x / SCALE)] ?? COBALT
882      const at = (y * width + x) * 4
883
884      bytes[at] = r
885      bytes[at + 1] = g
886      bytes[at + 2] = b
887      bytes[at + 3] = 255
888    }
889  }
890
891  art = { rgba: toBase64(bytes), width, height }
892
893  return art
894}
895
896/** The client id `/ads login` sends; the site's device flow accepts no other. */
897export const MOD_CLIENT_ID = 'tokenbreak-mod'
898export const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'
899
900/** `ABCDEFGH` as `ABCD-EFGH`, easier to compare by eye; the site ignores the dash. */
901export const formatUserCode = (code: string) => (code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code)
902
903/** What the site answered `/ads login` with (RFC 8628's device authorization response). */
904export type DeviceCode = {
905  deviceCode: string
906  userCode: string
907  /** Where to approve, with the code filled in when the site gives one. */
908  url: string
909  intervalMs: number
910  expiresInMs: number
911}
912
913export function parseDeviceCode(text: string): DeviceCode | undefined {
914  try {
915    const raw = JSON.parse(text) as Record<string, unknown>
916    const url = typeof raw.verification_uri_complete === 'string' ? raw.verification_uri_complete : raw.verification_uri
917
918    if (typeof raw.device_code !== 'string' || typeof raw.user_code !== 'string' || typeof url !== 'string' || !/^https?:\/\//.test(url)) {
919      return undefined
920    }
921
922    return {
923      deviceCode: raw.device_code,
924      userCode: raw.user_code,
925      url,
926      intervalMs: Math.max(1, Number(raw.interval) || 5) * 1000,
927      expiresInMs: Math.max(60, Number(raw.expires_in) || 900) * 1000,
928    }
929  } catch {
930    return undefined
931  }
932}
933
934/** One poll of the token endpoint: signed in, keep waiting (slower when asked), or give up. */
935export type DevicePoll =
936  | { kind: 'token'; token: string }
937  | { kind: 'wait'; slower: boolean }
938  | { kind: 'stop'; reason: 'denied' | 'expired' | 'failed' }
939
940export function parseDevicePoll(status: number, text: string): DevicePoll {
941  let raw: Record<string, unknown> = {}
942
943  try {
944    raw = JSON.parse(text) as Record<string, unknown>
945  } catch {
946    // A proxy's error page: keep waiting below.
947  }
948
949  if (status === 200 && typeof raw.access_token === 'string' && raw.access_token.length > 0) {
950    return { kind: 'token', token: raw.access_token }
951  }
952
953  switch (raw.error) {
954    case 'authorization_pending':
955      return { kind: 'wait', slower: false }
956    case 'slow_down':
957      return { kind: 'wait', slower: true }
958    case 'access_denied':
959      return { kind: 'stop', reason: 'denied' }
960    case 'expired_token':
961      return { kind: 'stop', reason: 'expired' }
962    case 'invalid_grant':
963    case 'invalid_request':
964      return { kind: 'stop', reason: 'failed' }
965    default:
966      // A 5xx or a dropped connection: try again on the next tick until the code expires.
967      return { kind: 'wait', slower: false }
968  }
969}
970
types/index.d.ts 193 lines
1// Tokenbreak's type contract.
2//
3// The wire types below mirror packages/shared/src/index.ts in the Tokenbreak
4// monorepo (the API's zod schemas). A hooks module cannot import npm
5// packages, so they are copied by hand: change both together.
6
7export type AdFormat = 'banner' | 'theater'
8
9/** Where an ad was drawn: a terminal, or the desktop app's Code tab (text-only ads). */
10export type AdSurface = 'terminal' | 'desktop'
11
12export type AdImage = {
13  /** A whole PNG, base64; at most 2 MiB decoded (the Image element's limit). */
14  png: string
15  width: number
16  height: number
17}
18
19/** A short loop, as PNG frames played in order. */
20export type AdVideo = {
21  /** Whole PNGs, base64, all the same size. */
22  frames: string[]
23  /**
24   * Built-in ads only: absolute paths of PNG files the terminal reads itself, in
25   * place of `frames`. Never taken from the ad server, which may not name files.
26   */
27  files?: string[]
28  /** Frames a second, 1 to 30. */
29  fps: number
30  width: number
31  height: number
32}
33
34/** An ad's sound: a URL the engine fetches, or (built-in ads only) a file the plugin ships. */
35export type AdAudio = { url: string } | { asset: string }
36
37export type Ad = {
38  id: string
39  format: AdFormat
40  brand: string
41  glyph?: string
42  /**
43   * Banner only: the brand's mark as a tiny PNG (36x36, at most 768 bytes), drawn in
44   * two cells. Kept tiny on purpose: a picture's data can be cut off mid-send while
45   * the screen redraws and spill out as text, and a small one goes in one short piece.
46   */
47  logo?: AdImage
48  headline: string
49  /** Banner only: the button's words (`Start free`); `Learn more` when absent. */
50  cta?: string
51  /** `#rrggbb` */
52  accent: string
53  /** Tracked click-through (`/c/<token>`), which logs and redirects. */
54  clickUrl: string
55  /** Theater only. */
56  image?: AdImage
57  /** Theater only: plays in place of `image` where the terminal shows pictures. */
58  video?: AdVideo
59  /** Theater only: cuts of the video in other shapes (9:16, 16:9, 1:1); the Theater plays the one that fills its pane best. */
60  videos?: AdVideo[]
61  /** Theater only: the video's sound, played only when the person presses the sound button. */
62  audio?: AdAudio
63  isHouse: boolean
64  /** Paid ads only: the campaign, which `✕` hides on this machine. */
65  campaignId?: string
66  /**
67   * Paid ads only: the server's signed receipt for this one serve, at most 512
68   * characters. Each impression of the ad hands it back; house ads have none.
69   */
70  serveToken?: string
71}
72
73/** The mod's newest release, and the oldest that still earns. */
74export type ModRelease = {
75  latest: string
76  min: string
77  /** This build is switched off: show nothing, report nothing. */
78  blocked?: boolean
79}
80
81/** Whether the account holds one of the beta's earning seats, or waits for one (house ads only). */
82export type Seat = 'earning' | 'waiting'
83
84export type AdBatch = {
85  ads: Ad[]
86  ttlSeconds: number
87  servedAt: string
88  mod?: ModRelease
89  seat?: Seat
90}
91
92/** Where this build stands: current, an update out, too old to earn, or switched off by the server. */
93export type UpdateState =
94  | { kind: 'current' }
95  | { kind: 'available'; latest: string }
96  | { kind: 'required'; latest: string }
97  | { kind: 'blocked'; latest: string }
98
99export type Impression = {
100  adId: string
101  format: AdFormat
102  /** Epoch milliseconds. */
103  at: number
104  turnId?: string
105  /** The `serveToken` of the ad that was shown, when it had one; never another ad's. */
106  serveToken?: string
107  /** The server's token for the turn (`POST /api/v1/turns`). Paid impressions always carry one. */
108  turnToken?: string
109  /** Where the ad was drawn. */
110  surface?: AdSurface
111  /** The longest continuous stretch the ad was on screen during the turn, in ms. */
112  shownMs?: number
113}
114
115/** `POST /api/v1/turns`, sent at the start of each of the person's turns. */
116export type TurnRequest = {
117  deviceId: string
118  surface: AdSurface
119}
120
121/** The server's answer: a signed token naming the turn. */
122export type TurnGrant = {
123  turnId: string
124  turnToken: string
125  /** Epoch ms, the server's clock. */
126  issuedAt: number
127}
128
129export type AdReportReason = 'scam' | 'misleading' | 'offensive' | 'broken' | 'other' | 'hide'
130
131/** `POST /api/v1/reports`: `/ads report`, and `✕` (reason `hide`). */
132export type AdReport = {
133  adId: string
134  serveToken?: string
135  reason: AdReportReason
136  note?: string
137}
138
139export type ImpressionBatch = {
140  deviceId: string
141  /** The reporting mod's version; the server credits nothing from one under its minimum. */
142  modVersion?: string
143  impressions: Impression[]
144}
145
146/** How the banner is drawn: `pill` a colored call-to-action, `rule` an accent bar and an underlined link, `card` a bordered box. */
147export type BannerStyle = 'pill' | 'rule' | 'card'
148
149/** Where the ads on screen came from: the API, the store's last batch, or the module itself. */
150export type AdSource = 'server' | 'cache' | 'built-in'
151
152/**
153 * Who the mod is signed in as. Ads show and count only once signed in: `pending` while
154 * `/ads login` waits for the code to be approved on the site.
155 */
156export type Account =
157  | { kind: 'out' }
158  | { kind: 'pending'; userCode: string; url: string }
159  | { kind: 'in'; login: string }
160
161/** The Theater ad showing in the pane, for the turn it belongs to. */
162export type TheaterShowing = {
163  adId: string
164  /** The shown ad's `serveToken`, for the impression the turn's end counts. */
165  serveToken?: string
166  turnId: string
167  isPlaced: boolean
168}
169
170declare module 'claude-code' {
171  interface PluginState {
172    tokenbreak: {
173      ads: Ad[]
174      source: AdSource
175      bannerIndex: number
176      pausedUntil: number | null
177      theater: TheaterShowing | null
178      bannerStyle: BannerStyle
179      theaterSound: boolean
180      update: UpdateState
181      account: Account
182      /** Whether the banner may show: during a turn and for a while after it. */
183      bannerUp: boolean
184      /** Campaigns `✕` hid on this machine, each with when the hide ends (epoch ms). */
185      hidden: Record<string, number>
186      /** The account's seat, as the ad server last said; null until it says. */
187      seat: Seat | null
188      /** Whether the welcome card is still to be shown after the first sign-in. */
189      welcome: boolean
190    }
191  }
192}
193