SLOPSHOPPER

topic-filter

Keep unrelated topics from pulling Claude off your code: listed terms become stable placeholder names (or their lines are dropped) in tool output, prompts…

panespinnerguardcommandtoastprompt
★ 1v0.8.0GPL-3.0-onlyupdated 2026-10-22lperezmo/topic-filter-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · topic-filter
│ ┃ topic-filter ✕ › fix the failing auth test and add an audit log call │ ┃ 0 hidden this session │ ┃ Nothing yet. ● topic-filter: topic-filter is off, nothing chosen to hide. Switch o │ ┃ ● topic-filter: Topics file: /Users/dev/.claude/topic-filter/topics.j │ ┃ 1: Lists 2: Feed whole session ⏺ Read(src/auth.ts) │ ┃ Hidden terms show here as Claude reads ⎿ Read 6 lines │ ┃ them. ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /topic-filter │ ┃ ● topic-filter: Run /topic-filter packs to see every pack, /topic-fil │ ┃ ● topic-filter: and /topic-filter sidebar to watch it in a pane as it │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts auto-accept edits & topic-filter: off, nothing chosen

Draws

Pane · topic-filter
0 hidden this session Nothing yet. 1: Lists 2: Feed whole session Hidden terms show here as Claude reads them.
README

<img src=".claude-plugin/icon.svg" alt="topic-filter logo: a benzene ring swapped for code braces" width="200">

test

topic-filter-mod

Code with Claude without your past life tagging along. Chosen topics become neutral placeholders before Claude reads them; nothing on disk changes.

Your machine carries everything you have ever worked on: a career in chemistry, a thesis, old side projects, a client's name. None of it has anything to do with the bug you are fixing today, but Claude reads it anyway, in file names, notes, memory and command output, and unrelated material pulls a session sideways. You should be free to work on the code in front of you without explaining your history first.

topic-filter is a Claude Mod (a Claude Code plugin built on function hooks) that keeps chosen topics out of the way. Before the model reads tool output, prompts, CLAUDE.md and skills, each listed term becomes a stable placeholder (Teotihuacan becomes Teacup7), or the lines that mention it disappear. Your repos, notes and memory stay as they are.

A Claude Code session summarizing a demo project: its reply uses codenames in place of the hidden terms, while the sidebar lists each hidden term, its codename, and where the hits came from

Claude answers in codenames; the sidebar, shown to you only, maps each one back and counts where it was hidden. The dim topic-filter: 50 hidden sits in the prompt footer.

Install

1. Install the plugin. It needs Claude Code 2.1.287 or newer, where mods load by default. This repository is its own marketplace:

claude plugin marketplace add lperezmo/topic-filter-mod
claude plugin install topic-filter@topic-filter-mod

Or from inside Claude Code: /plugin marketplace add lperezmo/topic-filter-mod, then /plugin install topic-filter@topic-filter-mod.

2. Choose what to hide. Run /config and type topic-filter to find the plugin's rows. Enter or Space flips a switch or edits a field:

The /config screen listing topic-filter's rows: one switch per built-in pack, other packs, the sidebar switches and the topics file

SettingDefaultWhat it does
Hide anthropology, biology, chemistry, geneticsoffOne switch per built-in pack
Other packsemptyNames of your own packs, comma-separated
Start pausedoffEvery session starts paused; /topic-filter on turns it on for that session
SidebaroffOpens the sidebar at every start
Sidebar: counts onlyoffThe sidebar shows counts by list, never a word or file name
Extra words to hideemptyComma-separated words or names; kept in secure storage, not in settings.json
Topics file (advanced)emptyWhere the topics file lives, if you want one

Extra words to hide is kept secret, so /config does not list it: set it in /plugin: Installed, then topic-filter, then configure it. That screen shows every setting as a text box; there, a switch takes the word true or false (a y is saved as false).

What you type in either place goes to the plugin, never into the conversation. A change applies right away, no restart needed. To hide a repo, see Hiding repositories.

3. Restart Claude Code once after installing: sessions that were already running do not load the plugin. The prompt footer then shows a dim topic-filter: M hidden beside the other modes, /topic-filter shows what is set to be hidden and where each part comes from, and /topic-filter log shows what was actually hidden and where (both shown to you only).

The topics file is optional. Use it for what the settings cannot express: drop-line or restore modes for your own words, several lists, exclude. Edit it in an editor: it lists the very terms you want kept out of the session. Its lists add to the settings'.

Needs Claude Code 2.1.287 or newer. The stable update channel can lag behind that, so use the latest channel if claude --version shows something older. CI runs the tests on 2.1.287 and the latest release, and again every week, since the mods API may change between releases.

Update

Claude Code does not update plugins from third-party marketplaces on its own unless you turn that on. Pick one:

  • Automatic (recommended). Once, in Claude Code: /plugin, then Marketplaces, then topic-filter-mod, then enable auto-update. New versions install when Claude Code starts.
  • By hand, whenever you want the latest:
  claude plugin marketplace update topic-filter-mod
  claude plugin update topic-filter@topic-filter-mod

Either way, restart Claude Code afterwards; running sessions keep the old version. claude plugin list shows the version you have. Updates never touch your topics file or your own packs in ~/.claude/topic-filter/.

Upgrading to 0.8.0.

  • Placeholder names are drawn from a new random seed, so every term gets a new codename once. Sessions started before the upgrade keep the old ones.
  • New Start paused setting, off by default.

Upgrading to 0.7.0.

  • The built-in cybersecurity pack is gone. If a list in your topics file has "pack": "cybersecurity", tool calls pause until you take it out. Its /config switch is gone too, and a saved value is ignored.
  • A list that uses a pack can no longer set "restore": true. Such a topics file is now a settings problem: tool calls pause until the restore is removed.
  • The system prompt, Claude Code's own reminders and built-in tools' descriptions are no longer filtered (see Limits).

To remove it: claude plugin uninstall topic-filter@topic-filter-mod. Your topics file stays until you delete it.

Using it

The motivating case: gh repo list shows repositories a session has no reason to see. List their names in a drop-line list, and they drop out of every listing the model reads.

Run /topic-filter in a session to see each list and where its terms come from, /topic-filter packs to see every topic pack and which lists use it, /topic-filter off and on to pause and resume it, and /topic-filter reload after editing packs. The overview and the pack list show counts, never terms. Edits to the topics file and packs are picked up on their own.

/topic-filter log shows what was hidden this session and where it came from: each source (a file read, a command, CLAUDE.md, your prompt) with the real terms, the placeholder each became, and how many lines each drop-line term removed. The dropped lines themselves are not shown.

Hidden in what Claude reads with every request (CLAUDE.md, context blocks):
  C:/work/CLAUDE.md
      Teotihuacan -> Marzipan (x1)
Hidden as it came in (most recent last):
  Bash gh repo list
      2 lines dropped by "hidden-repos": secret-repo (x1), old-thesis (x1)
  Read C:/notes/trip.md
      Teotihuacan -> Marzipan (x3)

The log is kept in memory only and ends with the session. The mod never writes it to a file of its own, since that would be a second copy of what you are hiding. /topic-filter log clear empties the second part sooner; the first stays, as that text is still in every request.

Every /topic-filter output is shown to you only: it names packs, lists and terms, so it is printed for you and not added to the conversation. Two caveats for the log, which names real terms:

  • Claude Code copies every such line into its debug log, so with --debug or --debug-file the terms end up in that file.
  • Another plugin that hooks ui.log sees the lines too.

The footer's M hidden counts each hidden word and each dropped line, not distinct terms. The footer label is drawn on the terminal and in the desktop app.

The label is the only thing topic-filter shows under the prompt; it never pins a warning. While all is well it is dim. When something needs you it turns yellow and says what: topic-filter: paused, topic-filter: off, nothing chosen, topic-filter: blocking tool calls, run /topic-filter, or a count with settings problem. /topic-filter then gives the details.

What a subagent reads is filtered the same way, and its placeholders are refused in its tool calls too. The log lists each subagent under its own heading.

The sidebar

/topic-filter sidebar opens a pane that shows what has been hidden so far and updates as it happens. It is the right-hand pane in the screenshot at the top.

  • Lists is a tree: each list with a bar for its share, then its terms and the placeholder each became, then the files and commands each term was hidden in. Click a row (or reach it with ctrl+x tab, then Tab, and press Enter) to open or close it. Expand opens the whole tree to one depth: lists only, their terms, or everything. From 30 distinct terms on, it starts at lists only.
  • Feed is each hit as it happened, newest first: when, what Claude was reading, and which terms it hid there.
  • Where it came from sums hits by the kind of source: files, prompts, web pages, commands, searches, skills, and context such as CLAUDE.md.

Open a subagent's transcript from the tasks list and the sidebar shows only what that subagent read.

  • Where it shows. In the fullscreen layout it docks beside the transcript; otherwise it opens above the prompt. Opened by the setting rather than the command, it waits for a terminal at least 144 columns wide.
  • Next to other plugins' panes. Claude Code shows one pane at a time and turns the others into tabs: click a tab to switch, or press ctrl+x tab to move into the panes, then Tab to a tab and Enter. ctrl+x x (or the pane's close mark) closes it, and /topic-filter sidebar toggles it.
  • Every start. The Sidebar switch in /config opens it at every start. Turning the switch off closes it.
  • Screen sharing. It shows the real words. Sidebar: counts only keeps it to counts by list, with no words, placeholders or file names, in the tree and the feed alike.

The sidebar is drawn in your terminal and is not part of the conversation.

Pausing it

/topic-filter off (or pause, stop) pauses filtering for the session: tool output reaches Claude whole and placeholders are no longer refused, so Claude can act on something hidden, such as deleting a hidden repo. /topic-filter on (or resume, start) turns it back on and says how many lists and terms it resumed with.

  • Only you can pause it. The command pauses only when you type it at the prompt. Sent through Remote Control, whose sender Claude Code cannot confirm, or run by Claude, a subagent or another plugin, it leaves the filter on. Anything may turn it back on.
  • It never outlasts the session. The pause is kept in memory only: a restart, /clear or a reload of the plugin goes back to what the settings say.
  • Or start every session paused. Turn on Start paused in /config and nothing is hidden until you type /topic-filter on, which lasts for that session.
  • You can see it. The footer label reads topic-filter: paused in place of the count, and the sidebar says so at the top.
  • Claude is told. Pausing and resuming each leave Claude a one-line note, so it knows whether placeholders will be refused.
  • Two guards stay on. The topics file is still not read into the session, since that would bring every listed term back into context. A file Claude read with content hidden still cannot be overwritten whole until Claude reads it again, in full, while paused.

What Claude read before the pause keeps its placeholders.

The topics file

{
  "placeholder": "codename",
  "informModel": true,
  "lists": [
    { "name": "hidden-repos", "mode": "drop-line", "terms": ["my-private-experiment", "old-client-work"] },
    { "name": "anthropology", "terms": ["Teotihuacan", "Chichen Itza", "Maya", "Pyramids of Giza"] },
    { "name": "email-contacts", "restore": true, "terms": ["Ada Lovelace"] }
  ]
}
FieldDefaultMeaning
placeholdercodenamecodename gives each term a capitalized word and a number (Bubblegum7, Kazoo12); the number keeps it from ever matching a word you really write. tag gives [hidden-3fa2c1].
informModeltrueTell the model that placeholders exist and how to treat them. Without it the model tends to treat Bubblegum as a real name and go looking for it.
lists[].namelist NA label for you. It never reaches the model.
lists[].terms[]The terms to hide.
lists[].modereplacereplace swaps each term for its placeholder. drop-line removes every line that mentions a term; in JSON (gh ... --json, MCP results) the whole array item goes. A typed prompt always gets placeholders, never lost lines.
lists[].matchwordword matches whole words only. substring matches inside words too (maya in Mayapan).
lists[].restorefalseWhen the model uses this list's placeholder in a tool call, write the real term back instead of refusing. For your own names (contacts, client names) that a tool must write out exactly. Not allowed on a list that uses a pack.
lists[].packnoneA topic pack whose terms join the list.
lists[].exclude[]Terms to leave out of the list, whatever brought them in (a pack or terms). Matched the same forgiving way as terms.

Matching ignores case and accents (Teotihuacán = teotihuacan), treats spaces, hyphens and underscores as one separator (secret repo also finds secret-repo and secret_repo), and takes plural and possessive endings (Mayas, Maya's). Terms shorter than two characters are ignored.

A term keeps the same placeholder in every session. The names are derived from the term and a random seed kept in the plugin's store, so memory files and the prompt cache stay consistent, and the word list alone does not reveal the mapping.

Topic packs

A pack is a ready-made term list for one topic, so you do not have to type every name yourself. Point a list at one:

{ "lists": [{ "name": "anthropology", "pack": "anthropology", "exclude": ["Maya"], "terms": ["my extra word"] }] }

The list keeps its own mode and match (restore is not allowed on a pack list), exclude drops pack terms you do not want hidden, and terms adds your own. /topic-filter packs lists every pack with what it covers and its counts (never its terms), and marks which of your lists use it.

A pack name that does not exist is never ignored quietly, since that would hide nothing while looking set up. Tool calls pause, a toast names the missing pack, the footer label turns yellow, and /topic-filter suggests the closest real one ("Did you mean paleontology?") and lists what is available. The session is told only that the settings need attention.

Built-in packs ship in this repository's packs/ folder:

PackTermsCovers
anthropology2,167Ancient Mesoamerican, Andean and Egyptian sites, civilizations, rulers and deities; anthropology and archaeology vocabulary
biology270Molecular biology techniques, cellular processes, anatomical terms
chemistry940Chemical elements, named reactions, functional groups, laboratory equipment
genetics2,591Genetic disorders and syndromes; genetics and heredity vocabulary

They are built by the script in tools/packs/ from Wikipedia and Wiktionary categories, word-frequency data and a dry run against ordinary code, with a review report per pack in tools/packs/reports/.

Your own packs go in ~/.claude/topic-filter/packs/<name>.json. A pack there replaces a built-in one of the same name, so to customize a built-in pack, copy it there and edit the copy. Never edit the plugin's own folder: Claude Code replaces it on every update. The format:

{
  "name": "my-topic",
  "description": "What it covers.",
  "terms": ["Hidden on sight", "Another one"],
  "hints": ["loose", "related", "words"]
}

Only terms hide anything today; hints are kept for a later version that takes a closer look at paragraphs mentioning them. Editing a pack file takes effect on the next tool call, no restart needed.

Hiding repositories without deleting them

Put the repository names in a list whose mode is drop-line, in the topics file or in Extra words to hide (a replace list, so those get placeholders instead):

{ "name": "hidden-repos", "mode": "drop-line", "terms": ["some-repo", "another-repo"] }

Each one vanishes from gh repo list, gh api JSON, GitHub MCP results, paths and file contents. Take the name out to bring it back. The topics file is not read into the session, since that would bring every listed name back into context.

What it covers

Text reaches the model through many doors, and there is no single outgoing request to filter (turn.step carries a message count, not the messages). So every door but the system prompt is hooked:

What the model readsEvent
Tool results: Bash, Read, Grep, Glob, WebFetch, MCP tools, subagent answers, errorstool.call, on the way up
Your typed promptprompt.submit
CLAUDE.md and the other first-message context blocksprompt.context
Mentioned and edited files, nested CLAUDE.md, queued prompts, context added by classic hooks and plugins (Claude Code's own reminders pass unchanged)prompt.attachment
Skill text, MCP tool descriptions (built-in tools keep theirs), slash command outputskill.prompt, tool.describe, command.run
Remote Control and peer deliveriessession.receive

Each of these hooks changes one thing: it replaces listed terms in the text with their placeholders (or drops the line, for a drop-line list) and passes everything else on unchanged. With informModel on (the default), Claude also gets one short note that placeholders exist, quoted below. The system prompt is never hooked or changed. prompt.submit filters every prompt that passes through it, yours or one another plugin submits; the mod never submits a prompt itself.

The note Claude gets once per session, in the first message's context:

Some names in this session may be placeholders written by the user's topic-filter mod: capitalized numbered codenames such as Bubblegum7 or Kazoo12, or tags such as [hidden-3fa2c1]. Each stands for an item the user has set aside as off-topic for this session, and lines about some of those items are removed entirely. Treat a placeholder as an opaque name and do not guess what it stands for. Mentioning placeholders in replies is fine. A tool call (command, search, file edit) that uses one is refused, unless the note on the output it came from says that placeholder may be used.

Tool output that had something replaced carries a one-line note saying how many terms were replaced and whether their placeholders may be used.

Going the other way:

  • Guard. A tool call that uses a placeholder is refused, so the model cannot act on what it cannot see, and never writes Bubblegum into a file where the real word was. Subagent prompts, todos and questions to you are exempt, since they are the model talking to itself or to you.
  • Restore. The one case where the mod changes a tool's input: for a list with "restore": true, a placeholder from that list in a tool call is written back as the real term before the tool runs. This applies to every tool (Bash, Read, Edit, Write, Grep, Glob, WebFetch, MCP tools and the rest) except Agent, Task, TodoWrite, TaskCreate, TaskUpdate, AskUserQuestion, ExitPlanMode and SendMessage, whose input is passed on unchanged. The tool then runs on the real word, not on what Claude wrote. Without a restore list, tool input is never changed.
  • No blind overwrites. Once the model has read a file with something hidden, a
Source 8 files
hooks/register.ts 1032 lines
1// topic-filter: hides chosen topics from the model.
2//
3// Every place text enters the model's context, except the system prompt, is hooked, and the listed
4// terms in it become placeholder names (or their lines are dropped) before
5// the model reads it: tool results on their way up from core, the person's
6// prompt, the first message's context blocks
7// (CLAUDE.md), injected attachments (mentioned files, reminders, classic
8// hook context), skill text, tool descriptions, slash command output and
9// deliveries from outside the session. `turn.step` carries no messages, so
10// there is no single outgoing request to filter instead. The system prompt
11// is never hooked or changed.
12//
13// On the way out, a tool call that uses a placeholder is refused, so the
14// model cannot act on what it cannot see and never writes a placeholder over
15// the real word in a file. A list marked `restore` puts the real term back
16// instead.
17//
18// Every hook fails closed: when filtering throws or overruns, what it was
19// filtering is withheld, never passed through.
20
21import type { AgentInfo, EngineInterface, FsEntry, On, PluginOptions, ToolCallResult } from 'claude-code'
22
23import {
24  closestName,
25  ConfigError,
26  optionLists,
27  parseConfig,
28  parsePack,
29  SLUG,
30  type Config,
31  type Pack,
32} from './config.ts'
33import { HiddenLog, type LogMode, type SourceKind } from './log.ts'
34import { fnv1a } from './placeholders.ts'
35import { openRows, SIDEBAR_ID, sidebarView, type Depth, type SidebarView } from './sidebar.tsx'
36import { Filter, forEachString, newTally, noteFor, type Tally } from './redact.ts'
37
38const COMMAND = 'topic-filter'
39const DEFAULT_CONFIG = '.claude/topic-filter/topics.json'
40
41/** The person's own packs, under the home directory; the plugin's folder is replaced on update. */
42const USER_PACKS = '.claude/topic-filter/packs'
43
44/** How long a checked config stays trusted before the file is looked at again. */
45const RECHECK_MS = 1000
46
47/**
48 * Tools whose input is the model talking to itself or to the person, never
49 * to the world: a placeholder there is harmless, and a restore there would
50 * hand the real term to a model (a subagent's prompt). Neither guard nor
51 * restore touches them.
52 */
53const MODEL_FACING_TOOLS = new Set([
54  'Agent',
55  'Task',
56  'TodoWrite',
57  'TaskCreate',
58  'TaskUpdate',
59  'AskUserQuestion',
60  'ExitPlanMode',
61  'SendMessage',
62])
63
64/**
65 * The attachments the engine writes from the person's own content: files
66 * mentioned or edited, nested CLAUDE.md files, prompts queued into a turn.
67 * Its other attachments (reminders, mode changes, listings) are Claude Code's
68 * own text and pass unchanged; settings-hook and plugin context is filtered.
69 */
70const CONTENT_ATTACHMENTS = new Set(['file', 'edited_text_file', 'nested_memory', 'queued_command'])
71
72/** Whether a tool comes from an MCP server; by name on a build without `provider`. */
73const isMcpTool = (e: { tool: string; provider?: { plugin?: string } }) =>
74  e.provider?.plugin?.startsWith('mcp:') ?? e.tool.startsWith('mcp__')
75
76/** Whether the mod filters this attachment. */
77const filtersAttachment = (e: { type: string; origin?: { kind: string } }) =>
78  e.origin?.kind !== 'engine' || CONTENT_ATTACHMENTS.has(e.type)
79
80/** The context block that tells the model placeholders exist; stable, so the prompt cache holds. */
81const EXPLAINER =
82  "Some names in this session may be placeholders written by the user's topic-filter mod: capitalized " +
83  'numbered codenames such as Bubblegum7 or Kazoo12, or tags such as [hidden-3fa2c1]. Each stands for an item the ' +
84  'user has set aside as off-topic for this session, and lines about some of those items are removed entirely. Treat a ' +
85  'placeholder as an opaque name and do not guess what it stands for. Mentioning placeholders in replies ' +
86  'is fine. A tool call (command, search, file edit) that uses one is refused, unless the note on the ' +
87  'output it came from says that placeholder may be used.'
88
89/** The topics file as last read, and the filter built from it. */
90type Loaded = {
91  key: string
92  path: string
93  /** The pack files the key covers, found or not. */
94  deps: string[]
95  /** Which pack each list got its terms from, by list index. */
96  packsUsed: Map<number, PackUse>
97  /** The settings the filter was built from: the last good ones. */
98  config: Config | null
99  /** The settings as the file says now, even when they could not be used; what the person is shown. */
100  latest: Config | null
101  filter: Filter | null
102  /** Why the file could not be used; the filter kept is the last good one, if any. */
103  error?: string
104}
105
106let loaded: Loaded | undefined
107let loading: { key: string; promise: Promise<Loaded> } | undefined
108let checkedAt = 0
109
110/** Items hidden since the session started, for the status line. */
111let hiddenCount = 0
112
113/** What was hidden and where, for `/topic-filter log`: memory only, shown to the person only. */
114const hiddenLog = new HiddenLog()
115
116/**
117 * Whether filtering is paused, by `/topic-filter off` or by the "Start
118 * paused" setting. Memory only: a restart, /clear or a reload goes back to
119 * what the setting says, so a forgotten pause does not outlive the session.
120 */
121let paused = false
122
123/** Whether the person set every session to start paused. */
124const startsPaused = () => pluginOptions.startPaused === true
125
126/**
127 * Who may pause: the person at this terminal's prompt. Remote Control is left
128 * out, as the engine cannot attest its sender is the owner. Anyone may resume.
129 */
130const MAY_PAUSE = new Set(['composer'])
131
132/** Whether this module has matched the sidebar to its setting yet: once per load, as a /config change reloads it. */
133let sidebarSynced = false
134
135/**
136 * Opens the sidebar when its setting is on, and closes it when the setting
137 * was just turned off. The setting's last value is kept in the store, so a
138 * pane the person opened with `/topic-filter sidebar` is left alone.
139 */
140async function syncSidebar($: EngineInterface): Promise<void> {
141  if (sidebarSynced) return
142  sidebarSynced = true
143  try {
144    const isOn = pluginOptions.showSidebar === true
145    const was = await $.store.get('sidebar')
146    if (isOn) await $.ui.open({ id: SIDEBAR_ID, title: 'topic-filter' })
147    else if (was === true) await $.ui.close({ id: SIDEBAR_ID })
148    if (was !== isOn) await $.store.set('sidebar', isOn)
149  } catch {
150    // The filter works without its sidebar; the next call tries again.
151    sidebarSynced = false
152  }
153}
154
155/** A subagent as the log and the sidebar name it. */
156const agentLabel = (info: AgentInfo) => info.name ?? (info.description.trim() === '' ? info.type : info.description)
157
158/** Every subagent's label by id; empty when they cannot be listed. */
159async function agentLabels($: EngineInterface): Promise<Map<string, string>> {
160  try {
161    return new Map((await $.agent.list()).map((info) => [info.id, agentLabel(info)]))
162  } catch {
163    return new Map()
164  }
165}
166
167/** Subagent labels the sidebar has looked up, so a redraw lists the agents only for one it has not seen. */
168const sidebarLabels = new Map<string, string>()
169
170async function sidebarLabel($: EngineInterface, agentId: string): Promise<string> {
171  if (!sidebarLabels.has(agentId)) for (const [id, name] of await agentLabels($)) sidebarLabels.set(id, name)
172  return sidebarLabels.get(agentId) ?? agentId
173}
174
175/** Which kind of source a tool's output is, for the sidebar's bars. */
176function kindOfTool(tool: string): SourceKind {
177  if (['Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'NotebookRead'].includes(tool)) return 'files'
178  if (['Bash', 'PowerShell', 'BashOutput', 'Monitor', 'KillShell'].includes(tool)) return 'commands'
179  if (['WebFetch', 'WebSearch'].includes(tool)) return 'web'
180  if (['Grep', 'Glob', 'LS', 'ToolSearch'].includes(tool)) return 'searches'
181  if (tool === 'Skill') return 'skills'
182  return 'tools'
183}
184
185/** The input fields that say what a tool call was about, in order of preference. */
186const SOURCE_KEYS = ['file_path', 'notebook_path', 'command', 'url', 'pattern', 'query', 'path', 'description']
187
188/** A tool call as the log names it: the tool and what it was about. */
189function toolSource(tool: string, input: Record<string, unknown>): string {
190  for (const key of SOURCE_KEYS) {
191    const value = input[key]
192    if (typeof value === 'string' && value.trim() !== '') return `${tool} ${value}`
193  }
194  return tool
195}
196
197/** The `configPath` option; empty means the default under the home directory. */
198let configured = ''
199
200/** The plugin's settings: what to hide besides the topics file (packs, extra words). */
201let pluginOptions: PluginOptions = {}
202
203/** Files the model has read with something hidden, by pathKey. */
204const filteredFiles = new Set<string>()
205
206/** A path as a set key: one slash direction, one case. */
207const pathKey = (path: string) => path.replace(/\\/g, '/').toLowerCase()
208
209/** Whether what the model read lacks something a whole-file rewrite would lose. */
210const hidesContent = (f: Filter, seen: Tally) => seen.dropped > 0 || [...seen.names].some((name) => f.guarded.has(name))
211
212async function homeOf($: EngineInterface): Promise<string> {
213  // USERPROFILE first: on Windows it is where Claude Code keeps ~/.claude,
214  // while HOME may be unset or a POSIX spelling from a Unix-like shell.
215  return (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? ''
216}
217
218async function pathOf($: EngineInterface): Promise<string> {
219  const home = await homeOf($)
220  if (configured === '') return `${home}/${DEFAULT_CONFIG}`
221  return configured.startsWith('~') ? home + configured.slice(1) : configured
222}
223
224/** A file's identity for the cache key: its path and, when it exists, its size and time. */
225async function statKey($: EngineInterface, path: string): Promise<string> {
226  try {
227    const stat = await $.fs.stat(path)
228    return `${path}|${stat.mtimeMs}|${stat.size}`
229  } catch {
230    return `${path}|missing`
231  }
232}
233
234/** Which pack file a list got its terms from. */
235type PackUse = { name: string; where: PackWhere; terms: number }
236
237type PackWhere = 'yours' | 'built-in'
238
239/** One pack file found on disk. */
240type PackEntry = {
241  name: string
242  where: PackWhere
243  /** Undefined when the file is not a valid pack. */
244  pack?: Pack
245  /** A built-in pack that one of yours with the same name replaces. */
246  isReplaced: boolean
247}
248
249/**
250 * The terms of every pack the topics file names, per list index, and which
251 * file each came from. The person's own pack wins over a built-in one of the
252 * same name, so copying a built-in pack there and editing it is how one is
253 * customized; the plugin's own folder is replaced on every update.
254 */
255async function loadPacks(
256  $: EngineInterface,
257  config: Config,
258  home: string,
259): Promise<{ terms: Map<number, string[]>; used: Map<number, PackUse> }> {
260  const terms = new Map<number, string[]>()
261  const used = new Map<number, PackUse>()
262
263  for (const [i, list] of config.lists.entries()) {
264    if (list.pack === undefined) continue
265    const [mine, builtIn] = packPaths(home, $.plugin.root, list.pack)
266
267    let text: string
268    let where: PackWhere = 'yours'
269    try {
270      text = await $.fs.read(mine)
271    } catch {
272      where = 'built-in'
273      try {
274        text = await $.fs.read(builtIn)
275      } catch {
276        const names = [...new Set((await findPacks($, home)).map((entry) => entry.name))]
277        const where = list.setting === undefined ? `lists[${i}]` : `the ${list.setting} setting`
278        throw new ConfigError(missingPack(list.pack, where, names))
279      }
280    }
281    const pack = parsePack(text, list.pack)
282    terms.set(i, pack.terms)
283    used.set(i, { name: list.pack, where, terms: pack.terms.length })
284  }
285
286  return { terms, used }
287}
288
289/** What to tell the person about a pack that does not exist; its first sentence fits a status line. */
290function missingPack(name: string, where: string, available: readonly string[]): string {
291  const guess = closestName(name, available)
292  return [
293    `Pack "${name}" (${where}) was not found.`,
294    guess === undefined ? '' : `Did you mean "${guess}"?`,
295    available.length === 0 ? 'No packs are installed.' : `Available: ${available.join(', ')}.`,
296    `Run /topic-filter packs to see what each covers, or make your own at ~/${USER_PACKS}/${name}.json.`,
297  ]
298    .filter((part) => part !== '')
299    .join(' ')
300}
301
302const count = (n: number, noun: string) => `${n.toLocaleString('en-US')} ${noun}${n === 1 ? '' : 's'}`
303
304/** Where a pack may be: the person's folder first, then the plugin's own. */
305function packPaths(home: string, root: string, name: string): [string, string] {
306  return [`${home}/${USER_PACKS}/${name}.json`, `${root}/packs/${name}.json`]
307}
308
309/** Every pack file there is, yours first, each folder by name. */
310async function findPacks($: EngineInterface, home: string): Promise<PackEntry[]> {
311  const places: { where: PackWhere; dir: string }[] = [
312    { where: 'yours', dir: `${home}/${USER_PACKS}` },
313    { where: 'built-in', dir: `${$.plugin.root}/packs` },
314  ]
315  const mine = new Set<string>()
316  const found: PackEntry[] = []
317
318  for (const { where, dir } of places) {
319    let entries: FsEntry[]
320    try {
321      entries = await $.fs.list(dir)
322    } catch {
323      continue
324    }
325    for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {
326      const name = entry.name.replace(/\.json$/, '')
327      if (entry.kind !== 'file' || name === entry.name || !SLUG.test(name)) continue
328      let pack: Pack | undefined
329      try {
330        pack = parsePack(await $.fs.read(`${dir}/${entry.name}`), name)
331      } catch {
332        pack = undefined
333      }
334      found.push({ name, where, pack, isReplaced: where === 'built-in' && mine.has(name) })
335      if (where === 'yours') mine.add(name)
336    }
337  }
338
339  return found
340}
341
342/**
343 * The pack listing, for the person only: every pack with what it covers,
344 * its counts, and which of your lists use it, plus any list naming a pack
345 * that does not exist.
346 */
347async function packListing($: EngineInterface, l: Loaded): Promise<string[]> {
348  const entries = await findPacks($, await homeOf($))
349  const users = new Map<string, string[]>()
350  for (const list of l.latest?.lists ?? []) {
351    if (list.pack !== undefined) users.set(list.pack, [...(users.get(list.pack) ?? []), `"${list.name}"`])
352  }
353
354  const lines = ['Topic packs (yours first, then built-in):']
355  for (const entry of entries) {
356    const head = `  ${entry.name} (${entry.where})`
357    if (entry.isReplaced) {
358      lines.push(`${head}: replaced by yours`)
359      continue
360    }
361    if (entry.pack === undefined) {
362      lines.push(`${head}: not a valid pack file`)
363      continue
364    }
365    const inUse = users.get(entry.name)
366    lines.push(
367      `${head}: ${count(entry.pack.terms.length, 'term')}, ${count(entry.pack.hints.length, 'hint')}` +
368        (inUse === undefined ? '' : `, used by ${inUse.join(', ')}`),
369    )
370    if (entry.pack.description !== '') lines.push(`      ${entry.pack.description}`)
371  }
372  if (entries.length === 0) lines.push('  none installed')
373
374  const names = new Set(entries.map((entry) => entry.name))
375  for (const [name, lists] of users) {
376    if (!names.has(name)) lines.push(`  ${name}: NOT FOUND, named by ${lists.join(', ')}`)
377  }
378
379  lines.push(`Your own packs go in ~/${USER_PACKS}/<name>.json; a list uses one with "pack": "<name>".`)
380  return lines
381}
382
383async function seedOf($: EngineInterface): Promise<string> {
384  const stored = await $.store.get('seed')
385  if (typeof stored === 'string' && stored.length >= 16) return stored
386  const seed = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join('')
387  await $.store.set('seed', seed)
388  return seed
389}
390
391/** The filter for the topics file as it is now, read again only when it changed. */
392async function current($: EngineInterface): Promise<Loaded> {
393  await syncSidebar($)
394  if (loaded !== undefined && Date.now() - checkedAt < RECHECK_MS) return loaded
395
396  // The key covers the topics file and every pack file the last build read, so editing any of them is seen.
397  const path = await pathOf($)
398  const topicsKey = await statKey($, path)
399  const deps = loaded?.path === path ? loaded.deps : []
400  const key = [topicsKey, ...(await Promise.all(deps.map((d) => statKey($, d))))].join('\n')
401  checkedAt = Date.now()
402
403  if (loaded?.key === key) return loaded
404  if (loading?.key === key) return loading.promise
405
406  const previous = loaded
407  const promise = build($, path, topicsKey, previous)
408  loading = { key, promise }
409  try {
410    loaded = await promise
411  } finally {
412    if (loading?.key === key) loading = undefined
413  }
414
415  // A new problem is shown once where the person looks; the status line keeps it.
416  if (loaded.error !== undefined && loaded.error !== previous?.error) {
417    $.ui.toast(`topic-filter: ${firstSentence(loaded.error)} Run /topic-filter for details.`, { timeoutMs: 10_000 })
418  }
419
420  // Cached answers were computed from the old file.
421  if (previous !== undefined) {
422    $.ui.invalidate('prompt.context')
423    $.ui.invalidate('prompt.attachment')
424    $.ui.invalidate('tool.describe')
425  }
426  showStatus($)
427  return loaded
428}
429
430/** The filter to apply now: none while the person has paused it. */
431async function active($: EngineInterface): Promise<Filter | null> {
432  const f = (await current($)).filter
433  return paused ? null : f
434}
435
436/** Drops what was filtered from answers the engine may have kept, after a pause or a resume. */
437function refilter($: EngineInterface): void {
438  $.ui.invalidate('prompt.context')
439  $.ui.invalidate('prompt.attachment')
440  $.ui.invalidate('tool.describe')
441  $.ui.invalidate('ui.render')
442  showStatus($)
443}
444
445async function build(
446  $: EngineInterface,
447  path: string,
448  topicsKey: string,
449  previous: Loaded | undefined,
450): Promise<Loaded> {
451  const isMissing = topicsKey.endsWith('|missing')
452
453  let deps: string[] = previous?.deps ?? []
454  let latest: Config | null = previous?.latest ?? null
455  try {
456    // The settings' lists come after the file's, so `lists[i]` in a message
457    // still points into the file.
458    const own = isMissing ? null : parseConfig(await $.fs.read(path))
459    const extra = optionLists(pluginOptions)
460    if (own === null && extra.length === 0) {
461      return { key: topicsKey, path, deps: [], packsUsed: new Map(), config: null, latest: null, filter: null }
462    }
463    const config: Config = {
464      placeholder: 'codename',
465      informModel: true,
466      ...own,
467      lists: [...(own?.lists ?? []), ...extra],
468    }
469    latest = config
470    // Both places of every named pack, found or not: creating or editing
471    // either one is then noticed.
472    const home = await homeOf($)
473    deps = config.lists.flatMap((list) => (list.pack === undefined ? [] : packPaths(home, $.plugin.root, list.pack)))
474    const packs = await loadPacks($, config, home)
475    const key = [topicsKey, ...(await Promise.all(deps.map((d) => statKey($, d))))].join('\n')
476    const filter = new Filter(config, await seedOf($), packs.terms)
477    return { key, path, deps, packsUsed: packs.used, config, latest, filter }
478  } catch (error) {
479    const message = error instanceof ConfigError ? error.message : 'the file could not be read'
480    const key = [topicsKey, ...(await Promise.all(deps.map((d) => statKey($, d))))].join('\n')
481    return {
482      key,
483      path,
484      deps,
485      packsUsed: previous?.packsUsed ?? new Map(),
486      config: previous?.config ?? null,
487      latest,
488      filter: previous?.filter ?? null,
489      error: message,
490    }
491  }
492}
493
494/** A message's first sentence: a period followed by a space or the end, so `lists[0].pack` is not one. */
495const firstSentence = (text: string) => /^.*?[.?!](?=\s|$)/.exec(text)?.[0] ?? text
496
497/** The state in a sentence, for `/topic-filter`: UI only, never sent to the model, so it may name packs and problems. */
498function statusText(): string {
499  if (loaded === undefined || (loaded.filter === null && loaded.error === undefined)) {
500    return 'topic-filter: off, nothing chosen to hide. Switch on packs in /config.'
501  }
502  if (paused) return 'topic-filter: PAUSED, nothing is hidden. /topic-filter on resumes it.'
503  if (loaded.filter === null)
504    return `topic-filter: BLOCKING tool calls. ${firstSentence(loaded.error ?? '')} Run /topic-filter.`
505  const base = `topic-filter: on, ${count(loaded.filter.termCount, 'term')}, ${hiddenCount} hidden`
506  if (loaded.error !== undefined)
507    return `${base}. Using the last good settings: ${firstSentence(loaded.error)} Run /topic-filter.`
508  return base
509}
510
511/**
512 * The footer label, always shown. `isImportant` draws it in the theme's
513 * warning color: something needs the person, or nothing is being hidden.
514 * The details are in `/topic-filter`; the label only points there.
515 */
516function footerLabel(): { text: string; isImportant: boolean } {
517  if (loaded === undefined || (loaded.filter === null && loaded.error === undefined)) {
518    return { text: 'topic-filter: off, nothing chosen', isImportant: true }
519  }
520  if (paused) return { text: 'topic-filter: paused', isImportant: true }
521  if (loaded.filter === null) return { text: 'topic-filter: blocking tool calls, run /topic-filter', isImportant: true }
522  if (loaded.error !== undefined) {
523    return { text: `topic-filter: ${hiddenCount} hidden, settings problem, run /topic-filter`, isImportant: true }
524  }
525  return { text: `topic-filter: ${hiddenCount} hidden`, isImportant: false }
526}
527
528/** Redraws the footer label. The warning-styled status line is never used. */
529function showStatus($: EngineInterface): void {
530  $.ui.invalidate('ui.render')
531}
532
533/**
534 * Counts a pass for the status line, logs it under `source` as a `kind` of
535 * source (see HiddenLog.record for `mode`, `key` and `agent`), and redraws
536 * the sidebar.
537 */
538function counted(
539  $: EngineInterface,
540  tally: Tally,
541  source: string,
542  kind: SourceKind,
543  mode: LogMode = 'add',
544  key?: string,
545  agent?: string,
546): void {
547  hiddenLog.record(source, tally, mode, key, agent, kind)
548  // A pass that hid nothing changes the log only by removing an entry.
549  const n = tally.replaced + tally.dropped
550  hiddenCount += n
551  if (n > 0) showStatus($)
552  else if (tally.hits.size > 0 || mode !== 'add') $.ui.invalidate('ui.render')
553}
554
555/** The overview `/topic-filter` shows the person: every list and where its terms come from. */
556function describe(l: Loaded): string[] {
557  const lines = [statusText().replace(/^topic-filter: /, 'topic-filter is '), `Topics file: ${l.path}`]
558  if (l.latest !== null && l.latest.lists.every((list) => list.setting !== undefined)) {
559    lines.push('(No topics file: everything below comes from the plugin settings in /config.)')
560  }
561  if (l.error !== undefined) lines.push(`Problem: ${l.error}`)
562  if (l.latest !== null) {
563    lines.push('Lists:')
564    l.latest.lists.forEach((list, i) => {
565      const parts: string[] = [list.setting === undefined ? list.mode : `${list.mode}, from settings`]
566      const pack = l.packsUsed.get(i)
567      if (pack !== undefined) parts.push(`pack ${pack.name} (${pack.where}, ${count(pack.terms, 'term')})`)
568      else if (list.pack !== undefined) parts.push(`pack ${list.pack} (NOT FOUND)`)
569      if (list.terms.length > 0) parts.push(count(list.terms.length, 'own term'))
570      if (list.exclude.length > 0) parts.push(`${list.exclude.length} excluded`)
571      lines.push(`  "${list.name}": ${parts.join(', ')}`)
572    })
573    if ((l.filter?.skippedTerms ?? 0) > 0) lines.push(`${l.filter?.skippedTerms} terms were too short to use.`)
574  }
575  lines.push('Run /topic-filter packs to see every pack, /topic-filter log to see what was hidden and where,')
576  lines.push('and /topic-filter sidebar to watch it in a pane as it happens.')
577  return lines
578}
579
580export function register(on: On, options: PluginOptions) {
581  configured = typeof options.configPath === 'string' ? options.configPath.trim() : ''
582  pluginOptions = options
583  paused = startsPaused()
584
585  on('session.start', async ($, e, next) => {
586    try {
587      await $.command.register({
588        name: COMMAND,
589        description:
590          'Show what topic-filter is set to hide; `off` pauses it and `on` resumes it; `log` lists what was hidden and where; `sidebar` shows or hides it in a pane; `packs` lists topic packs; `reload` re-reads everything',
591        argumentHint: '[on|off|reload|packs|log|log clear|sidebar]',
592      })
593    } catch {
594      // The filter works without its command.
595    }
596
597    await current($)
598    showStatus($)
599    return next(e)
600  })
601
602  // A pause lasts one session: /clear starts the next as the setting says.
603  on('session.end', async ($, e, next) => {
604    if (paused !== startsPaused()) {
605      paused = startsPaused()
606      refilter($)
607    }
608    return next(e)
609  })
610
611  on('tool.call', async ($, e, next) => {
612    const l = await current($)
613    const f = l.filter
614    const input = e as unknown as Record<string, unknown>
615
616    // These two hold while paused too: the list itself stays out of reach, and
617    // a file the model holds a filtered copy of cannot be overwritten whole.
618    // A topics file that failed to load still holds the list.
619    if ((f !== null || l.error !== undefined) && mentionsPath(input, l.path)) {
620      return {
621        deny: 'topic-filter: that path holds the list of hidden topics, which this session may not read or change.',
622      }
623    }
624    // Edit changes only the text it names, and fails if that text spans
625    // something hidden, so it stays allowed.
626    if (e.tool === 'Write' && typeof e.file_path === 'string' && filteredFiles.has(pathKey(e.file_path))) {
627      return {
628        deny:
629          'topic-filter: this file holds content hidden from this session, so overwriting it whole would delete ' +
630          'that content. Use Edit to change specific parts instead.',
631      }
632    }
633
634    if (f === null && l.error !== undefined && !paused) {
635      // The model is told there is a problem, never what it is: the
636      // message names packs, which would say what is being hidden.
637      return {
638        deny:
639          "topic-filter: tool calls are paused because the user's topic-filter settings have a problem. " +
640          'Ask the user to run /topic-filter to see it.',
641      }
642    }
643
644    let call = e
645    if (f !== null && !MODEL_FACING_TOOLS.has(e.tool)) {
646      const used = paused ? [] : f.guardedIn(input)
647      if (used.length > 0) {
648        const names = used.join(', ')
649        return {
650          deny:
651            `topic-filter: ${names} ${used.length === 1 ? 'is a placeholder for a hidden item' : 'are placeholders for hidden items'}. ` +
652            'Hidden items cannot be used in commands, searches or file edits; leave them out or work around them.',
653        }
654      }
655      const restored = f.restore(input)
656      if (restored.changed) call = restored.value as typeof e
657    }
658
659    const result = await next(call)
660    if (paused || f === null) {
661      // Read whole while paused, the file can be written back without loss.
662      if (paused && e.tool === 'Read' && typeof e.file_path === 'string' && readWhole(input, result)) {
663        filteredFiles.delete(pathKey(e.file_path))
664      }
665      return result
666    }
667    const seen = newTally()
668    const filtered = filterResult(f, result, seen)
669    counted($, seen, toolSource(e.tool, input), kindOfTool(e.tool), 'add', undefined, e.agentId)
670    if (e.tool === 'Read' && typeof e.file_path === 'string' && hidesContent(f, seen)) {
671      filteredFiles.add(pathKey(e.file_path))
672    }
673    return filtered
674  }).catch(($, e, next) => ({
675    deny: next.called
676      ? 'topic-filter: the tool ran, but its output is withheld because topic-filter failed while checking it.'
677      : 'topic-filter: this call was refused because topic-filter failed while checking it.',
678  }))
679
680  on('prompt.submit', async ($, e, next) => {
681    const f = await active($)
682    if (f === null) return next(e)
683
684    const tally = newTally()
685    const text = f.text(e.text, tally, false)
686    const context = e.context?.map((c) => f.text(c, tally).value).filter((c) => c.length > 0)
687    if (tally.replaced === 0 && tally.dropped === 0) return next(e)
688
689    counted($, tally, 'Your prompt', 'prompts')
690    const note = f.informModel ? noteFor(tally, f.restorable) : undefined
691    return next({ ...e, text: text.value, context: note === undefined ? context : [...(context ?? []), note] })
692  }).catch(($, e, next) =>
693    next.called ? undefined : { drop: 'topic-filter failed while checking this prompt, so it was not sent.' },
694  )
695
696  on('prompt.context', async ($, e, next) => {
697    const f = await active($)
698    if (f === null) return next(e)
699
700    const r = await next(f.informModel ? { ...e, blocks: [...e.blocks, { name: 'topicFilter', text: EXPLAINER }] } : e)
701    // The claudeMd block is the instruction files' text: with the files at
702    // hand, it is counted and logged by file, not a second time as a block.
703    const byFile = r.instructionFiles !== undefined
704    const blocks = r.blocks.map((b) => {
705      const tally = newTally()
706      const text = f.text(b.text, tally).value
707      if (!(byFile && b.name === 'claudeMd')) counted($, tally, `Context block ${b.name}`, 'context', 'standing')
708      return { ...b, text }
709    })
710    const instructionFiles = r.instructionFiles?.map((file) => {
711      const tally = newTally()
712      const content = f.text(file.content, tally).value
713      counted($, tally, file.path, 'context', 'standing')
714      return { ...file, content }
715    })
716    return instructionFiles === undefined ? { blocks } : { blocks, instructionFiles }
717  }).catch(() => ({ blocks: [] }))
718
719  on('prompt.attachment', async ($, e, next) => {
720    const r = await next(e)
721    if (!filtersAttachment(e)) return r
722    const f = await active($)
723    if (f === null || r.text === null) return r
724    const tally = newTally()
725    const text = f.text(r.text, tally)
726    // An attachment has no name of its own; its text tells one from another,
727    // so one asked again (after a reload) replaces its entry.
728    counted(
729      $,
730      tally,
731      `Attachment (${e.type})`,
732      'context',
733      'replace',
734      `attachment:${e.type}:${fnv1a(r.text)}`,
735      e.agentId,
736    )
737    if (!text.changed) return r
738    return { text: text.vanished ? null : text.value }
739  }).catch(($, e) => (filtersAttachment(e) ? { text: null } : undefined))
740
741  on('skill.prompt', async ($, e, next) => {
742    const r = await next(e)
743    const f = await active($)
744    if (f === null) return r
745    const tally = newTally()
746    const text = f.text(r.text, tally)
747    counted($, tally, `Skill ${e.skill}`, 'skills')
748    return text.changed ? { text: text.value } : r
749  }).catch(() => ({ text: 'topic-filter failed while checking this skill, so its text is withheld.' }))
750
751  // Only MCP tools' descriptions: a built-in tool's description carries
752  // Claude Code's own instructions for it, which are never changed.
753  on('tool.describe', async ($, e, next) => {
754    const r = await next(e)
755    if (!isMcpTool(e)) return r
756    const f = await active($)
757    if (f === null) return r
758    const text = f.text(r.description, newTally(), false)
759    return text.changed ? { ...r, description: text.value } : r
760  }).catch(() => undefined)
761
762  on('session.receive', async ($, e, next) => {
763    const f = await active($)
764    if (f === null) return next(e)
765    const tally = newTally()
766    const text = f.text(e.text, tally, false)
767    counted($, tally, 'Message delivered to the session', 'prompts', 'add', undefined, e.agentId)
768    return next(text.changed ? { ...e, text: text.value } : e)
769  }).catch(($, e, next) =>
770    next.called ? undefined : { consumed: 'topic-filter failed while checking this delivery.' },
771  )
772
773  on('command.run', async ($, e, next) => {
774    if (e.command === COMMAND) {
775      const arg = e.args.trim()
776      if (PAUSE_ARGS.has(arg) || RESUME_ARGS.has(arg)) {
777        const { lines, context } = await setPaused($, PAUSE_ARGS.has(arg), e.origin?.kind)
778        for (const line of [...lines, '(Shown to you only; Claude does not see this.)']) $.ui.log(line)
779        return context === undefined ? {} : { context: [context] }
780      }
781      if (arg === 'reload') {
782        loaded = undefined
783        await current($)
784        $.ui.invalidate('prompt.context')
785        $.ui.invalidate('prompt.attachment')
786        $.ui.invalidate('tool.describe')
787      }
788      // Shown to the person only: `ui.log` lines never reach the model, and
789      // these name packs and lists, which would say what is being hidden.
790      if (arg === 'log clear') {
791        hiddenLog.clear()
792        $.ui.invalidate('ui.render')
793      }
794      const l = await current($)
795      const labels = arg === 'log' ? await agentLabels($) : new Map<string, string>()
796      const lines =
797        arg === 'packs'
798          ? await packListing($, l)
799          : arg === 'log'
800            ? hiddenLog.lines((agent) => labels.get(agent) ?? agent)
801            : arg === 'log clear'
802              ? [
803                  'The log is cleared, except what Claude reads with every request. The status line count keeps its total.',
804                ]
805              : arg === 'sidebar'
806                ? await toggleSidebar($)
807                : describe(l)
808      for (const line of [...lines, '(Shown to you only; Claude does not see this.)']) $.ui.log(line)
809      return {}
810    }
811
812    const r = await next(e)
813    const f = await active($)
814    if (f === null || r.text === undefined) return r
815    const tally = newTally()
816    const text = f.text(r.text, tally)
817    if (!text.changed) return r
818    counted($, tally, `/${e.command} output`, 'commands')
819    const { ref: _ref, ...rest } = r
820    return { ...rest, text: text.value }
821  }).catch(() => ({ text: 'topic-filter failed while checking this output, so it is withheld.' }))
822
823  // The footer's dim mode labels, with topic-filter's last. A label is a plain
824  // string, so an important one draws the row itself to color its own part.
825  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
826    const label = footerLabel()
827    if (!label.isImportant) return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label.text] } })
828    const { Text } = await $.ui.resolve(e)
829    const others = e.props.modes.join(' & ')
830    return Text({
831      children: [
832        ...(others === '' ? [] : [Text({ dimColor: true, children: `${others} & ` })]),
833        Text({ color: 'warning', children: label.text }),
834      ],
835    })
836  })
837
838  // The sidebar: the whole session, or the subagent whose transcript is in view.
839  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
840    if (e.requestId !== SIDEBAR_ID) return next(e)
841    const { Box, Text, Button } = await $.ui.resolve(e)
842    const agentId = e.props.view.agentId
843    const agent = agentId === undefined ? undefined : await sidebarLabel($, agentId)
844    sidebarAgent = agentId
845    return sidebarView(
846      { Box, Text, Button },
847      {
848        summary: hiddenLog.summary(agentId),
849        ...(agent === undefined ? {} : { agent }),
850        countsOnly: pluginOptions.sidebarCountsOnly === true,
851        isPaused: paused,
852        view: sidebarState,
853        columns: e.props.bodyColumns,
854        rows: e.props.scroll.bodyRows,
855        onPress: pressSidebar,
856      },
857    )
858  })
859
860  // A press ran its button's handler, which changed the view: draw it again.
861  on('ui.press', async ($, e, next) => {
862    const r = await next(e)
863    if (e.requestId === SIDEBAR_ID) $.ui.invalidate('ui.render')
864    return r
865  })
866}
867
868/**
869 * What the person picked in the sidebar: memory only, like the log, so a
870 * reload opens it fresh. One view for every scope it is drawn in.
871 */
872let sidebarState: SidebarView = { tab: 'lists', open: new Set() }
873
874/** The subagent the sidebar was last drawn for, which a row press refers to. */
875let sidebarAgent: string | undefined
876
877/** A sidebar button's press: `tab:<tab>`, `depth:<0-2>` or `row:<id>`. */
878function pressSidebar(key: string): void {
879  const [kind, ...rest] = key.split(':')
880  const arg = rest.join(':')
881  if (kind === 'tab' && (arg === 'lists' || arg === 'feed')) {
882    sidebarState = { ...sidebarState, tab: arg }
883  } else if (kind === 'depth' && (arg === '0' || arg === '1' || arg === '2')) {
884    sidebarState = { ...sidebarState, depth: Number(arg) as Depth, open: new Set() }
885  } else if (kind === 'row') {
886    // From a depth to rows picked one by one: start from what shows now.
887    const open = openRows(sidebarState, hiddenLog.summary(sidebarAgent))
888    if (open.has(arg)) open.delete(arg)
889    else open.add(arg)
890    sidebarState = { ...sidebarState, depth: null, open }
891  }
892}
893
894const PAUSE_ARGS = new Set(['off', 'pause', 'stop'])
895const RESUME_ARGS = new Set(['on', 'resume', 'start'])
896
897/**
898 * Pauses or resumes filtering. Answers the lines the person sees, and a note
899 * for the model when the state changed, so it knows whether placeholders
900 * are still refused.
901 */
902async function setPaused(
903  $: EngineInterface,
904  pause: boolean,
905  origin: string | undefined,
906): Promise<{ lines: string[]; context?: string }> {
907  if (pause && !MAY_PAUSE.has(origin ?? '')) {
908    return { lines: ['Only you can pause topic-filter, by typing /topic-filter off. It stays on.'] }
909  }
910  const l = await current($)
911  const was = paused
912  paused = pause
913  if (was !== pause) refilter($)
914
915  if (pause) {
916    return {
917      lines: was
918        ? ['topic-filter is already paused. /topic-filter on resumes it.']
919        : [
920            'topic-filter paused: nothing is hidden until /topic-filter on.',
921            'What Claude already read stays as it was. A restart, /clear or a reload turns it back on.',
922          ],
923      ...(was
924        ? {}
925        : {
926            context:
927              'The user paused topic-filter: tool output is no longer filtered, and placeholders are no longer refused.',
928          }),
929    }
930  }
931
932  const status =
933    l.filter === null
934      ? statusText()
935      : `Filter on: ${count(l.config?.lists.length ?? 0, 'list')}, ${count(l.filter.termCount, 'term')}.`
936  return {
937    lines: [was ? status : `${status} (It was not paused.)`],
938    ...(was
939      ? {
940          context:
941            'The user turned topic-filter back on: hidden items are filtered again, and placeholders are refused in tool calls.',
942        }
943      : {}),
944  }
945}
946
947/** Opens the sidebar, or closes it when it is open; says which, for the person. */
948async function toggleSidebar($: EngineInterface): Promise<string[]> {
949  const isOpen = (await $.ui.panes()).some((pane) => pane.id === SIDEBAR_ID)
950  if (isOpen) {
951    await $.ui.close({ id: SIDEBAR_ID })
952    return ['Sidebar closed. /topic-filter sidebar opens it again.']
953  }
954  const opened = await $.ui.open({ id: SIDEBAR_ID, title: 'topic-filter' })
955  if (!opened.isPlaced) return [`Sidebar opened, but it waits undrawn: ${opened.reason}`]
956  return [
957    'Sidebar open. With other panes open it is one of their tabs: click a tab to switch;',
958    'ctrl+x x or its close mark closes it. The "Sidebar" switch in /config opens it at every start.',
959  ]
960}
961
962/**
963 * Filters a tool's result for the model. `seen` counts what was hidden from
964 * the text the model reads (`text`, which core maps from the record), not
965 * from record fields it never sees (a Write's `originalFile`), so the note
966 * and the status line describe the model's view.
967 */
968function filterResult(f: Filter, r: ToolCallResult, seen: Tally): ToolCallResult {
969  if (r.deny !== undefined) {
970    const text = f.text(r.deny, seen, false)
971    return text.changed ? { deny: text.value } : r
972  }
973
974  // An errored call reaches the model as its error text; a deny carries a
975  // rewritten one the same way.
976  if (r.isError === true) {
977    const text = f.text(r.text ?? '', seen, false)
978    return text.changed ? { deny: text.value } : r
979  }
980
981  const record = f.value(r.result, newTally())
982  if (typeof r.text === 'string') f.text(r.text, seen)
983  const context = r.context?.map((c) => f.text(c, seen))
984  const contextChanged = context?.some((c) => c.changed) ?? false
985
986  if (!record.changed && !contextChanged) {
987    // A term in `text` that the record does not hold came from the mapper,
988    // so filtering the record cannot remove it: send the filtered text as an
989    // error instead.
990    if (typeof r.text === 'string' && f.hasTerm(r.text)) return { deny: f.text(r.text, newTally(), false).value }
991    return r
992  }
993
994  const kept = (context ?? []).map((c) => c.value).filter((c) => c.length > 0)
995  const note = f.informModel ? noteFor(seen, f.restorable) : undefined
996  const all = note === undefined ? kept : [...kept, note]
997  // Without `ref`, core maps the filtered record for the model afresh.
998  return all.length > 0 ? { result: record.value, context: all } : { result: record.value }
999}
1000
1001/**
1002 * Whether a Read answered the whole file: no range asked, and every line
1003 * returned (a long file is cut at the engine's line cap).
1004 */
1005function readWhole(input: Record<string, unknown>, r: ToolCallResult): boolean {
1006  if (r.deny !== undefined || r.isError === true) return false
1007  if (input.offset !== undefined || input.limit !== undefined || input.pages !== undefined) return false
1008  const file = (r.result as { file?: { numLines?: unknown; totalLines?: unknown } } | undefined)?.file
1009  return typeof file?.numLines === 'number' && file.numLines === file.totalLines
1010}
1011
1012/** Whether a tool call names the topics file (best effort: a name match, not a sandbox). */
1013/**
1014 * Fields that are text being written into some file, not a file to act on: a
1015 * README or script that merely mentions the topics file's path is fine. The
1016 * target (`file_path`), commands, patterns and paths are still checked.
1017 */
1018const WRITTEN_TEXT = new Set(['content', 'old_string', 'new_string', 'new_source'])
1019
1020function mentionsPath(input: Record<string, unknown>, path: string): boolean {
1021  const norm = (s: string) => s.replace(/\\/g, '/').toLowerCase()
1022  const full = norm(path)
1023  const tail = full.split('/').slice(-2).join('/')
1024  let found = false
1025  const checked = Object.fromEntries(Object.entries(input).filter(([key]) => !WRITTEN_TEXT.has(key)))
1026  forEachString(checked, (s) => {
1027    const n = norm(s)
1028    if (n.includes(full) || n.includes(tail)) found = true
1029  })
1030  return found
1031}
1032
hooks/config.ts 214 lines
1// Reads topics.json. Errors name a position (`lists[1].terms[3]`), never a
2// term, because an error can reach the transcript and the terms are exactly
3// what must not.
4
5import type { Mode } from './matcher.ts'
6import type { PlaceholderStyle } from './placeholders.ts'
7
8export type ListConfig = {
9  name: string
10  mode: Mode
11  /** `word`: a term matches only as whole words. `substring`: anywhere. */
12  match: 'word' | 'substring'
13  /** Put the real term back when the model uses this list's placeholder in a tool call. */
14  restore: boolean
15  terms: string[]
16  /** A topic pack whose terms join `terms`: the user's own file first, else the built-in one. */
17  pack?: string
18  /** Terms left out of this list, whatever brought them in (the pack or `terms`). */
19  exclude: string[]
20  /** The plugin option this list came from; absent for the topics file's own lists. */
21  setting?: string
22}
23
24export type Config = {
25  placeholder: PlaceholderStyle
26  /** Tell the model that placeholders exist and how to treat them. */
27  informModel: boolean
28  lists: ListConfig[]
29}
30
31export class ConfigError extends Error {}
32
33const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
34
35function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T, where: string): T {
36  if (value === undefined) return fallback
37  if (typeof value === 'string' && (allowed as readonly string[]).includes(value)) return value as T
38  throw new ConfigError(`${where} must be one of ${allowed.join(', ')}`)
39}
40
41function flag(value: unknown, fallback: boolean, where: string): boolean {
42  if (value === undefined) return fallback
43  if (typeof value === 'boolean') return value
44  throw new ConfigError(`${where} must be true or false`)
45}
46
47/** Parses and checks the topics file's text. */
48export function parseConfig(text: string): Config {
49  let raw: unknown
50  try {
51    raw = JSON.parse(text)
52  } catch {
53    throw new ConfigError('topics.json is not valid JSON')
54  }
55  if (!isRecord(raw)) throw new ConfigError('topics.json must hold an object')
56
57  const lists = raw.lists
58  if (!Array.isArray(lists)) throw new ConfigError('lists must be an array')
59
60  return {
61    placeholder: oneOf(raw.placeholder, ['codename', 'tag'] as const, 'codename', 'placeholder'),
62    informModel: flag(raw.informModel, true, 'informModel'),
63    lists: lists.map((list, i) => parseList(list, i)),
64  }
65}
66
67function parseList(list: unknown, i: number): ListConfig {
68  const at = `lists[${i}]`
69  if (!isRecord(list)) throw new ConfigError(`${at} must be an object`)
70
71  const pack = list.pack
72  if (pack !== undefined && (typeof pack !== 'string' || !SLUG.test(pack))) {
73    throw new ConfigError(`${at}.pack must be a pack name (lowercase letters, digits, hyphens)`)
74  }
75
76  const restore = flag(list.restore, false, `${at}.restore`)
77  // Restore writes real terms into tool input; it is for the person's own
78  // names, never for a topic pack.
79  if (restore && pack !== undefined) throw new ConfigError(`${at}.restore is not allowed on a list that uses a pack`)
80
81  return {
82    name: typeof list.name === 'string' ? list.name : `list ${i + 1}`,
83    mode: oneOf(list.mode, ['replace', 'drop-line'] as const, 'replace', `${at}.mode`),
84    match: oneOf(list.match, ['word', 'substring'] as const, 'word', `${at}.match`),
85    restore,
86    terms: strings(list.terms, `${at}.terms`),
87    pack,
88    exclude: strings(list.exclude, `${at}.exclude`),
89  }
90}
91
92/** A pack name: also safe as a file name, never a path. */
93export const SLUG = /^[a-z0-9][a-z0-9-]*$/
94
95/** The built-in packs' switches in the plugin's settings, by option key. */
96export const PACK_OPTIONS: Readonly<Record<string, string>> = {
97  hideAnthropology: 'anthropology',
98  hideBiology: 'biology',
99  hideChemistry: 'chemistry',
100  hideGenetics: 'genetics',
101}
102
103/** A comma-separated option (or a list option) as its items. */
104function items(value: unknown): string[] {
105  const parts = typeof value === 'string' ? value.split(',') : Array.isArray(value) ? value : []
106  return parts
107    .filter((s): s is string => typeof s === 'string')
108    .map((s) => s.trim())
109    .filter((s) => s !== '')
110}
111
112function slugs(value: unknown, setting: string, what: string): string[] {
113  const names = items(value).map((s) => s.toLowerCase())
114  const bad = names.findIndex((name) => !SLUG.test(name))
115  if (bad >= 0)
116    throw new ConfigError(
117      `The ${setting} setting's item ${bad + 1} is not a ${what} (lowercase letters, digits, hyphens).`,
118    )
119  return [...new Set(names)]
120}
121
122/**
123 * The lists the plugin's own settings (`/plugin configure`, `/config`) add to
124 * the topics file's: switched-on packs and extra words. The topics file is then only needed for more than
125 * this.
126 */
127export function optionLists(options: Readonly<Record<string, unknown>>): ListConfig[] {
128  const list = (over: Partial<ListConfig> & { name: string; setting: string }): ListConfig => ({
129    mode: 'replace',
130    match: 'word',
131    restore: false,
132    terms: [],
133    exclude: [],
134    ...over,
135  })
136  const lists: ListConfig[] = []
137
138  const packs = new Map<string, string>()
139  for (const [key, pack] of Object.entries(PACK_OPTIONS)) {
140    if (options[key] === true) packs.set(pack, `Hide ${pack}`)
141  }
142  for (const pack of slugs(options.otherPacks, 'Other packs', 'pack name')) {
143    if (!packs.has(pack)) packs.set(pack, 'Other packs')
144  }
145  for (const [pack, setting] of packs) lists.push(list({ name: `pack ${pack}`, setting, pack }))
146
147  const words = items(options.extraWords)
148  if (words.length > 0) lists.push(list({ name: 'extra words', setting: 'Extra words to hide', terms: words }))
149
150  return lists
151}
152
153function strings(value: unknown, where: string): string[] {
154  if (value === undefined) return []
155  if (!Array.isArray(value)) throw new ConfigError(`${where} must be an array`)
156  value.forEach((item, j) => {
157    if (typeof item !== 'string') throw new ConfigError(`${where}[${j}] must be a string`)
158  })
159  return value as string[]
160}
161
162/** The candidate a mistyped name most likely meant, or undefined when none is close. */
163export function closestName(name: string, candidates: readonly string[]): string | undefined {
164  let best: string | undefined
165  let bestDistance = Infinity
166  for (const candidate of candidates) {
167    if (candidate.startsWith(name) || name.startsWith(candidate)) return candidate
168    const d = editDistance(name, candidate)
169    if (d < bestDistance) {
170      best = candidate
171      bestDistance = d
172    }
173  }
174  return bestDistance <= Math.max(2, Math.floor(name.length / 3)) ? best : undefined
175}
176
177function editDistance(a: string, b: string): number {
178  let row = Array.from({ length: b.length + 1 }, (_, j) => j)
179  for (let i = 1; i <= a.length; i += 1) {
180    const cur = [i]
181    for (let j = 1; j <= b.length; j += 1) {
182      cur[j] = Math.min(row[j]! + 1, cur[j - 1]! + 1, row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1))
183    }
184    row = cur
185  }
186  return row[b.length]!
187}
188
189/** A topic pack as its file holds it; only `terms` hides anything today. */
190export type Pack = {
191  name: string
192  description: string
193  terms: string[]
194  hints: string[]
195}
196
197/** Parses a pack file. Errors name the pack and a position, never a term. */
198export function parsePack(text: string, name: string): Pack {
199  let raw: unknown
200  try {
201    raw = JSON.parse(text)
202  } catch {
203    throw new ConfigError(`pack "${name}" is not valid JSON`)
204  }
205  if (!isRecord(raw)) throw new ConfigError(`pack "${name}" must hold an object`)
206
207  return {
208    name,
209    description: typeof raw.description === 'string' ? raw.description : '',
210    terms: strings(raw.terms, `pack "${name}" terms`),
211    hints: strings(raw.hints, `pack "${name}" hints`),
212  }
213}
214
hooks/log.ts 304 lines
1// What was hidden this session and where it came from, for `/topic-filter
2// log`. It names the real terms, so it lives in memory only and is shown
3// through `ui.log`, which never reaches the model: a file of its own would be
4// a second copy of the hidden list, somewhere the model might read it. The
5// engine's debug log does get every `ui.log` line, as the README says.
6
7import type { Hit, Tally } from './redact.ts'
8
9/** Past this many passing sources the oldest are forgotten. */
10const MAX_SOURCES = 200
11
12/** Past this many hits the feed forgets the oldest. */
13const MAX_FEED = 100
14
15/** Past this many terms a source's entry says how many more there were. */
16const MAX_TERMS_SHOWN = 20
17
18/** Past this many characters a source's label is cut. */
19const MAX_LABEL = 100
20
21/** "1 word", "1,204 words": a count as the log and the sidebar show it. */
22export const plural = (n: number, noun: string) => `${n.toLocaleString('en-US')} ${noun}${n === 1 ? '' : 's'}`
23
24/** A source's label on one line, cut to a readable length. */
25export function label(text: string): string {
26  const flat = text.replace(/\s+/g, ' ').trim()
27  return flat.length <= MAX_LABEL ? flat : `${flat.slice(0, MAX_LABEL - 3)}...`
28}
29
30/**
31 * How a pass joins the log:
32 * - `add`: something read once (a tool's output, a prompt); passes add up.
33 * - `replace`: the pass covers the source's whole text and may run again for
34 *   the same text (an attachment asked again after a reload); it replaces the
35 *   last one, and a pass that hid nothing removes the entry.
36 * - `standing`: like `replace`, for text in every request of the session (a
37 *   CLAUDE.md and the other context blocks). Kept apart, never forgotten to the
38 *   cap, and kept by `clear`, since the engine may not filter it again.
39 */
40export type LogMode = 'add' | 'replace' | 'standing'
41
42/** What kind of source a pass read, for the sidebar's bars. */
43export type SourceKind = 'files' | 'prompts' | 'web' | 'commands' | 'searches' | 'skills' | 'context' | 'tools'
44
45/** Each kind as the sidebar names it. */
46export const KIND_LABELS: Record<SourceKind, string> = {
47  files: 'Files',
48  prompts: 'Prompts',
49  web: 'Web',
50  commands: 'Commands',
51  searches: 'Searches',
52  skills: 'Skills',
53  context: 'Context',
54  tools: 'Other tools',
55}
56
57/**
58 * One source's hits; `agent` is the subagent whose loop read it, absent for
59 * the main conversation, and `at` when it last hid something new.
60 */
61type Entry = { label: string; agent?: string; kind: SourceKind; at: number; hits: Map<string, Hit> }
62
63/** A source a term was hidden in, and how many times. */
64export type TermSource = { label: string; n: number }
65
66/** A term's share of a summary, with the sources it was hidden in, most first. */
67export type TermSummary = Hit & { sources: TermSource[] }
68
69/** One list's share of a summary: its hits merged across sources, most hidden first. */
70export type ListSummary = { list: string; replaced: number; dropped: number; hits: TermSummary[] }
71
72/** One pass that hid something, as the feed shows it. */
73export type FeedItem = {
74  at: number
75  label: string
76  agent?: string
77  replaced: number
78  dropped: number
79  hits: { list: string; term: string; n: number }[]
80}
81
82/** What the sidebar draws: totals, each list's share, and where the last hit came from. */
83export type Summary = {
84  replaced: number
85  dropped: number
86  /** Distinct terms hidden. */
87  terms: number
88  lists: ListSummary[]
89  /** The label of the most recent source with a hit, if any. */
90  latest?: string
91  /** The subagents with hits, ordered by their least recently hidden source. */
92  agents: string[]
93  /** How much each kind of source hid, most first; kinds that hid nothing are left out. */
94  kinds: { kind: SourceKind; n: number }[]
95  /** How many sources hid something. */
96  sources: number
97  /** When something was last hidden, if ever. */
98  lastAt?: number
99  /** The passes that hid something, newest first. */
100  feed: FeedItem[]
101}
102
103export class HiddenLog {
104  /** Passing sources by slot, least recently hidden first. */
105  private readonly passing = new Map<string, Entry>()
106  /** Standing sources by slot. */
107  private readonly standing = new Map<string, Entry>()
108  /** Passing sources forgotten to stay under the cap. */
109  private forgotten = 0
110  /** Every pass that hid something new, oldest first. */
111  private readonly feed: FeedItem[] = []
112
113  /** `now` tells the time; tests pass their own. */
114  constructor(private readonly now: () => number = () => Date.now()) {}
115
116  /**
117   * Adds one pass's hits under `source`, shown cut to one line; `slot` tells
118   * sources apart when their labels could match (a long path cut short), and
119   * `agent` names the subagent whose loop read it.
120   */
121  record(
122    source: string,
123    tally: Tally,
124    mode: LogMode = 'add',
125    slot: string = source,
126    agent?: string,
127    kind: SourceKind = 'tools',
128  ): void {
129    const entries = mode === 'standing' ? this.standing : this.passing
130    slot = agent === undefined ? slot : `${agent}\u0000${slot}`
131    const previous = entries.get(slot)
132    if (tally.hits.size === 0) {
133      if (mode !== 'add' && previous !== undefined) entries.delete(slot)
134      return
135    }
136
137    const hits = new Map<string, Hit>(mode !== 'add' || previous === undefined ? [] : previous.hits)
138    for (const [term, hit] of tally.hits) {
139      const had = hits.get(term)
140      // The newest placeholder and list name stand: settings may have changed since.
141      hits.set(
142        term,
143        had === undefined
144          ? { ...hit }
145          : { ...hit, replaced: had.replaced + hit.replaced, dropped: had.dropped + hit.dropped },
146      )
147    }
148    // A pass that only repeats what a standing or replaced source already
149    // hid (the same CLAUDE.md, every request) is not news: it keeps its
150    // time and stays out of the feed.
151    const isNew = mode === 'add' || previous === undefined
152    const at = isNew ? this.now() : previous.at
153    if (isNew) this.remember(label(source), tally, at, agent)
154
155    // Newest last: a source hidden again moves to the end.
156    entries.delete(slot)
157    const entry: Entry = { label: label(source), kind, at, hits }
158    entries.set(slot, agent === undefined ? entry : { ...entry, agent })
159
160    while (this.passing.size > MAX_SOURCES) {
161      this.passing.delete(this.passing.keys().next().value!)
162      this.forgotten += 1
163    }
164  }
165
166  private remember(source: string, tally: Tally, at: number, agent?: string): void {
167    const hits = [...tally.hits.values()].map((hit) => ({
168      list: hit.list,
169      term: hit.term,
170      n: hit.replaced + hit.dropped,
171    }))
172    hits.sort((a, b) => b.n - a.n)
173    const item: FeedItem = { at, label: source, replaced: tally.replaced, dropped: tally.dropped, hits }
174    this.feed.push(agent === undefined ? item : { ...item, agent })
175    if (this.feed.length > MAX_FEED) this.feed.shift()
176  }
177
178  /** Empties what passed and the feed; what stands in every request stays, as it is still hidden there. */
179  clear(): void {
180    this.passing.clear()
181    this.forgotten = 0
182    this.feed.length = 0
183  }
184
185  /** The log as the person reads it; `agentName` labels a subagent by its id. */
186  lines(agentName: (agent: string) => string = (agent) => agent): string[] {
187    if (this.passing.size === 0 && this.standing.size === 0) return ['Nothing has been hidden this session yet.']
188
189    const lines: string[] = []
190    if (this.standing.size > 0) {
191      lines.push('Hidden in what Claude reads with every request (CLAUDE.md, context blocks):')
192      for (const entry of this.standing.values()) lines.push(...entryLines(entry))
193    }
194    if (this.forgotten > 0) lines.push(`(${plural(this.forgotten, 'older source')} not shown)`)
195
196    // The main conversation first, then each subagent, ordered by its least recently hidden source.
197    const byAgent = new Map<string | undefined, Entry[]>()
198    for (const entry of this.passing.values()) byAgent.set(entry.agent, [...(byAgent.get(entry.agent) ?? []), entry])
199    const main = byAgent.get(undefined)
200    if (main !== undefined) {
201      lines.push('Hidden as it came in (most recent last):')
202      for (const entry of main) lines.push(...entryLines(entry))
203    }
204    for (const [agent, entries] of byAgent) {
205      if (agent === undefined) continue
206      lines.push(`Hidden in subagent ${agentName(agent)} (most recent last):`)
207      for (const entry of entries) lines.push(...entryLines(entry))
208    }
209    return lines
210  }
211
212  /**
213   * Totals and each list's share, for the sidebar: the whole session, or one
214   * subagent's own reads when `agent` is given.
215   */
216  summary(agent?: string): Summary {
217    const inScope = (entry: Entry) => agent === undefined || entry.agent === agent
218    const entries = [...(agent === undefined ? this.standing.values() : []), ...this.passing.values()].filter(inScope)
219
220    const weight = (x: { replaced: number; dropped: number }) => x.replaced + x.dropped
221    const byTerm = new Map<string, TermSummary>()
222    const byTermSource = new Map<string, Map<string, number>>()
223    const byKind = new Map<SourceKind, number>()
224    for (const entry of entries) {
225      for (const [term, hit] of entry.hits) {
226        const had = byTerm.get(term)
227        byTerm.set(
228          term,
229          had === undefined
230            ? { ...hit, sources: [] }
231            : { ...hit, sources: [], replaced: had.replaced + hit.replaced, dropped: had.dropped + hit.dropped },
232        )
233        const sources = byTermSource.get(term) ?? new Map<string, number>()
234        sources.set(entry.label, (sources.get(entry.label) ?? 0) + weight(hit))
235        byTermSource.set(term, sources)
236        byKind.set(entry.kind, (byKind.get(entry.kind) ?? 0) + weight(hit))
237      }
238    }
239    for (const [term, hit] of byTerm) {
240      hit.sources = [...(byTermSource.get(term) ?? [])].map(([label, n]) => ({ label, n })).sort((a, b) => b.n - a.n)
241    }
242
243    const byList = new Map<string, ListSummary>()
244    for (const hit of byTerm.values()) {
245      const list = byList.get(hit.list) ?? { list: hit.list, replaced: 0, dropped: 0, hits: [] }
246      list.replaced += hit.replaced
247      list.dropped += hit.dropped
248      list.hits.push(hit)
249      byList.set(hit.list, list)
250    }
251    const lists = [...byList.values()].sort((a, b) => weight(b) - weight(a))
252    for (const list of lists) list.hits.sort((a, b) => weight(b) - weight(a))
253
254    const passing = [...this.passing.values()].filter(inScope)
255    const agents = [
256      ...new Set([...this.passing.values()].flatMap((entry) => (entry.agent === undefined ? [] : [entry.agent]))),
257    ]
258    const lastAt = entries.reduce<number | undefined>(
259      (at, entry) => (at === undefined || entry.at > at ? entry.at : at),
260      undefined,
261    )
262    const feed = this.feed.filter((item) => agent === undefined || item.agent === agent).reverse()
263    return {
264      replaced: lists.reduce((n, list) => n + list.replaced, 0),
265      dropped: lists.reduce((n, list) => n + list.dropped, 0),
266      terms: byTerm.size,
267      lists,
268      ...(passing.length > 0 ? { latest: passing.at(-1)!.label } : {}),
269      agents,
270      kinds: [...byKind].map(([kind, n]) => ({ kind, n })).sort((a, b) => b.n - a.n),
271      sources: entries.length,
272      ...(lastAt === undefined ? {} : { lastAt }),
273      feed,
274    }
275  }
276}
277
278/** One source: its label, each replaced term, then the lines each list dropped (counted, never shown). */
279function entryLines({ label, hits }: Entry): string[] {
280  const lines = [`  ${label}`]
281  const all = [...hits.values()]
282
283  const replaced = all.filter((hit) => hit.replaced > 0).sort((a, b) => b.replaced - a.replaced)
284  for (const hit of replaced.slice(0, MAX_TERMS_SHOWN)) {
285    lines.push(`      ${hit.term} -> ${hit.placeholder} (x${hit.replaced})`)
286  }
287  if (replaced.length > MAX_TERMS_SHOWN)
288    lines.push(`      and ${plural(replaced.length - MAX_TERMS_SHOWN, 'more term')}`)
289
290  const byList = new Map<string, Hit[]>()
291  for (const hit of all) if (hit.dropped > 0) byList.set(hit.list, [...(byList.get(hit.list) ?? []), hit])
292  for (const [list, dropped] of byList) {
293    dropped.sort((a, b) => b.dropped - a.dropped)
294    const total = dropped.reduce((n, hit) => n + hit.dropped, 0)
295    const terms = dropped
296      .slice(0, MAX_TERMS_SHOWN)
297      .map((hit) => `${hit.term} (x${hit.dropped})`)
298      .join(', ')
299    const more = dropped.length > MAX_TERMS_SHOWN ? `, and ${dropped.length - MAX_TERMS_SHOWN} more` : ''
300    lines.push(`      ${plural(total, 'line')} dropped by "${list}": ${terms}${more}`)
301  }
302  return lines
303}
304
hooks/placeholders.ts 115 lines
1// Gives each hidden term the name the model reads in its place, and finds
2// those names again in what the model writes. A term's name depends only on
3// the term and this machine's seed, never on the session or on which text
4// it turned up in, so memory files, the prompt cache and a long transcript
5// stay consistent. The seed keeps the mapping from being recomputed by
6// anyone who has the word list but not this machine's store.
7
8import { CODENAMES } from './codenames.ts'
9
10export type PlaceholderStyle = 'codename' | 'tag'
11
12/** 32-bit FNV-1a: small, fast, and good enough to spread terms over names. */
13export function fnv1a(text: string): number {
14  let hash = 0x811c9dc5
15  for (let i = 0; i < text.length; i += 1) {
16    hash ^= text.charCodeAt(i)
17    hash = Math.imul(hash, 0x01000193)
18  }
19  return hash >>> 0
20}
21
22const CODENAME_SHAPE = /\b([A-Z][a-z]+)(\d*)(e?s)?\b/g
23const TAG_SHAPE = /\[hidden-[0-9a-f]{6}\](e?s)?/g
24
25/** One placeholder found in a text written by the model. */
26export type PlaceholderHit = {
27  start: number
28  end: number
29  name: string
30  /** A plural ending written after the name. */
31  suffix: string
32}
33
34/**
35 * The names for a set of folded terms. `avoid` lists folded strings no
36 * codename may equal or contain (the terms themselves, so a codename is
37 * never mistaken for a hidden word).
38 */
39export function assignPlaceholders(
40  foldedTerms: readonly string[],
41  style: PlaceholderStyle,
42  seed: string,
43  avoid: { equal: ReadonlySet<string>; contain: readonly string[] },
44): Map<string, string> {
45  const names = new Map<string, string>()
46  const taken = new Set<string>()
47  const unique = [...new Set(foldedTerms)].sort()
48
49  for (const term of unique) {
50    const hash = fnv1a(`${seed}\u0000${term}`)
51    names.set(term, style === 'tag' ? tagFor(hash, taken) : codenameFor(hash, taken, avoid))
52  }
53
54  return names
55}
56
57function codenameFor(
58  hash: number,
59  taken: Set<string>,
60  avoid: { equal: ReadonlySet<string>; contain: readonly string[] },
61): string {
62  const n = CODENAMES.length
63  const first = hash % n
64  // Always numbered, so a name is never a word people really write: a plain
65  // one would make every real mention of that word read as a hidden item.
66  const digit = 2 + (Math.floor(hash / n) % 8)
67
68  for (let c = 0; ; c += 1) {
69    const round = Math.floor((first + c) / n)
70    const name = `${CODENAMES[(first + c) % n]!}${round * 10 + digit}`
71    const lower = name.toLowerCase()
72    if (taken.has(name) || avoid.equal.has(lower) || avoid.contain.some((t) => lower.includes(t))) continue
73    taken.add(name)
74    return name
75  }
76}
77
78function tagFor(hash: number, taken: Set<string>): string {
79  for (let h = hash; ; h = (h + 1) >>> 0) {
80    const name = `[hidden-${h.toString(16).padStart(8, '0').slice(0, 6)}]`
81    if (taken.has(name)) continue
82    taken.add(name)
83    return name
84  }
85}
86
87/** Every placeholder of `known` in `text`, left to right. */
88export function findPlaceholders(text: string, known: ReadonlySet<string>): PlaceholderHit[] {
89  const hits: PlaceholderHit[] = []
90
91  for (const m of text.matchAll(CODENAME_SHAPE)) {
92    // The letters are greedy, so `Bubblegums` arrives whole: try it, then
93    // without a plural ending.
94    const word = `${m[1]}${m[2]}`
95    const suffix = m[3] ?? ''
96    const end = m.index + m[0].length
97    for (const cut of suffix === '' ? [0, 1, 2] : [0]) {
98      const name = word.slice(0, word.length - cut)
99      const ending = word.slice(word.length - cut) + suffix
100      if ((cut === 0 || /^e?s$/.test(ending)) && known.has(name)) {
101        hits.push({ start: m.index, end, name, suffix: ending })
102        break
103      }
104    }
105  }
106  for (const m of text.matchAll(TAG_SHAPE)) {
107    const name = m[0].slice(0, m[0].length - (m[1]?.length ?? 0))
108    if (known.has(name)) {
109      hits.push({ start: m.index, end: m.index + m[0].length, name, suffix: m[1] ?? '' })
110    }
111  }
112
113  return hits.sort((a, b) => a.start - b.start)
114}
115
hooks/sidebar.tsx 413 lines
1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4// The sidebar: a pane that shows, as the session goes, what topic-filter has
5// hidden. Drawn for the person only, like `/topic-filter log`: a pane is part
6// of the screen, never of what the model reads.
7//
8// Two tabs. Lists is a tree (list, then term, then the sources it was hidden
9// in) with a three-stop control that expands it to a depth; Feed is each pass
10// that hid something, newest first. Under both, bars for where hits came from.
11
12import type { BoxProps, ButtonProps, ElementConstructor, RenderElement, TextProps } from 'claude-code'
13
14import { KIND_LABELS, plural, type FeedItem, type Summary } from './log.ts'
15
16/** The pane's id, one per plugin. */
17export const SIDEBAR_ID = 'topic-filter'
18
19/** From this many distinct terms on, the tree starts collapsed to its lists. */
20export const CONDENSE_AT = 30
21
22/** The elements the sidebar draws with: every surface has these three. */
23export type SidebarUi = {
24  Box: ElementConstructor<BoxProps>
25  Text: ElementConstructor<TextProps>
26  Button: ElementConstructor<ButtonProps>
27}
28
29/** How deep the tree is open: 0 lists only, 1 their terms, 2 each term's sources. */
30export type Depth = 0 | 1 | 2
31
32/**
33 * What the person chose in the pane. `depth` set opens the tree to it;
34 * `null` means rows were opened one by one, as `open` lists; absent, the
35 * default for the summary's size.
36 */
37export type SidebarView = { tab: 'lists' | 'feed'; depth?: Depth | null; open: ReadonlySet<string> }
38
39export type SidebarInput = {
40  summary: Summary
41  /** The subagent in view and its label, or undefined for the whole session. */
42  agent?: string
43  /** Counts by list only, never a word, a placeholder or a source. */
44  countsOnly: boolean
45  /** Filtering is paused: the pane says so above everything else. */
46  isPaused?: boolean
47  view: SidebarView
48  /** The pane's body, in cells. */
49  columns: number
50  rows: number
51  /** Presses on the pane's buttons; `key` is the pressed element's. */
52  onPress: (key: string) => void
53}
54
55/** A tree row's id: a list, or a term within one. Also the row button's key, after `row:`. */
56export const listId = (list: string) => `l/${encodeURIComponent(list)}`
57export const termId = (list: string, term: string) => `t/${encodeURIComponent(list)}/${encodeURIComponent(term)}`
58
59/** The depth the tree opens to before the person picks one. */
60export const defaultDepth = (summary: Summary): Depth => (summary.terms >= CONDENSE_AT ? 0 : 1)
61
62/** Whether a row is open in `view`. */
63export function isOpen(view: SidebarView, summary: Summary, id: string): boolean {
64  const depth = view.depth === undefined ? defaultDepth(summary) : view.depth
65  if (depth === null) return view.open.has(id)
66  return id.startsWith('l/') ? depth >= 1 : depth >= 2
67}
68
69/** Every row open in `view` now, so a press can switch from a depth to rows picked one by one. */
70export function openRows(view: SidebarView, summary: Summary): Set<string> {
71  const ids = summary.lists.flatMap((list) => [
72    listId(list.list),
73    ...list.hits.map((hit) => termId(list.list, hit.term)),
74  ])
75  return new Set(ids.filter((id) => isOpen(view, summary, id)))
76}
77
78/** Short bars: the widest list's bar is this many cells. */
79const MINI = 8
80/** Room kept for a count at a row's end ("12 words"). */
81const COUNT_WIDTH = 9
82/** A term's column in the tree. */
83const TERM_WIDTH = 14
84
85/** "3 words, 2 lines": what a list or the session hid, in the person's terms. */
86function counts(x: { replaced: number; dropped: number }): string {
87  const parts: string[] = []
88  if (x.replaced > 0) parts.push(plural(x.replaced, 'word'))
89  if (x.dropped > 0) parts.push(plural(x.dropped, 'line'))
90  return parts.join(', ')
91}
92
93/** `text` cut or padded to exactly `width` cells. */
94function fit(text: string, width: number): string {
95  if (width <= 0) return ''
96  if (text.length > width) return width <= 3 ? text.slice(0, width) : `${text.slice(0, width - 3)}...`
97  return text.padEnd(width)
98}
99
100const clock = (at: number) => {
101  const d = new Date(at)
102  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
103}
104
105export function sidebarView({ Box, Text, Button }: SidebarUi, input: SidebarInput): RenderElement {
106  const { summary, agent, countsOnly, isPaused = false, view, onPress } = input
107  const columns = Math.max(24, input.columns - 1)
108  const total = summary.replaced + summary.dropped
109  const isEmpty = total === 0
110  const press = (key: string) => () => onPress(key)
111  const top: RenderElement[] = []
112  const body: RenderElement[] = []
113  const bottom: RenderElement[] = []
114  // Each element below is one row high (every Text truncates), so the rows
115  // are counted as they are added, and the stats can sit on the pane's floor.
116  let used = 0
117  const add = (to: RenderElement[], element: RenderElement, rows = 1) => {
118    to.push(element)
119    used += rows
120  }
121
122  if (isPaused) {
123    add(
124      top,
125      <Text key="paused" bold inverse wrap="truncate-end">
126        {fit(' PAUSED: nothing is hidden. /topic-filter on', columns)}
127      </Text>,
128    )
129  }
130  add(
131    top,
132    <Box key="total" flexDirection="row">
133      <Text key="n" bold inverse color="claude">{` ${total.toLocaleString('en-US')} `}</Text>
134      <Text key="what" bold wrap="truncate-end">
135        {agent === undefined ? ' hidden this session' : ' hidden in this subagent'}
136      </Text>
137    </Box>,
138  )
139  add(
140    top,
141    <Text key="detail" dimColor wrap="truncate-end">
142      {isEmpty
143        ? 'Nothing yet.'
144        : [
145            summary.replaced > 0 ? `${plural(summary.replaced, 'word')} replaced` : '',
146            summary.dropped > 0 ? `${plural(summary.dropped, 'line')} dropped` : '',
147          ]
148            .filter(Boolean)
149            .join(', ')}
150    </Text>,
151  )
152
153  const scope = agent !== undefined ? `subagent ${agent}` : 'whole session'
154  add(
155    top,
156    <Box key="tabs" flexDirection="row" marginTop={1} gap={2}>
157      <Button key="tab:lists" plain hotkey="1" dimColor={view.tab !== 'lists'} onPress={press('tab:lists')}>
158        Lists
159      </Button>
160      <Button key="tab:feed" plain hotkey="2" dimColor={view.tab !== 'feed'} onPress={press('tab:feed')}>
161        Feed
162      </Button>
163      <Box key="gap" flexGrow={1} />
164      <Text key="scope" dimColor wrap="truncate-start">
165        {scope}
166      </Text>
167    </Box>,
168    2,
169  )
170
171  if (view.tab === 'lists') treeRows()
172  else feedRows()
173  statsRows()
174
175  // Pin the stats to the floor when everything fits; else the pane scrolls.
176  const spare = input.rows - used
177  return (
178    <Box flexDirection="column" paddingRight={1}>
179      {top}
180      {body}
181      {spare > 0 ? <Box key="spacer" height={spare} /> : null}
182      {bottom}
183    </Box>
184  )
185
186  function treeRows(): void {
187    if (isEmpty) {
188      add(
189        body,
190        <Text key="empty" dimColor>
191          Hidden terms show here as Claude reads them.
192        </Text>,
193      )
194      return
195    }
196    if (!countsOnly) depthControl()
197    const widest = Math.max(1, ...summary.lists.map((list) => list.replaced + list.dropped))
198    for (const list of summary.lists) {
199      const id = listId(list.list)
200      const open = !countsOnly && isOpen(view, summary, id)
201      const weight = list.replaced + list.dropped
202      const bar = '▮'.repeat(Math.max(1, Math.round((weight / widest) * MINI))).padEnd(MINI)
203      const nameWidth = columns - 2 - MINI - 1 - COUNT_WIDTH
204      const name = `${countsOnly ? ' ' : open ? '▾' : '▸'} ${fit(list.list, nameWidth)}`
205      add(
206        body,
207        <Box key={`row-${id}`} flexDirection="row">
208          {countsOnly ? (
209            <Text key="name" bold>
210              {name}
211            </Text>
212          ) : (
213            <Button key={`row:${id}`} plain onPress={press(`row:${id}`)}>
214              {name}
215            </Button>
216          )}
217          <Text key="bar" color="claude">
218            {bar}
219          </Text>
220          <Text key="n" dimColor>
221            {counts(list).padStart(COUNT_WIDTH)}
222          </Text>
223        </Box>,
224      )
225      if (!open) continue
226      for (const hit of list.hits) {
227        const tid = termId(list.list, hit.term)
228        const termOpen = isOpen(view, summary, tid)
229        const shown = hit.replaced > 0 ? `-> ${hit.placeholder}` : 'line dropped'
230        const n = `x${hit.replaced + hit.dropped}`
231        add(
232          body,
233          <Box key={`row-${tid}`} flexDirection="row" paddingLeft={2}>
234            <Button
235              key={`row:${tid}`}
236              plain
237              onPress={press(`row:${tid}`)}
238            >{`${termOpen ? '▾' : '▸'} ${fit(hit.term, TERM_WIDTH)}`}</Button>
239            <Box key="as" flexGrow={1}>
240              <Text
241                key="as"
242                color={hit.replaced > 0 ? 'warning' : undefined}
243                dimColor={hit.replaced === 0}
244                wrap="truncate-end"
245              >{` ${shown}`}</Text>
246            </Box>
247            <Text key="n" dimColor>{` ${n}`}</Text>
248          </Box>,
249        )
250        if (!termOpen) continue
251        for (const [i, source] of hit.sources.entries()) {
252          add(
253            body,
254            <Text key={`src-${tid}-${i}`} dimColor wrap="truncate-end">{`       ${source.label} x${source.n}`}</Text>,
255          )
256        }
257      }
258    }
259  }
260
261  /** `Expand ● none ──── ○ lists ──── ○ all`: the line fills up to the depth in use. */
262  function depthControl(): void {
263    const depth = view.depth === undefined ? defaultDepth(summary) : view.depth
264    const stops: [Depth, string][] = [
265      [0, 'none'],
266      [1, 'lists'],
267      [2, 'all'],
268    ]
269    const fixed = 'Expand '.length + stops.reduce((n, [, label]) => n + label.length + 3, 0)
270    const line = '─'.repeat(Math.max(2, Math.floor((columns - fixed) / 2)))
271    const parts: RenderElement[] = [
272      <Text key="label" dimColor>
273        Expand{' '}
274      </Text>,
275    ]
276    for (const [n, label] of stops) {
277      if (n > 0)
278        parts.push(
279          <Text
280            key={`line-${n}`}
281            color={depth !== null && depth >= n ? 'claude' : undefined}
282            dimColor={depth === null || depth < n}
283          >
284            {line}
285          </Text>,
286        )
287      parts.push(
288        <Button
289          key={`depth:${n}`}
290          plain
291          dimColor={depth !== n}
292          onPress={press(`depth:${n}`)}
293        >{`${depth === n ? '●' : '○'} ${label}`}</Button>,
294      )
295    }
296    add(
297      body,
298      <Box key="depth" flexDirection="row" marginBottom={1}>
299        {parts}
300      </Box>,
301      2,
302    )
303  }
304
305  function feedRows(): void {
306    if (summary.feed.length === 0) {
307      add(
308        body,
309        <Text key="empty" dimColor>
310          Each hit shows here as it happens, newest first.
311        </Text>,
312      )
313      return
314    }
315    // The pane scrolls, but a feed longer than a screen or two is noise.
316    for (const [i, item] of summary.feed.slice(0, Math.max(10, input.rows)).entries()) feedItem(item, i)
317  }
318
319  function feedItem(item: FeedItem, i: number): void {
320    const who = agent === undefined && item.agent !== undefined ? 'Subagent: ' : ''
321    const what = countsOnly
322      ? `${who}${item.hits.length === 1 ? '1 term' : `${item.hits.length} terms`}`
323      : `${who}${item.label}`
324    const n = counts(item)
325    add(
326      body,
327      <Box key={`feed-${i}`} flexDirection="row">
328        <Text key="at" dimColor>{`${clock(item.at)} `}</Text>
329        <Box key="what" flexGrow={1}>
330          <Text key="what" wrap="truncate-end">
331            {what}
332          </Text>
333        </Box>
334        <Text key="n" dimColor>{` ${n}`}</Text>
335      </Box>,
336    )
337    const lists = [...new Set(item.hits.map((hit) => hit.list))]
338    const detail = countsOnly
339      ? lists.join(', ')
340      : lists
341          .map(
342            (list) =>
343              `${list}: ${item.hits
344                .filter((hit) => hit.list === list)
345                .map((hit) => `${hit.term} x${hit.n}`)
346                .join(', ')}`,
347          )
348          .join('; ')
349    add(body, <Text key={`feed-${i}-hits`} dimColor wrap="truncate-end">{`      ${detail}`}</Text>)
350  }
351
352  function statsRows(): void {
353    if (isEmpty) return
354    add(
355      bottom,
356      <Text key="rule" dimColor>
357        {'─'.repeat(columns)}
358      </Text>,
359      2,
360    )
361    add(
362      bottom,
363      <Box key="where" flexDirection="row">
364        <Box key="title" flexGrow={1}>
365          <Text key="title" bold>
366            Where it came from
367          </Text>
368        </Box>
369        {summary.lastAt === undefined ? null : <Text key="last" dimColor>{`last hit ${clock(summary.lastAt)}`}</Text>}
370      </Box>,
371    )
372    const most = Math.max(1, ...summary.kinds.map((k) => k.n))
373    const width = Math.max(4, columns - 12 - 5)
374    for (const { kind, n } of summary.kinds) {
375      const fill = Math.max(1, Math.round((n / most) * width))
376      add(
377        bottom,
378        <Box key={`kind-${kind}`} flexDirection="row">
379          <Text key="label">{fit(KIND_LABELS[kind], 12)}</Text>
380          <Text key="fill" color="claude">
381            {'█'.repeat(fill)}
382          </Text>
383          {fill < width ? (
384            <Text key="track" dimColor>
385              {'░'.repeat(width - fill)}
386            </Text>
387          ) : null}
388          <Text key="n" dimColor>
389            {String(n).padStart(5)}
390          </Text>
391        </Box>,
392      )
393    }
394    const facts: [number, string][] = [
395      [summary.terms, 'term'],
396      [summary.lists.length, 'list'],
397      [summary.sources, 'source'],
398    ]
399    if (agent === undefined && summary.agents.length > 0) facts.push([summary.agents.length, 'subagent'])
400    add(
401      bottom,
402      <Box key="facts" flexDirection="row" gap={2} marginTop={1}>
403        {facts.map(([n, noun]) => (
404          <Text key={noun} dimColor>
405            {plural(n, noun)}
406          </Text>
407        ))}
408      </Box>,
409      2,
410    )
411  }
412}
413
hooks/redact.ts 358 lines
1// The filter: a compiled topics file that rewrites what the model is about
2// to read and checks what it is about to do.
3//
4// Reading: every string is searched for listed terms. A `drop-line` list's
5// term removes each line it appears on; where a whole string goes that way
6// inside an array (one repository in a JSON listing, one path in a Glob
7// result), the array's item goes with it. Everything else becomes the term's
8// placeholder. JSON printed as text (`gh ... --json`) is parsed, filtered as
9// structure, and printed again.
10//
11// Writing: a tool call that uses a placeholder is found here; the hook then
12// refuses it, or for a `restore` list writes the real term back.
13
14import type { Config } from './config.ts'
15import { foldTerm, Matcher, type Match, type TermRef } from './matcher.ts'
16import { assignPlaceholders, findPlaceholders } from './placeholders.ts'
17
18/** What one filtering pass hid, for the note the model reads and the status line. */
19export type Tally = {
20  replaced: number
21  dropped: number
22  /** The placeholders written, so the note can name them. */
23  names: Set<string>
24  /** Each term hidden, by folded term: for the person's log only, never the model. */
25  hits: Map<string, Hit>
26}
27
28/** One term's share of a pass: how often it became its placeholder, and how many lines it dropped. */
29export type Hit = { term: string; placeholder: string; list: string; replaced: number; dropped: number }
30
31export const newTally = (): Tally => ({ replaced: 0, dropped: 0, names: new Set(), hits: new Map() })
32
33/** A filtered value: `vanished` when a dropped line took the whole of it. */
34type Filtered<T> = { value: T; changed: boolean; vanished: boolean }
35
36/** Terms shorter than this, folded, are ignored: they would match everywhere. */
37const MIN_TERM_LENGTH = 2
38
39/** Keys whose strings are enums or engine ids, never free text. */
40const SKIPPED_KEYS = new Set(['type', 'kind', 'mode', 'action', 'media_type', 'mediaType', 'tool_use_id', 'agentId'])
41
42/** Keys of `tool.call`'s input that belong to the engine, not the tool. */
43const RESERVED_INPUT_KEYS = new Set(['tool', 'tool_use_id', 'agentId', 'consent'])
44
45/** Past this many characters a string is not parsed as JSON. */
46const MAX_JSON_PARSE = 2_000_000
47
48const MAX_DEPTH = 64
49
50const isPlainObject = (v: unknown): v is Record<string, unknown> =>
51  typeof v === 'object' && v !== null && !Array.isArray(v)
52
53/** Image and file bytes as text: nothing in them is a word, and a rewrite would corrupt them. */
54function isEncodedBytes(s: string): boolean {
55  if (s.startsWith('data:') && s.slice(0, 100).includes(';base64,')) return true
56  return s.length >= 256 && /^[A-Za-z0-9+/=_-]+$/.test(s)
57}
58
59function looksLikeJson(s: string): boolean {
60  const t = s.trim()
61  if (t.length < 2 || t.length > MAX_JSON_PARSE) return false
62  const first = t[0]
63  const last = t[t.length - 1]
64  return (first === '{' && last === '}') || (first === '[' && last === ']')
65}
66
67export class Filter {
68  private readonly matcher = new Matcher()
69  /** Folded term to its placeholder. */
70  private readonly placeholderOf = new Map<string, string>()
71  /** Placeholder to the term a restore writes back. */
72  private readonly canonicalOf = new Map<string, string>()
73  /** Placeholders whose use in a tool call is refused. */
74  readonly guarded = new Set<string>()
75  /** Placeholders a tool call may use; the real term is put back. */
76  readonly restorable = new Set<string>()
77  readonly informModel: boolean
78  /** Each list's name, by index, for the person's log. */
79  private readonly listNames: readonly string[]
80  /** How many terms were too short to use. */
81  readonly skippedTerms: number
82  /** How many distinct terms are active. */
83  readonly termCount: number
84
85  /**
86   * @param config the parsed topics file
87   * @param seed this machine's seed for placeholder names
88   * @param packTerms a pack's terms per list index, always matched as whole words: thousands of
89   *   terms matched inside words would hide text everywhere
90   */
91  constructor(config: Config, seed: string, packTerms: ReadonlyMap<number, readonly string[]> = new Map()) {
92    this.informModel = config.informModel
93    this.listNames = config.lists.map((list) => list.name)
94
95    const refs: TermRef[] = []
96    let skipped = 0
97    config.lists.forEach((list, i) => {
98      const excluded = new Set(list.exclude.map(foldTerm))
99      const sources: [readonly string[], boolean][] = [
100        [list.terms, list.match === 'word'],
101        [packTerms.get(i) ?? [], true],
102      ]
103      for (const [terms, isWordOnly] of sources) {
104        for (const term of terms) {
105          const folded = foldTerm(term)
106          if (folded.length < MIN_TERM_LENGTH) {
107            skipped += 1
108            continue
109          }
110          if (excluded.has(folded)) continue
111          refs.push({ folded, canonical: term.trim(), list: i, mode: list.mode, isWordOnly })
112        }
113      }
114    })
115    this.skippedTerms = skipped
116
117    for (const ref of refs) this.matcher.add(ref)
118    this.termCount = this.matcher.size()
119
120    const folded = refs.map((r) => r.folded)
121    const names = assignPlaceholders(folded, config.placeholder, seed, {
122      equal: new Set(folded),
123      contain: refs.filter((r) => !r.isWordOnly).map((r) => r.folded),
124    })
125
126    // A term listed twice keeps its first spelling for restores, and is
127    // guarded if any list holding it is not a restore list.
128    const restoreOnly = new Map<string, boolean>()
129    for (const ref of refs) {
130      const name = names.get(ref.folded)!
131      this.placeholderOf.set(ref.folded, name)
132      if (!this.canonicalOf.has(name)) this.canonicalOf.set(name, ref.canonical)
133      const isRestore = config.lists[ref.list]!.restore
134      restoreOnly.set(name, (restoreOnly.get(name) ?? true) && isRestore)
135    }
136    for (const [name, isRestore] of restoreOnly) (isRestore ? this.restorable : this.guarded).add(name)
137  }
138
139  /** Whether `text` holds any listed term. */
140  hasTerm(text: string): boolean {
141    return this.matcher.test(text)
142  }
143
144  /**
145   * Filters free text. `allowDrop` false makes drop-line terms placeholders
146   * too: a person's own prompt keeps all its lines.
147   */
148  text(text: string, tally: Tally, allowDrop = true): Filtered<string> {
149    let matches = this.matcher.find(text)
150    if (matches.length === 0) return { value: text, changed: false, vanished: false }
151
152    let out = text
153    if (allowDrop && matches.some((m) => m.ref.mode === 'drop-line')) {
154      // A literal `\n` ends a line too: some output prints its newlines as text.
155      const lines = text.split(/(?<=\n|\\n)/)
156      const kept = lines.filter((line) => {
157        const dropper = this.matcher.find(line).find((m) => m.ref.mode === 'drop-line')
158        if (dropper !== undefined) this.hit(tally, dropper.ref).dropped += 1
159        return dropper === undefined
160      })
161      tally.dropped += lines.length - kept.length
162      if (kept.length === 0) return { value: '', changed: true, vanished: true }
163      out = kept.join('')
164      matches = this.matcher.find(out)
165    }
166
167    return { value: this.replace(out, matches, tally), changed: true, vanished: false }
168  }
169
170  private replace(text: string, matches: readonly Match[], tally: Tally): string {
171    if (matches.length === 0) return text
172
173    const parts: string[] = []
174    let at = 0
175    for (const m of matches) {
176      const name = this.placeholderOf.get(m.ref.folded)!
177      parts.push(text.slice(at, m.start), name, m.suffix)
178      tally.replaced += 1
179      tally.names.add(name)
180      this.hit(tally, m.ref).replaced += 1
181      at = m.end
182    }
183    parts.push(text.slice(at))
184    return parts.join('')
185  }
186
187  /** The tally's entry for a term, made on first use. A line is dropped by the first drop-line term on it. */
188  private hit(tally: Tally, ref: TermRef): Hit {
189    let hit = tally.hits.get(ref.folded)
190    if (hit === undefined) {
191      hit = {
192        term: ref.canonical,
193        placeholder: this.placeholderOf.get(ref.folded)!,
194        list: this.listNames[ref.list]!,
195        replaced: 0,
196        dropped: 0,
197      }
198      tally.hits.set(ref.folded, hit)
199    }
200    return hit
201  }
202
203  /** Filters any value: strings anywhere inside it, JSON printed as text included. */
204  value(value: unknown, tally: Tally, depth = 0): Filtered<unknown> {
205    if (depth > MAX_DEPTH) return { value, changed: false, vanished: false }
206
207    if (typeof value === 'string') return this.string(value, tally, depth)
208
209    if (Array.isArray(value)) {
210      let changed = false
211      const out: unknown[] = []
212      for (const item of value) {
213        const r = this.value(item, tally, depth + 1)
214        changed ||= r.changed
215        if (!r.vanished) out.push(r.value)
216      }
217      return changed ? { value: out, changed, vanished: false } : { value, changed, vanished: false }
218    }
219
220    if (isPlainObject(value)) {
221      let changed = false
222      let vanished = false
223      const out: Record<string, unknown> = {}
224      for (const [key, child] of Object.entries(value)) {
225        if (SKIPPED_KEYS.has(key)) {
226          out[key] = child
227          continue
228        }
229        const r = this.value(child, tally, depth + 1)
230        changed ||= r.changed
231        vanished ||= r.vanished
232        out[key] = r.value
233      }
234      return changed ? { value: out, changed, vanished } : { value, changed, vanished: false }
235    }
236
237    return { value, changed: false, vanished: false }
238  }
239
240  private string(s: string, tally: Tally, depth: number): Filtered<unknown> {
241    if (isEncodedBytes(s) || !this.matcher.test(s)) return { value: s, changed: false, vanished: false }
242
243    if (looksLikeJson(s)) {
244      let parsed: unknown
245      let isJson = true
246      try {
247        parsed = JSON.parse(s)
248      } catch {
249        isJson = false
250      }
251      if (isJson) {
252        const r = this.value(parsed, tally, depth + 1)
253        if (r.vanished) return { value: '', changed: true, vanished: true }
254        const lead = s.slice(0, s.length - s.trimStart().length)
255        const trail = s.slice(s.trimEnd().length)
256        const indent = /\n([ \t]+)\S/.exec(s)?.[1]
257        return { value: lead + JSON.stringify(r.value, null, indent) + trail, changed: true, vanished: false }
258      }
259    }
260
261    return this.text(s, tally)
262  }
263
264  /** The guarded placeholders `input` uses, the engine's own keys aside. */
265  guardedIn(input: Record<string, unknown>): string[] {
266    const found = new Set<string>()
267    forEachString(input, (s) => {
268      for (const hit of findPlaceholders(s, this.guarded)) found.add(hit.name)
269    })
270    return [...found]
271  }
272
273  /** `input` with each restorable placeholder replaced by its real term. */
274  restore(input: Record<string, unknown>): { value: Record<string, unknown>; changed: boolean } {
275    if (this.restorable.size === 0) return { value: input, changed: false }
276
277    let changed = false
278    const swap = (s: string): string => {
279      const hits = findPlaceholders(s, this.restorable)
280      if (hits.length === 0) return s
281      changed = true
282      const parts: string[] = []
283      let at = 0
284      for (const hit of hits) {
285        parts.push(s.slice(at, hit.start), this.canonicalOf.get(hit.name)!, hit.suffix)
286        at = hit.end
287      }
288      parts.push(s.slice(at))
289      return parts.join('')
290    }
291
292    const out: Record<string, unknown> = {}
293    for (const [key, child] of Object.entries(input)) {
294      out[key] = RESERVED_INPUT_KEYS.has(key) ? child : mapStrings(child, swap)
295    }
296    return { value: out, changed }
297  }
298}
299
300/** Calls `visit` on every string in a tool call's input, the engine's own keys aside. */
301export function forEachString(input: Record<string, unknown>, visit: (s: string) => void): void {
302  const walk = (v: unknown, depth: number): void => {
303    if (depth > MAX_DEPTH) return
304    if (typeof v === 'string') visit(v)
305    else if (Array.isArray(v)) for (const item of v) walk(item, depth + 1)
306    else if (isPlainObject(v)) for (const child of Object.values(v)) walk(child, depth + 1)
307  }
308  for (const [key, child] of Object.entries(input)) {
309    if (!RESERVED_INPUT_KEYS.has(key)) walk(child, 0)
310  }
311}
312
313function mapStrings(v: unknown, f: (s: string) => string, depth = 0): unknown {
314  if (depth > MAX_DEPTH) return v
315  if (typeof v === 'string') return f(v)
316  if (Array.isArray(v)) return v.map((item) => mapStrings(item, f, depth + 1))
317  if (isPlainObject(v)) {
318    const out: Record<string, unknown> = {}
319    for (const [key, child] of Object.entries(v)) out[key] = mapStrings(child, f, depth + 1)
320    return out
321  }
322  return v
323}
324
325/**
326 * The note that tells the model what a filtered text holds, or undefined
327 * when nothing was hidden. It names placeholders, never terms or lists.
328 */
329export function noteFor(tally: Tally, restorable: ReadonlySet<string> = new Set()): string | undefined {
330  if (tally.replaced === 0 && tally.dropped === 0) return undefined
331
332  const parts: string[] = []
333  if (tally.replaced > 0) {
334    const names = [...tally.names].slice(0, 12).join(', ')
335    parts.push(
336      `${tally.replaced} hidden term${tally.replaced === 1 ? ' was' : 's were'} replaced with placeholder names (${names})`,
337    )
338  }
339  if (tally.dropped > 0) {
340    parts.push(
341      `${tally.dropped} line${tally.dropped === 1 ? '' : 's'} mentioning hidden items ${tally.dropped === 1 ? 'was' : 'were'} removed`,
342    )
343  }
344
345  const usable = [...tally.names].filter((name) => restorable.has(name))
346  const rule =
347    usable.length === 0
348      ? 'Mentioning a placeholder in a reply is fine, but a tool call that uses one (a command, search or file edit) is refused.'
349      : usable.length === tally.names.size
350        ? 'These placeholders may be used in tool calls: the real name is put back before the tool runs.'
351        : `Of these, ${usable.join(', ')} may be used in tool calls (the real name is put back); a tool call using any other is refused.`
352
353  return (
354    `topic-filter: ${parts.join(', and ')}. The user has set these items aside as off-topic for this session. ` +
355    `Treat a placeholder as an opaque name and do not guess what it stands for. ${rule}`
356  )
357}
358
hooks/matcher.ts 214 lines
1// Finds listed terms in text. Text and terms are folded the same way before
2// they are compared: accents stripped, lower-cased, and every run of spaces,
3// hyphens and underscores made one space, so `Teotihuacán`, `teotihuacan`
4// and `TEOTIHUACAN` are one term, and `secret repo` also finds
5// `secret-repo` and `secret_repo`. A match is reported in the ORIGINAL
6// text's positions, so the caller replaces exactly what was written.
7
8/** How a list hides what it finds. */
9export type Mode = 'replace' | 'drop-line'
10
11/** One listed term, as the matcher reports it. */
12export type TermRef = {
13  /** The term folded, the key its placeholder is kept under. */
14  folded: string
15  /** The term as the topics file spells it; what a restore writes back. */
16  canonical: string
17  /** Index of the list the term came from. */
18  list: number
19  mode: Mode
20  /** Whether the term must stand as whole words (true) or may sit inside one. */
21  isWordOnly: boolean
22}
23
24/** A term found in a text: `[start, end)` in the original's UTF-16 indices. */
25export type Match = {
26  start: number
27  end: number
28  ref: TermRef
29  /** A plural ending (`s`, `es`) the match took after the term, as written. */
30  suffix: string
31}
32
33/** Text folded for matching, with each folded unit's span in the original. */
34type Folded = {
35  text: string
36  starts: number[]
37  ends: number[]
38}
39
40const SEPARATOR = /[\s\-_‐-―]/u
41const MARKS = /\p{M}+/gu
42const WORD = /[\p{L}\p{N}]/u
43
44/** Folds one code point the way terms are folded. */
45function foldChar(ch: string): string {
46  if (ch === '’' || ch === '‘') return "'"
47  return ch.normalize('NFD').replace(MARKS, '').toLowerCase()
48}
49
50/** Folds a whole text, keeping where each folded unit came from. */
51function fold(text: string): Folded {
52  const out: string[] = []
53  const starts: number[] = []
54  const ends: number[] = []
55  let pos = 0
56  let lastWasSeparator = false
57
58  for (const ch of text) {
59    const start = pos
60    pos += ch.length
61
62    if (SEPARATOR.test(ch)) {
63      if (lastWasSeparator) {
64        ends[ends.length - 1] = pos
65      } else {
66        out.push(' ')
67        starts.push(start)
68        ends.push(pos)
69      }
70      lastWasSeparator = true
71      continue
72    }
73
74    lastWasSeparator = false
75    for (const unit of foldChar(ch)) {
76      out.push(unit)
77      starts.push(start)
78      ends.push(pos)
79    }
80  }
81
82  return { text: out.join(''), starts, ends }
83}
84
85/** A term folded on its own, trimmed: the key terms are compared by. */
86export function foldTerm(term: string): string {
87  return fold(term).text.trim()
88}
89
90type Node = {
91  next: Map<string, Node>
92  ref?: TermRef
93}
94
95const isWordAt = (text: string, i: number) => i >= 0 && i < text.length && WORD.test(text[i]!)
96
97/**
98 * A literal escape such as `\n` or `\t` (backslash, letter) ends the word
99 * before it: `gh --template '...\n...'` and logs print them as text, and
100 * `\ngpmap` must still find `gpmap`.
101 */
102const startsWord = (text: string, i: number) =>
103  !isWordAt(text, i - 1) || (text[i - 2] === '\\' && 'ntr'.includes(text[i - 1]!))
104
105/** Matches a set of terms in text, leftmost first and longest at each start. */
106export class Matcher {
107  private readonly root: Node = { next: new Map() }
108  private count = 0
109
110  /** How many distinct folded terms the matcher holds. */
111  size(): number {
112    return this.count
113  }
114
115  /**
116   * Adds a term. A term folded the same as one already held keeps the first
117   * list's settings, unless the new one drops lines where the held one only
118   * replaces: the stronger hiding wins.
119   */
120  add(ref: TermRef): void {
121    let node = this.root
122    for (const unit of ref.folded) {
123      let child = node.next.get(unit)
124      if (child === undefined) {
125        child = { next: new Map() }
126        node.next.set(unit, child)
127      }
128      node = child
129    }
130
131    if (node.ref === undefined) {
132      node.ref = ref
133      this.count += 1
134    } else if (node.ref.mode === 'replace' && ref.mode === 'drop-line') {
135      node.ref = ref
136    }
137  }
138
139  /** Every term in `text`, left to right, none overlapping. */
140  find(text: string): Match[] {
141    if (this.count === 0 || text.length === 0) return []
142
143    const folded = fold(text)
144    const t = folded.text
145    const matches: Match[] = []
146    let i = 0
147
148    while (i < t.length) {
149      const found = this.longestAt(t, i)
150      if (found === undefined) {
151        i += 1
152        continue
153      }
154
155      const [endExclusive, ref, suffixLength] = found
156      const last = endExclusive + suffixLength - 1
157      const termEnd = folded.ends[endExclusive - 1]!
158      const end = folded.ends[last]!
159      matches.push({
160        start: folded.starts[i]!,
161        end,
162        ref,
163        suffix: text.slice(termEnd, end),
164      })
165      i = endExclusive + suffixLength
166    }
167
168    return matches
169  }
170
171  /** True when `text` holds any term; cheaper to say than `find` is to list. */
172  test(text: string): boolean {
173    return this.find(text).length > 0
174  }
175
176  /**
177   * The longest term starting at folded index `i` that stands where it is:
178   * `[end, ref, suffixLength]`, or undefined.
179   */
180  private longestAt(t: string, i: number): [number, TermRef, number] | undefined {
181    if (t[i] === ' ') return undefined
182
183    const boundaryBefore = startsWord(t, i)
184    let node: Node | undefined = this.root
185    let best: [number, TermRef, number] | undefined
186    let j = i
187
188    while (j < t.length) {
189      node = node.next.get(t[j]!)
190      if (node === undefined) break
191      j += 1
192
193      const ref = node.ref
194      if (ref === undefined) continue
195
196      if (!ref.isWordOnly) {
197        best = [j, ref, 0]
198        continue
199      }
200      if (!boundaryBefore) continue
201
202      if (!isWordAt(t, j)) {
203        best = [j, ref, 0]
204      } else if (t[j] === 's' && !isWordAt(t, j + 1)) {
205        best = [j, ref, 1]
206      } else if (t[j] === 'e' && t[j + 1] === 's' && !isWordAt(t, j + 2)) {
207        best = [j, ref, 2]
208      }
209    }
210
211    return best
212  }
213}
214
hooks/codenames.ts 266 lines
1// The words a hidden term's codename is picked from. Chosen to read as
2// ordinary names while being rare in code, logs and shell output, so a
3// codename in a tool call almost certainly came from a placeholder. When a
4// session needs more names than these, a number follows (`Bubblegum2`).
5// Keep every entry a single capitalized word of letters only: the guard
6// finds codenames by that shape.
7
8export const CODENAMES: readonly string[] = [
9  'Bubblegum',
10  'Marmalade',
11  'Pinwheel',
12  'Kazoo',
13  'Snorkel',
14  'Gumdrop',
15  'Waffle',
16  'Pretzel',
17  'Teacup',
18  'Walrus',
19  'Platypus',
20  'Porcupine',
21  'Accordion',
22  'Trombone',
23  'Tambourine',
24  'Lollipop',
25  'Marshmallow',
26  'Doughnut',
27  'Periwinkle',
28  'Buttercup',
29  'Dandelion',
30  'Huckleberry',
31  'Gooseberry',
32  'Kumquat',
33  'Persimmon',
34  'Rhubarb',
35  'Parsnip',
36  'Rutabaga',
37  'Artichoke',
38  'Butterscotch',
39  'Nougat',
40  'Toffee',
41  'Meringue',
42  'Crumpet',
43  'Scone',
44  'Strudel',
45  'Popover',
46  'Macaroon',
47  'Biscotti',
48  'Cannoli',
49  'Churro',
50  'Dumpling',
51  'Pancake',
52  'Flapjack',
53  'Muffin',
54  'Custard',
55  'Sherbet',
56  'Sorbet',
57  'Gelato',
58  'Tapioca',
59  'Licorice',
60  'Fudge',
61  'Truffle',
62  'Praline',
63  'Brioche',
64  'Baguette',
65  'Croissant',
66  'Bagel',
67  'Pierogi',
68  'Tamale',
69  'Empanada',
70  'Gnocchi',
71  'Ravioli',
72  'Tortellini',
73  'Anchovy',
74  'Barnacle',
75  'Pelican',
76  'Flamingo',
77  'Penguin',
78  'Puffin',
79  'Toucan',
80  'Cockatoo',
81  'Parakeet',
82  'Hummingbird',
83  'Kingfisher',
84  'Sandpiper',
85  'Heron',
86  'Albatross',
87  'Cormorant',
88  'Starling',
89  'Wombat',
90  'Koala',
91  'Kangaroo',
92  'Wallaby',
93  'Armadillo',
94  'Aardvark',
95  'Anteater',
96  'Hedgehog',
97  'Chipmunk',
98  'Marmot',
99  'Beaver',
100  'Otter',
101  'Badger',
102  'Ferret',
103  'Weasel',
104  'Mongoose',
105  'Meerkat',
106  'Lemur',
107  'Sloth',
108  'Tapir',
109  'Okapi',
110  'Narwhal',
111  'Manatee',
112  'Dugong',
113  'Octopus',
114  'Squid',
115  'Cuttlefish',
116  'Seahorse',
117  'Starfish',
118  'Jellyfish',
119  'Lobster',
120  'Crawfish',
121  'Tortoise',
122  'Iguana',
123  'Chameleon',
124  'Gecko',
125  'Salamander',
126  'Axolotl',
127  'Newt',
128  'Tadpole',
129  'Bumblebee',
130  'Ladybug',
131  'Dragonfly',
132  'Firefly',
133  'Grasshopper',
134  'Cricket',
135  'Caterpillar',
136  'Butterfly',
137  'Harmonica',
138  'Bagpipe',
139  'Banjo',
140  'Ukulele',
141  'Mandolin',
142  'Xylophone',
143  'Glockenspiel',
144  'Bassoon',
145  'Clarinet',
146  'Oboe',
147  'Piccolo',
148  'Tuba',
149  'Cowbell',
150  'Maraca',
151  'Didgeridoo',
152  'Ocarina',
153  'Teapot',
154  'Kettle',
155  'Colander',
156  'Ladle',
157  'Spatula',
158  'Whisk',
159  'Thimble',
160  'Doorknob',
161  'Lampshade',
162  'Umbrella',
163  'Galosh',
164  'Mitten',
165  'Earmuff',
166  'Scarf',
167  'Bonnet',
168  'Beret',
169  'Sombrero',
170  'Fedora',
171  'Bowtie',
172  'Suspender',
173  'Cufflink',
174  'Monocle',
175  'Pocketwatch',
176  'Hourglass',
177  'Telescope',
178  'Periscope',
179  'Kaleidoscope',
180  'Gyroscope',
181  'Metronome',
182  'Sextant',
183  'Astrolabe',
184  'Compass',
185  'Lighthouse',
186  'Windmill',
187  'Gazebo',
188  'Pergola',
189  'Treehouse',
190  'Igloo',
191  'Wigwam',
192  'Chalet',
193  'Carousel',
194  'Ferris',
195  'Trampoline',
196  'Seesaw',
197  'Hopscotch',
198  'Yoyo',
199  'Frisbee',
200  'Boomerang',
201  'Pogostick',
202  'Scooter',
203  'Tricycle',
204  'Unicycle',
205  'Rickshaw',
206  'Gondola',
207  'Zeppelin',
208  'Dirigible',
209  'Canoe',
210  'Kayak',
211  'Dinghy',
212  'Schooner',
213  'Tugboat',
214  'Paddleboat',
215  'Hovercraft',
216  'Submarine',
217  'Snowglobe',
218  'Pinecone',
219  'Acorn',
220  'Chestnut',
221  'Walnut',
222  'Hazelnut',
223  'Pistachio',
224  'Cashew',
225  'Coconut',
226  'Pineapple',
227  'Mango',
228  'Papaya',
229  'Guava',
230  'Lychee',
231  'Rambutan',
232  'Durian',
233  'Tangerine',
234  'Clementine',
235  'Grapefruit',
236  'Pomelo',
237  'Apricot',
238  'Nectarine',
239  'Plum',
240  'Quince',
241  'Cranberry',
242  'Blueberry',
243  'Raspberry',
244  'Blackberry',
245  'Elderberry',
246  'Mulberry',
247  'Boysenberry',
248  'Cloudberry',
249  'Paprika',
250  'Nutmeg',
251  'Cinnamon',
252  'Saffron',
253  'Cardamom',
254  'Turmeric',
255  'Oregano',
256  'Tarragon',
257  'Pumpernickel',
258  'Sourdough',
259  'Focaccia',
260  'Ciabatta',
261  'Pita',
262  'Naan',
263  'Tortilla',
264  'Chapati',
265]
266