SLOPSHOPPER

cmod

Claude Mod Manager: fetches the cmod program for every mod, runs the uninstall step of each mod Claude Code removes, and carries calls from one mod to another.

★ 2v4.3.1MITupdated 2026-10-26heyJordanParker/cmod
A shopper browsing a rack in a slop shop
README

<img src=".claude-plugin/icon.png" alt="Claude Mod Manager" width="160">

<h1 align="center">Claude Mod Manager</h1>

Claude Mod Manager (cmod) installs and builds Claude Code mods. A mod is a Claude Code plugin built with the @cmodjs/core package. It can hear and change what happens in a session, and add panes, slash commands, tools, and permission rules, and it can run its own install step. cmod installs mods, runs their install and uninstall steps with your consent, and helps you build and publish your own.

Install a mod

In Claude Code, add the mod's marketplace and install the mod:

/plugin marketplace add <owner>/<repo>
/plugin install <mod>@<marketplace>

Claude Code installs the cmod plugin with the mod. To install the cmod plugin on its own, as an author building a mod does:

/plugin install cmod --marketplace heyJordanParker/cmod

Once a mod is installed, cmod fetches the cmod program and opens the mod's install page, the Install <mod> tab of the Sidebar, and the mod runs its install step once you accept. The page names each command the mod runs, each hotkey it binds, and each permission it asks for, such as "connect to api.github.com" or "run gh on your computer". It then asks for any setting the mod needs, and walks you through any step only you can do, such as signing in. The mod can reach nothing else through cmod. A progress bar shows each step. A notice tells you when the mod is ready.

The Sidebar is cmod's pane beside the conversation. meta+0 shows or hides it. Its tabs are the Dashboard, each page a mod opened, and Settings, and 0, 1 to 8, and 9 switch between them. meta+m and /mods open Settings.

Settings lists every mod with the one-line description from its plugin.json, whether Claude Code has it turned off, its own settings pages, its options, its permissions, its hotkeys, and its changelog. When a mod installs, a toast says what it adds. Turn a permission off there and the mod loses it before its next call. Type a new combo for a hotkey, and every session uses it at once. Turn off and Turn on run cmod disable and cmod enable, and Remove asks once, then runs cmod remove <mod>. Under cmod, the Log lists the newest 100 errors of your mods from every session, each with Copy and Report, and Preferences holds two switches: Ask before an update adds a permission and Show errors from installed mods.

An error of a mod you installed goes to the Log. A mod you run from its checkout, such as one you linked with cmod link, shows its errors as toasts, because you are its author, and a failed install or setup, a stopped program, or a failed button or hotkey shows a toast for every mod. An error for a permission you turned off goes only to the Log. When a mod needs something only you can give, such as a plugin it depends on, its message carries a button that takes you there.

Mods add widgets, such as the branch or a CI status. Settings, under cmod, Widgets, arranges every mod's widgets in rows: above the prompt, below it, under the spinner while Claude works, under each turn that ends, and on the Sidebar's Dashboard. Hide any widget there, Claude Code's own hint and mode labels below the prompt included. Claude Code always shows its permission mode. Every running session follows the layout at once.

When a cmod command, /plugin, claude plugin, or Claude Code's automatic update installs, updates, turns on or off, removes, links, or unlinks a plugin, every running session reloads its plugins by itself, once the changes have stopped for 2 seconds. A session in the middle of a turn reloads when the turn ends, and the prompt you are typing stays. When a plugin's version changed, a short toast in the corner says so, such as notes updated to 1.3.0. An update that added a permission always has its own toast, which names the permission. More than 3 others at once show as one toast, such as 5 plugins updated. A permission you change applies at once, with no reload.

A mod keeps itself up to date. Its setup turns on Claude Code's automatic updates for the marketplace it came from, unless you already chose, and the install question says so. Turn them off under /plugin Marketplaces. An update that changes what the mod runs asks you again before it runs.

When you remove a mod with /plugin uninstall, cmod runs the mod's uninstall step at the next session start or prompt. If Claude Code quits before the uninstall step finishes, the next session runs it again. If the uninstall step fails, a notice names the saved step to fix and the command that runs it again, cmod teardown <mod>. Once the uninstall step has run, every open session stops running the mod.

In a terminal, one command does the same, for a mod or any other Claude Code plugin:

cmod install <owner>/<repo>

A plugin that is not a mod installs through Claude Code alone, with no consent question. cmod update, cmod enable, cmod disable, and cmod remove work on any plugin the same way. The cmod plugin puts cmod in ~/.local/bin the first time it runs. A mod that ships a program, such as trace, runs it by its name in Claude Code even when your system has a command of the same name, and a mod built only for some machines says so before it runs anything. cmod list shows every plugin Claude Code has, and whether cmod set up each mod.

What the cmod plugin runs

The cmod plugin runs these programs, and sends no data anywhere:

  • setup/bootstrap.sh, the first time it runs. It runs the cmod launcher from the @cmodjs/cli package Claude Code installs with the plugin. The launcher downloads the cmod program for your machine from the GitHub release of this version at github.com/heyJordanParker/cmod, checks it against the release's SHA256SUMS, keeps it in ~/.local/share/cmod/bin/cmod/<version>/, and links ~/.local/share/cmod/programs/cmod and ~/.local/bin/cmod to it. It leaves a ~/.local/bin/cmod it did not make in place. That download is its only network request.
  • setup/path.sh, at each session start. It writes one line, once, to the file Claude Code reads into every Bash command's environment, export PATH="~/.local/share/cmod/programs:$PATH", so Claude runs each program a mod installs by its name.
  • cmod teardown <mod> --events, when you remove a mod. At each session start and prompt, the plugin reads enabledPlugins from your Claude Code user settings. For each mod that left the list, it runs cmod teardown, which runs the uninstall step you approved when you installed the mod.
  • cmod permission <mod> <name> [value] on|off, when you turn a permission on or off in Settings, cmod option <mod> <key> <value>, when you save a setting there, cmod hotkey <mod> <hotkey> <combo>, when you give a hotkey a new combo there, and cmod enable, cmod disable, and cmod remove with a mod's name, when you turn it on or off or remove it there.
  • cmod hotkey cmod sidebar meta+0 and cmod hotkey cmod settings meta+m, once, the first time the cmod plugin runs, to bind its own hotkeys.
  • cmod history index, in the background at each session start while a mod other than cmod holds the conversation permission. It reads your saved Claude Code conversations into an index on your machine, so a mod you granted "Read your Claude Code conversations" searches them at once. cmod history with a mod's question runs when that mod reads them, and cmod history follow runs while a mod listens to another running session.
  • cmod watch, only while a mod you linked with cmod link is linked. One of them watches your checkouts, and tells every session once a change builds. It skips files git ignores. A change that still doesn't build after 10 seconds shows its error in one toast.
  • cmod settings <mod> …, when a mod you granted "Change <setting> in your Claude Code settings" changes that setting.
  • cmod program <mod> -- <program> …, in each session of a mod that runs one copy of a program for the whole computer, a program you granted it to run. One session's cmod program runs the program, and the others wait to take over when that session ends.
  • cmod task start <prompt> --title <title>, when Claude's start_background_agent tool, or a mod you granted "Start tasks that work beside Claude", starts a task in a new background session. It runs claude --bg, and claude agents --json --all to find the new session.
  • /reload-plugins, in each session an app shows, whenever a plugin is installed, updated, turned on or off, removed, linked, or unlinked, by a cmod command, /plugin, claude plugin, or Claude Code's automatic update. A session in the middle of a turn runs it when the turn ends. The cmod plugin of each session watches ~/.local/share/cmod/store-changed, which each cmod command writes after it changes your plugins, and Claude Code's installed_plugins.json, and reads the enabledPlugins of your user settings each time Claude Code reports that file changed and at each prompt. The reload keeps the prompt cache.

A setting you change in Settings goes through cmod option to Claude Code's /config, the same place Claude Code keeps it when you change it there. The cmod plugin changes Claude Code's settings only for a mod that has your grant for each setting, keeps your own edits, and takes the mod's values out when you remove it.

It writes files in three places only. The first is the cmod store, ~/.local/share/cmod/, which holds the cmod program with its link at ~/.local/share/cmod/programs/cmod, the conversation index history-11.sqlite, the goals mods set in data/cmod/goals/, the record of the settings each mod changed in settings/, the address of each program a mod runs once for the whole computer in instances/, and the widget layout in widgets.json with the empty store-changed that tells every session it changed. The second is the link ~/.local/bin/cmod. The third is Claude Code's own storage for the plugin, where it keeps the list of mods it has seen. cmod setup and cmod hotkey also write each mod's hotkeys into Claude Code's ~/.claude/keybindings.json, and leave a combo you bound yourself in place.

Every mod built with cmod, the cmod plugin included, adds one hook on each Claude Code event a mod can use, and only a mod that decides permissions hooks Claude Code's permission check. So the cmod plugin hooks tool calls, prompts, and what Claude Code draws, and no permission check. On a tool call, the cmod plugin answers nothing of its own: it passes the event on unchanged. It never allows or denies a call, never rewrites a tool's input, and never changes a tool's output. It draws one line above the prompt while it downloads cmod, draws your mods' widgets where you placed them, and answers a call from one mod to another that names a mod you have not installed.

Change a mod

Your changes to a mod live in its config folders, outside the mod's code. Each mod has two:

~/.claude/cmods/<mod>/              yours, in every project
<project>/.claude/cmods/<mod>/      your team's, committed with the repository

A file in the project folder wins over the same file in yours. CLAUDE_CONFIG_DIR moves ~/.claude, and removing the mod keeps both folders.

A mod's options, such as a token or a branch to watch, are yours to set in /config. To set them for your whole team, commit an options.json in the project folder that lists only the options to change:

{ "branch": "release" }

The project's value wins over yours, and a value your organization set in managed settings wins over both. A secret never goes in the project file. The mod ignores an option it does not have and a value that does not fit, and logs one line naming the file, the option, and the fix. cmod reads the project's file when the mod starts, and again after a /cd.

To replace the text of a Skill a mod ships, put your own file at the same path in a config folder:

~/.claude/cmods/<mod>/skills/<skill>/SKILL.md

Claude reads your text in place of the mod's from the next time the Skill loads, and updates keep it. cmod drops the file's frontmatter, so the mod's own name and description stay. Delete the file to get the mod's text back.

Make a mod in 30 seconds

npm i -g @cmodjs/cli
cmod new my-mod
cd my-mod
cmod link

npm i -g @cmodjs/cli puts cmod on PATH, and bun add -g @cmodjs/cli does the same. bunx @cmodjs/cli new my-mod runs it once without installing. cmod new writes the mod and its CHANGELOG.md, and installs its packages. cmod link loads it in every Claude Code session, the running ones too. The mod lives in src/:

src/
├── mod.tsx                     defineMod, its hotkeys, and setup: the page, the widget, the listeners
├── state.ts                    the starting state, grouped by how long it lasts
├── pages/
│   └── prompts.tsx             one Sidebar page per file
├── widgets/
│   └── prompts.tsx             one widget per file
└── components/
    └── prompt-count.tsx        what the page and the widget draw with

src/mod.tsx adds each part with one line, and the hotkey shows or hides the page:

import { defineMod, sessions } from '../node_modules/@cmodjs/core/mod.js'
import { promptsPage } from './pages/prompts.js'
import { initialState } from './state.js'
import { promptsWidget } from './widgets/prompts.js'

export const myMod = defineMod({
  name: 'my-mod',
  state: initialState,
  hotkeys: {
    toggle: { title: 'Show or hide the prompt count', default: 'alt+shift+p' },
  },

  setup(mod) {
    const page = mod.sidebar.add(promptsPage)
    mod.widgets.add(promptsWidget)
    mod.hotkeys.toggle.onPress(() => page.toggle())

    sessions.current.onPrompt(() => {
      mod.state.session.prompts += 1
    })
  },
})

src/state.ts holds the starting state:

export type MyModState = { session: { prompts: number } }

export const initialState: MyModState = { session: { prompts: 0 } }

src/pages/prompts.tsx is the mod's Sidebar page:

export const promptsPage: PageInit<MyModState> = {
  id: 'prompts',
  title: 'Prompts',
  render: (mod) => <PromptCount count={mod.state.session.prompts} />,
}

src/widgets/prompts.tsx is the mod's widget. It first draws below the prompt, and the person can move it to the Dashboard:

export const promptsWidget: WidgetInit<MyModState> = {
  id: 'prompts',
  title: 'Prompt count',
  areas: [BelowPrompt, Dashboard],
  render: (mod) => <PromptCount count={mod.state.session.prompts} />,
}

src/components/prompt-count.tsx is what the page and the widget draw:

export function PromptCount({ count }: { readonly count: number }): RenderElement {
  return <Text>{`Prompts this session: ${count}`}</Text>
}

Start claude, and the mod counts every prompt. alt+shift+p shows the count in the Sidebar. cmod check writes the hotkeys and options defineMod declares into the manifests, then checks the layout, the imports, and the lint, validates the mod with Claude Code, compiles it against Claude Code's API, and runs its tests. A fresh clone has no .claude-plugin/types/, Claude Code's description of its API, so cmod check has Claude Code write it before compiling. cmod publish releases the mod on GitHub, and prints the link that lists it in Anthropic's plugin directory.

Docs

The mod author docs live in core/docs/ and ship inside @cmodjs/core. So every mod's node_modules/@cmodjs/core/docs/ holds the docs of the version it installed. The .claude/CLAUDE.md that cmod new writes points coding agents there. A project plugin, made with cmod new --project, gets no .claude/CLAUDE.md.

  • index.md: what a mod is, and which file answers which question
  • mod.md: defineMod, setup, what mod can call, and the imports, commands and config included
  • state.md: state groups and Skill overrides
  • options.md: options a person sets, typed in code, stored by Claude Code
  • permissions.md: the hosts, programs, and files a mod may reach, granted by the person
  • session.md: sessions, the conversation as contexts, turns, messages, a goal, and tasks, and every on and before method
  • ui.md: the Sidebar and its pages, Settings pages, panes, widgets, styles, markdown blocks, elements, the button rule, toasts, questions, and the conversation's rows
  • jobs.md: slash commands, tools, permission rules, checks, prompts, schedules, and programs
  • dependencies.md: calling another mod
  • install-steps.md: install and uninstall steps, and shipping a program
  • testing.md: testMod
  • commands.md: every cmod command

What is in this repository

  • The root is the cmod plugin. It fetches the cmod program, runs the uninstall step of each mod Claude Code removes, and carries calls from one mod to another.
  • core/ is @cmodjs/core on npm, the library every mod imports, with its docs in core/docs/.
  • cli/ is @cmodjs/cli on npm, the cmod command, which runs the newest cmod program. It also holds the source of the cmod program, which each GitHub release carries for macOS and Linux.
  • CONTRIBUTING.md runs cmod from a checkout, runs the gate, and releases.

License

MIT. See LICENSE.

Source 6 files
hooks/register.ts 19 lines
1import type { On, PluginOptions } from 'claude-code'
2import { notInstalled } from '../node_modules/@cmodjs/core/mod.js'
3import { registerMod } from '../node_modules/@cmodjs/core/register.js'
4import { cmodPlugin } from '../src/mod.js'
5import type { Cmod } from '../types/index.js'
6
7export function register(addHook: On, options: PluginOptions): void {
8  addHook('engine.create', async (_$, eventInput, passOn) => {
9    const built = await passOn(eventInput)
10    const cmod: Cmod = {
11      async call(input) {
12        return { deny: notInstalled(input.to) }
13      },
14    }
15    return { ...built, cmod }
16  })
17  registerMod(addHook, cmodPlugin, options)
18}
19
src/mod.ts 401 lines
1import { slashCommand } from '../node_modules/@cmodjs/core/jobs/slash-command.js'
2import { defineMod, fs, longestMs, messageOf, process, sessions, settings, type Mod, type Timer } from '../node_modules/@cmodjs/core/mod.js'
3import { buildFailuresPath, hasLinkedMods, linksPath, parseEvent, parseLinks, permissionWords, pluginsChangedPath, readRecord, storeChangedPath } from '../node_modules/@cmodjs/core/records.js'
4import { engineOf } from '../node_modules/@cmodjs/core/runtime/engine.js'
5import { failedMethod } from '../node_modules/@cmodjs/core/runtime/toaster.js'
6import { cmodError, runCmod } from '../node_modules/@cmodjs/core/runtime/programs.js'
7import { ifMissing } from '../node_modules/@cmodjs/core/utils/paths.js'
8import { formatExit } from '../node_modules/@cmodjs/core/utils/text.js'
9import { sessionsWith } from '../node_modules/@cmodjs/core/runtime/state.js'
10import { configRootOf, failureLog, readConsent, readJson, refreshPreferences, settings as settingsView, settingsMemory, settingsSession, storeOf, type SettingsState } from './settings.js'
11import { sidebar, sidebarSession, type SidebarState } from './sidebar.js'
12import { addClaudeTools } from './tools.js'
13
14export type CmodPluginState = {
15  readonly global: { installedPlugins: readonly string[] | null; areHotkeysBound: boolean; pluginsCheckedAt: number | null }
16  readonly session: { tip: string | null } & SidebarState['session'] & SettingsState['session']
17  readonly memory: SettingsState['memory']
18}
19
20const cmodGlobal: CmodPluginState['global'] = { installedPlugins: null, areHotkeysBound: false, pluginsCheckedAt: null }
21
22type Listed = { readonly name: string; readonly version: string; readonly state: string; readonly unsatisfied: readonly string[] }
23
24const cmodSession: CmodPluginState['session'] = { tip: null, ...sidebarSession, ...settingsSession }
25
26type InstalledCopy = { readonly version: string; readonly projectPath?: string }
27
28type Versions = Readonly<Record<string, string>>
29
30const newestMessages = 8
31
32const reloadDelayMs = 500
33
34const changesQuietMs = 2000
35
36const watchCheckMs = 10_000
37
38const watchStaleMs = 15_000
39
40const reloadEcho = '<command-name>/reload-plugins</command-name>'
41
42const reloadNote = '<local-command-caveat>cmod reloaded the plugins.</local-command-caveat>'
43
44const reloadToast = 'reload'
45
46const shownUpdates = 3
47
48const setupWaitMs = 10_000
49
50const recordCheckMs = 500
51
52type SyncedRules = {
53  readonly linked: readonly { readonly mod: string; readonly rules: readonly { readonly name: string; readonly isGlobal: boolean; readonly text: string }[] }[]
54  readonly placed: readonly string[]
55  readonly removed: readonly string[]
56  readonly watched: readonly string[]
57}
58
59async function tipOf(mod: Mod<CmodPluginState>): Promise<string | null> {
60  const messages = await engineOf(mod).claude.session.messages()
61  if (messages.length === 0) return null
62  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([messages.length, messages.slice(-newestMessages)])))
63  return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')
64}
65
66export const cmodPlugin = defineMod({
67  name: 'cmod',
68  state: { global: cmodGlobal, session: cmodSession, memory: settingsMemory },
69  hotkeys: {
70    sidebar: { title: 'Show or hide the Sidebar', default: 'meta+0' },
71    settings: { title: 'Show or hide Settings', default: 'meta+m' },
72  },
73
74  async setup(mod) {
75    const triedRemovals = new Set<string>()
76    const { claude, router, report, widgets } = engineOf(mod)
77    if (widgets === undefined) throw new Error('cmod draws no widgets, because the cmod plugin started without them.')
78
79    addClaudeTools(mod)
80    const shown = sidebar(mod, settingsView(mod))
81    mod.hotkeys.sidebar.onPress(() => shown.toggle())
82    mod.hotkeys.settings.onPress(() => shown.toggleSettings())
83
84    mod.use(
85      slashCommand({
86        name: 'mods',
87        description: 'Open Settings, where you turn your mods off or remove them, and change their options, permissions, hotkeys, pages, and widgets',
88        argumentHint: '[mod]',
89        immediate: true,
90        reply: ({ positionals }) => shown.openSettings(positionals[0]),
91      }),
92    )
93
94    const bindHotkeys = async () => {
95      let isBound = true
96      for (const [name, hotkey] of Object.entries(cmodPlugin.hotkeys ?? {})) {
97        if (mod.hotkeys[name as keyof typeof mod.hotkeys].combo !== undefined) continue
98        const { exitCode, stderr } = await process.run(['cmod', 'hotkey', mod.name, name, hotkey.default])
99        if (exitCode === 0) continue
100        isBound = false
101        report({ id: `hotkey:${name}`, message: `Could not bind ${hotkey.default} to ${hotkey.title}`, description: `cmod hotkey ${formatExit(exitCode, cmodError(stderr, 'hotkey'))}` })
102      }
103      mod.state.global.areHotkeysBound = isBound
104    }
105    if (!mod.state.global.areHotkeysBound) void bindHotkeys().catch((error: unknown) => report({ id: 'hotkeys', message: 'Could not bind the hotkeys', error }))
106
107    const store = await storeOf(mod)
108    const changed = pluginsChangedPath(store)
109    const configRoot = await configRootOf(mod)
110    const pluginsFile = configRoot === undefined ? undefined : `${configRoot}/plugins/installed_plugins.json`
111    const pluginsState = async () =>
112      JSON.stringify([
113        await fs.read(changed).catch(ifMissing('')),
114        pluginsFile === undefined ? '' : await fs.read(pluginsFile).catch(ifMissing('')),
115        (await settings.user.read())['enabledPlugins'] ?? null,
116      ])
117    const sessionKey = async (name: string) => `cmod:${name}:${await claude.session.id()}`
118    const loadedVersions = async (): Promise<Versions> => {
119      if (pluginsFile === undefined) return {}
120      const installed = JSON.parse(await fs.read(pluginsFile).catch(ifMissing('{}'))) as { readonly plugins?: Readonly<Record<string, readonly InstalledCopy[]>> }
121      const enabled = (await claude.settings.read())['enabledPlugins'] as Readonly<Record<string, unknown>> | undefined
122      const root = await claude.session.root()
123      return Object.fromEntries(
124        Object.entries(installed.plugins ?? {}).flatMap(([id, copies]) => {
125          const loaded = copies.find((copy) => copy.projectPath === root) ?? copies.find((copy) => copy.projectPath === undefined)
126          return enabled?.[id] === true && loaded !== undefined ? [[id, loaded.version]] : []
127        }),
128      )
129    }
130    const grantedWords = async (name: string, version: string): Promise<string[]> => {
131      for (let waitedMs = 0; ; waitedMs += recordCheckMs) {
132        const record = await readRecord((path) => fs.read(path).catch(ifMissing(undefined)), store, name)
133        if (record?.version === version) return record.grantedOnUpdate.map(permissionWords)
134        if (record === undefined || waitedMs >= setupWaitMs) return []
135        await new Promise<void>((resolve) => mod.after(recordCheckMs, resolve))
136      }
137    }
138    let loaded: Versions = {}
139    const takeVersionsBeforeReload = async () => {
140      const key = await sessionKey('versions-before-reload')
141      const before = (await claude.store.get(key)) as Versions | undefined
142      await claude.store.delete(key)
143      return before
144    }
145    const showUpdates = async (isAfterOwnReload: boolean) => {
146      const before = await takeVersionsBeforeReload()
147      loaded = await loadedVersions()
148      if (!isAfterOwnReload || before === undefined) return
149      const updates = await Promise.all(
150        Object.entries(loaded)
151          .filter(([id, version]) => before[id] !== undefined && before[id] !== version)
152          .map(async ([id, version]) => {
153            const name = id.replace(/@[^@]*$/, '')
154            return { line: `${name} updated to ${version}`, words: await grantedWords(name, version) }
155          }),
156      )
157      const rest = updates.filter(({ words }) => words.length === 0)
158      for (const { line, words } of updates) if (words.length > 0) claude.ui.toast([line, ...words].join(' · '))
159      if (rest.length > shownUpdates) claude.ui.toast(`${rest.length} plugins updated`)
160      else for (const { line } of rest) claude.ui.toast(line)
161    }
162    const announceUpdates = (isAfterOwnReload: boolean) => void showUpdates(isAfterOwnReload).catch((error: unknown) => report({ id: 'updates', message: 'Could not show which plugins updated', error }))
163    announceUpdates((await claude.store.get(await sessionKey('hiding-reload'))) === true)
164
165    let seenChange = await pluginsState()
166    let isReloadDue = false
167    let quietWait: Timer | undefined
168    const reloadAfter = (ms: number) => {
169      quietWait?.stop()
170      quietWait = mod.after(ms, reloadWhenIdle)
171    }
172    let reloading = Promise.resolve()
173    const reloadWhenIdle = () => {
174      reloading = reloading
175        .then(async () => {
176          if (!isReloadDue || (await sessions.current.turn()) !== undefined) return
177          isReloadDue = false
178          await reload()
179        })
180        .catch((error: unknown) => report({ id: reloadToast, message: 'Could not tell whether a turn runs, so the plugins did not reload', error, retry: reload, isCritical: true }))
181    }
182    const reloadIfChanged = async () => {
183      const change = await pluginsState()
184      if (change === seenChange) return
185      seenChange = change
186      if ((await claude.session.surfaces()).length === 0) return
187      isReloadDue = true
188      reloadAfter(changesQuietMs)
189    }
190    const reload = async () => {
191      mod.toast.dismiss(reloadToast)
192      try {
193        seenChange = await pluginsState()
194        await claude.store.set(await sessionKey('versions-before-reload'), loaded)
195        await claude.store.set(await sessionKey('hiding-reload'), true)
196        await claude.command.run({ command: 'reload-plugins' })
197        await widgets.recheck()
198        announceUpdates(true)
199      } catch (error) {
200        await claude.store.delete(await sessionKey('hiding-reload'))
201        await takeVersionsBeforeReload()
202        report({ id: reloadToast, message: 'Could not reload the plugins', error, retry: reload, isCritical: true })
203      }
204    }
205    sessions.current.onTurnEnd(() => {
206      if (isReloadDue && quietWait?.isRunning !== true) reloadAfter(reloadDelayMs)
207    })
208    router.add('session.append', async (e, next) => {
209      if (e.door !== 'command' || e.message.isMeta === true) return next(e)
210      const hidingReload = await sessionKey('hiding-reload')
211      if ((await claude.store.get(hidingReload)) !== true) return next(e)
212      const isOwnReload = e.origin.kind === 'plugin' && 'name' in e.origin && e.origin.name === mod.name && JSON.stringify(e.message.content).includes(reloadEcho)
213      if (!isOwnReload) {
214        await claude.store.delete(hidingReload)
215        if (e.message.type !== 'system') return next(e)
216      }
217      return next({ ...e, message: { ...e.message, content: [{ type: 'text', text: reloadNote }] } })
218    })
219
220    const isCmod = (id: string) => id.replace(/@[^@]*$/, '') === mod.name
221    const updatedFor = 'cmod:cmod-updated-for'
222    let isCheckingPlugins = false
223    const modifiedAt = async (path: string) => (await claude.fs.stat(path).catch(ifMissing(undefined)))?.mtimeMs ?? null
224    const keepCmodCurrent = async (): Promise<void> => {
225      if (pluginsFile === undefined || isCheckingPlugins) return
226      const at = await modifiedAt(pluginsFile)
227      if (at === null || at === mod.state.global.pluginsCheckedAt) return
228      isCheckingPlugins = true
229      let checked: number | null = at
230      try {
231        const session = await claude.session.id()
232        const listed = async () => JSON.parse(await runCmod(claude, ['list', '--json'], session)) as readonly Listed[]
233        const needing = (rows: readonly Listed[]) => rows.filter((row) => row.unsatisfied.some(isCmod))
234        const before = await listed()
235        const copies = new Set(before.filter((row) => isCmod(row.name)).map((row) => row.version))
236        let off = needing(before)
237        const reason = off.length > 0 || copies.size > 1 ? JSON.stringify([off.map((row) => row.name).toSorted(), [...copies].toSorted()]) : ''
238        if (reason !== '' && reason !== (await claude.store.get(updatedFor))) {
239          await claude.store.set(updatedFor, reason)
240          await runCmod(claude, ['update', mod.name], session)
241          checked = await modifiedAt(pluginsFile)
242          off = needing(await listed())
243        }
244        if (reason === '') await claude.store.delete(updatedFor)
245        if (off.length > 0) report({ id: 'needs-cmod', message: `${off.map((row) => row.name).join(', ')} ${off.length === 1 ? 'is' : 'are'} off`, description: off.map((row) => row.state).join('\n'), retry: updateAgain, isCritical: true })
246        else mod.toast.dismiss('needs-cmod')
247        mod.state.global.pluginsCheckedAt = checked
248      } finally {
249        isCheckingPlugins = false
250      }
251      if ((await modifiedAt(pluginsFile)) !== checked) await keepCmodCurrent()
252    }
253    const checkPlugins = () => void keepCmodCurrent().catch((error: unknown) => report({ id: 'needs-cmod', message: 'Could not update cmod for the mods that need a newer one', error, retry: updateAgain, isCritical: true }))
254    const updateAgain = async () => {
255      await claude.store.delete(updatedFor)
256      mod.state.global.pluginsCheckedAt = null
257      checkPlugins()
258    }
259    checkPlugins()
260
261    const failuresFile = buildFailuresPath(store)
262    let shownFailures: readonly string[] = []
263    const showBuildFailures = async () => {
264      const failures = JSON.parse(await fs.read(failuresFile).catch(ifMissing('{}'))) as Record<string, string>
265      for (const name of shownFailures) if (!Object.hasOwn(failures, name)) mod.toast.dismiss(`build:${name}`)
266      for (const [name, error] of Object.entries(failures)) report({ id: `build:${name}`, message: `${name} does not build`, description: error, isCritical: true })
267      shownFailures = Object.keys(failures)
268    }
269    const followBuildFailures = () => showBuildFailures().catch((error: unknown) => report({ id: 'build-failures', message: 'Could not read which linked mods fail to build', error, isCritical: true }))
270    void followBuildFailures()
271    const watchLock = `${store}/watch.lock`
272    let isWatchRunning = false
273    const keepWatching = async () => {
274      if (isWatchRunning) return
275      const now = await claude.clock.now()
276      const holders = await claude.fs.list(watchLock).catch(ifMissing([]))
277      const touched = await Promise.all(holders.map(async ({ name }) => (await claude.fs.stat(`${watchLock}/${name}`).catch(ifMissing(undefined)))?.mtimeMs ?? 0))
278      if (touched.some((at) => now - at < watchStaleMs)) return
279      isWatchRunning = true
280      void runCmod(claude, ['watch'], await claude.session.id())
281        .catch((error: unknown) => report({ id: 'watch', message: 'Stopped reloading the linked mods', error, isCritical: true }))
282        .finally(() => void (isWatchRunning = false))
283    }
284    const linksFile = linksPath(store)
285    const knownMarketplaces = configRoot === undefined ? undefined : `${configRoot}/plugins/known_marketplaces.json`
286    let isWatching = false
287    const watchIfLinked = async () => {
288      if (isWatching || knownMarketplaces === undefined || (await claude.session.surfaces()).length === 0) return
289      if (!hasLinkedMods(await readJson(knownMarketplaces), parseLinks(await readJson(linksFile), linksFile))) return
290      isWatching = true
291      const watchAgain = () => void keepWatching().catch((error: unknown) => report({ id: 'watch', message: 'Could not check that a cmod watch runs', error }))
292      watchAgain()
293      claude.clock.every(watchCheckMs, watchAgain)
294    }
295    const startWatching = () => void watchIfLinked().catch((error: unknown) => report({ id: 'watch', message: 'Could not read which mods are linked', error }))
296    startWatching()
297
298    fs.onChange({ path: [storeChangedPath(store), ...(pluginsFile === undefined ? [] : [pluginsFile])] }, ({ path }) => {
299      startWatching()
300      if (path === pluginsFile) {
301        checkPlugins()
302        return reloadIfChanged()
303      }
304      void followBuildFailures()
305      return Promise.all([widgets.reload(), reloadIfChanged(), refreshPreferences(mod)])
306    })
307    settings.beforeFileChange({ source: 'user' }, () => void mod.after(reloadDelayMs, reloadIfChanged))
308    sessions.current.onPrompt(() => reloadIfChanged())
309
310    void readConsent(mod)
311      .then(async (consent) => (Object.entries(consent).some(([name, granted]) => name !== mod.name && granted.includes('conversation')) ? runCmod(claude, ['history', 'index'], await claude.session.id()) : undefined))
312      .catch((error: unknown) => mod.log(messageOf(error)))
313
314    const tearDown = async (name: string) => {
315      const { exitCode, stdout, stderr } = await process.run(['cmod', 'teardown', name, '--events'], { timeoutMs: longestMs })
316      const outcome = parseEvent(stdout.trim().split('\n').at(-1) ?? '')
317      const isAnswered = outcome.type === 'done' || outcome.type === 'missing' || outcome.type === 'failed'
318      if (isAnswered) mod.state.global.installedPlugins = (mod.state.global.installedPlugins ?? []).filter((installed) => installed !== name)
319      if (outcome.type === 'done') mod.toast.success(`${name} is uninstalled`)
320      else if (outcome.type === 'failed') report({ id: `teardown:${name}`, message: `Could not uninstall ${name}`, description: outcome.message, isCritical: true })
321      else if (exitCode !== 0) report({ id: `teardown:${name}`, message: `Could not uninstall ${name}`, description: `cmod teardown ${formatExit(exitCode, cmodError(stderr, 'teardown'))}`, isCritical: true })
322    }
323
324    const watchRemovals = async () => {
325      const enabledPlugins = (await settings.user.read())['enabledPlugins'] as Record<string, unknown> | undefined
326      const current = [...new Set(Object.keys(enabledPlugins ?? {}).map((key) => key.replace(/@[^@]*$/, '')))]
327      const previous = mod.state.global.installedPlugins
328      const removed = (previous ?? []).filter((name) => !current.includes(name))
329      const installed = [...current, ...removed]
330      if (previous === null || previous.length !== installed.length || !installed.every((name) => previous.includes(name))) mod.state.global.installedPlugins = installed
331      for (const name of removed) {
332        if (triedRemovals.has(name)) continue
333        triedRemovals.add(name)
334        void tearDown(name).catch((error: unknown) => report({ id: `teardown:${name}`, message: `Could not uninstall ${name}`, error, isCritical: true }))
335      }
336    }
337
338    sessions.current.onSessionStart(watchRemovals)
339    sessions.current.onPrompt(watchRemovals)
340
341    let applied: ReadonlyMap<string, ReadonlyMap<string, string>> | undefined
342    let following = Promise.resolve()
343    let synced: { readonly project: string; readonly watched: readonly string[]; readonly stamp: string } | undefined
344    const changedAt = async (paths: readonly string[]) => Promise.all(paths.map(async (path) => (await claude.fs.stat(path).catch(ifMissing(undefined)))?.mtimeMs ?? 0))
345    const followRules = async (): Promise<string[]> => {
346      const project = await claude.session.root()
347      if (synced?.project === project && (await changedAt(synced.watched)).join(',') === synced.stamp) return []
348      const startedAt = await claude.clock.now()
349      const result = JSON.parse(await runCmod(claude, ['rules', '--project', project, '--json'], await claude.session.id())) as SyncedRules
350      const times = await changedAt(result.watched)
351      synced = { project, watched: result.watched, stamp: times.some((at) => at >= startedAt - 1000) ? '' : times.join(',') }
352      return rulesNotes(result)
353    }
354    const rulesNotes = (result: SyncedRules): string[] => {
355      const now = new Map(result.linked.map(({ mod: name, rules }) => [name, new Map(rules.filter((rule) => rule.isGlobal).map((rule) => [rule.name, rule.text]))]))
356      const notes = [...now].flatMap(([name, globals]) => {
357        const before = applied === undefined ? (result.placed.includes(name) ? undefined : globals) : applied.get(name)
358        const changed = [...globals].filter(([rule, text]) => before?.get(rule) !== text).map(([, text]) => text)
359        const withdrawn = [...(before ?? [])].filter(([rule]) => !globals.has(rule)).map(([, text]) => text)
360        return [
361          ...(changed.length === 0 ? [] : [[before === undefined ? `The ${name} mod adds these rules from now on:` : `The ${name} mod changed these rules, which apply from now on:`, ...changed].join('\n\n')]),
362          ...(withdrawn.length === 0 ? [] : [[`These rules of the ${name} mod no longer apply:`, ...withdrawn].join('\n\n')]),
363        ]
364      })
365      const gone = applied === undefined ? result.removed : [...applied.keys()].filter((name) => !now.has(name))
366      applied = now
367      return [...notes, ...gone.map((name) => `The ${name} mod's rules no longer apply.`)]
368    }
369    const keepRules = async (): Promise<readonly string[]> => {
370      let notes: readonly string[] = []
371      following = following.then(async () => void (notes = await followRules())).catch((error: unknown) => report({ id: 'rules', message: "Could not link the mods' rules", error }))
372      await following
373      return notes
374    }
375    const rulesNote = async () => {
376      const notes = await keepRules()
377      return notes.length === 0 ? undefined : { note: notes.join('\n\n') }
378    }
379    sessions.current.beforeSessionStart(rulesNote)
380    sessions.current.beforePrompt(rulesNote, { timeoutMs: 60_000 })
381
382    sessions.current.onTurnEnd(async () => {
383      mod.state.session.tip = await tipOf(mod)
384    })
385
386    return {
387      async forkParent() {
388        const tip = await tipOf(mod)
389        if (tip === null) return null
390        const current = await claude.session.id()
391        return (await sessionsWith(claude, mod.name, 'tip', tip)).find((session) => session !== current) ?? null
392      },
393      async updateSettings(input: { readonly mod: string; readonly source: string; readonly project: string; readonly values: Readonly<Record<string, unknown>> }) {
394        await runCmod(claude, ['settings', input.mod, input.source, JSON.stringify(input.values), '--project', input.project], await claude.session.id())
395        return null
396      },
397      [failedMethod]: failureLog(mod),
398    }
399  },
400})
401
src/settings.ts 574 lines
1import type { ConfigRow, RenderElement } from 'claude-code'
2import { AbovePrompt, BelowPrompt, clipboard, Dashboard, fs, longestMs, messageOf, process, TurnEnd, Working, type Area, type Mod, type Pane } from '../node_modules/@cmodjs/core/mod.js'
3import { consentPath, finishStepsMethod, hotkeyCommand, isObject, marketplaceOf, parseConsent, parsePreferences, pendingStepsMethod, permissionWords, preferencesPath, readRecord, readSteps, storeChangedPath, storeFolder, type Preferences } from '../node_modules/@cmodjs/core/records.js'
4import { filledButton } from '../node_modules/@cmodjs/core/runtime/buttons.js'
5import { engineOf } from '../node_modules/@cmodjs/core/runtime/engine.js'
6import { readCombos } from '../node_modules/@cmodjs/core/runtime/hotkeys.js'
7import { cmodError } from '../node_modules/@cmodjs/core/runtime/programs.js'
8import { failedMethod, reportLink, reportPrompt, type LoggedFailure } from '../node_modules/@cmodjs/core/runtime/toaster.js'
9import { builtInWidgets, moved, placedIn, toggled, type Move, type PlacedWidget, type Widgets } from '../node_modules/@cmodjs/core/runtime/widgets.js'
10import { areas } from '../node_modules/@cmodjs/core/ui/areas.js'
11import { Panel } from '../node_modules/@cmodjs/core/ui/components.js'
12import { Box, Button, Input, Markdown, Text } from '../node_modules/@cmodjs/core/ui/elements.js'
13import { changelogSections, unreleased, type ChangelogSection } from '../node_modules/@cmodjs/core/utils/changelog.js'
14import { ifMissing } from '../node_modules/@cmodjs/core/utils/paths.js'
15import { formatExit } from '../node_modules/@cmodjs/core/utils/text.js'
16import type { SettingsView } from './sidebar.js'
17
18export type SettingsState = {
19  readonly memory: { removing: string | null; views: readonly ModView[]; log: readonly LogEntry[]; reporting: string | null; preferences: Preferences }
20  readonly session: { selected: string | null; section: string; pageParams: unknown; notice: string | null; widget: string | null }
21}
22
23export const settingsMemory: SettingsState['memory'] = { removing: null, views: [], log: [], reporting: null, preferences: parsePreferences(undefined, 'preferences.json') }
24
25export const settingsSession: SettingsState['session'] = { selected: null, section: 'options', pageParams: null, notice: null, widget: null }
26
27const areaTitles: Readonly<Record<Area, string>> = {
28  [AbovePrompt]: 'Above the prompt',
29  [BelowPrompt]: 'Below the prompt',
30  [Working]: 'While Claude works',
31  [TurnEnd]: 'When a turn ends',
32  [Dashboard]: 'On the Dashboard, in the Sidebar',
33}
34
35const moves: readonly { readonly move: Move; readonly hotkey: string; readonly label: string }[] = [
36  { move: 'left', hotkey: 'h', label: '← left' },
37  { move: 'down', hotkey: 'j', label: '↓ down' },
38  { move: 'up', hotkey: 'k', label: '↑ up' },
39  { move: 'right', hotkey: 'l', label: '→ right' },
40]
41
42type Permission = { readonly item: string; readonly isOn: boolean }
43
44type HotkeyView = { readonly name: string; readonly title: string; readonly combo: string | undefined }
45
46export type ModView = {
47  readonly name: string
48  readonly version: string
49  readonly description: string | undefined
50  readonly isOn: boolean
51  readonly permissions: readonly Permission[]
52  readonly hotkeys: readonly HotkeyView[]
53  readonly options: readonly ConfigRow[]
54  readonly pendingSteps: readonly string[]
55  readonly changelog: readonly ChangelogSection[]
56}
57
58type LogEntry = Omit<LoggedFailure, 'isCritical' | 'root'>
59
60const loggedFailures = 100
61
62const preferenceTitles: Readonly<Record<keyof Preferences, string>> = {
63  asksBeforeUpdatePermissions: 'Ask before an update adds a permission',
64  showsInstalledModErrors: 'Show errors from installed mods',
65}
66
67const pageSection = 'page:'
68
69const selectedColor = 'userMessageBackground'
70
71const statusColumns = 2
72
73const rowPadding = 2
74
75const panelColumns = 4
76
77const detailMinColumns = 40
78
79export async function storeOf(mod: object): Promise<string> {
80  const { claude } = engineOf(mod)
81  return storeFolder({ HOME: await claude.env.home(), XDG_DATA_HOME: await claude.env.dataHome() })
82}
83
84export async function readConsent<State extends object>(mod: Mod<State>): Promise<ReturnType<typeof parseConsent>> {
85  const path = consentPath(await storeOf(mod))
86  return (await fs.exists(path)) ? parseConsent(JSON.parse(await fs.read(path)), path) : {}
87}
88
89export async function configRootOf(mod: object): Promise<string | undefined> {
90  const { claude } = engineOf(mod)
91  const [configHome, home] = await Promise.all([claude.env.configHome(), claude.env.home()])
92  return configHome ?? (home === undefined ? undefined : `${home}/.claude`)
93}
94
95export async function readJson(path: string): Promise<unknown> {
96  const text = await fs.read(path).catch(ifMissing(undefined))
97  return text === undefined ? undefined : JSON.parse(text)
98}
99
100const isText = (value: unknown) => typeof value === 'string'
101
102const isLogEntry = (value: unknown): value is LogEntry => isObject(value) && ['mod', 'id', 'message', 'details', 'at'].every((key) => isText(value[key]))
103
104const sameFailure = (left: LogEntry) => (right: LogEntry) => left.mod === right.mod && left.id === right.id
105
106async function readEntries(path: string): Promise<LogEntry[]> {
107  const value = await readJson(path).catch((error: unknown) => {
108    throw new Error(`${path} is not JSON (${messageOf(error)}). Delete it, and cmod starts it again.`)
109  })
110  if (value === undefined) return []
111  if (!Array.isArray(value) || !value.every(isLogEntry)) throw new Error(`${path} is not a list of mod failures. Delete it, and cmod starts it again.`)
112  return value
113}
114
115const logFolder = (mod: Mod<object>) => `${mod.dataFolder}/log`
116
117export async function readLog(mod: Mod<object>): Promise<LogEntry[]> {
118  const folder = logFolder(mod)
119  const files = (await fs.list(folder).catch(ifMissing([]))).filter((file) => file.isFile && file.name.endsWith('.json')).toSorted((left, right) => right.modifiedAt - left.modifiedAt)
120  const newest = new Map<string, LogEntry>()
121  const newestFirst = () => [...newest.values()].toSorted((left, right) => right.at.localeCompare(left.at))
122  for (const file of files) {
123    const oldestKept = newestFirst()[loggedFailures - 1]
124    if (oldestKept !== undefined && Date.parse(oldestKept.at) > file.modifiedAt) break
125    const entries = await readEntries(`${folder}/${file.name}`).catch((error: unknown) => {
126      mod.log(`the Log skips a file: ${messageOf(error)}`)
127      return []
128    })
129    for (const entry of entries) {
130      const key = `${entry.mod}\n${entry.id}`
131      if ((newest.get(key)?.at ?? '') < entry.at) newest.set(key, entry)
132    }
133  }
134  return newestFirst().slice(0, loggedFailures)
135}
136
137async function readPreferences(mod: Mod<object>): Promise<Preferences> {
138  const path = preferencesPath(await storeOf(mod))
139  return parsePreferences(await readJson(path), path)
140}
141
142export async function refreshPreferences<State extends SettingsState>(mod: Mod<State>): Promise<void> {
143  mod.state.memory.preferences = await readPreferences(mod)
144}
145
146export function failureLog<State extends SettingsState>(mod: Mod<State>): (failure: LoggedFailure) => Promise<{ readonly showsToast: boolean }> {
147  let writing: Promise<unknown> = Promise.resolve()
148  const add = async (entry: LogEntry) => {
149    const path = `${logFolder(mod)}/${await engineOf(mod).claude.session.id()}.json`
150    const kept = [entry, ...(await readEntries(path)).filter((each) => !sameFailure(entry)(each))].slice(0, loggedFailures)
151    await fs.write(path, `${JSON.stringify(kept, null, 2)}\n`)
152    mod.state.memory.log = [entry, ...mod.state.memory.log.filter((each) => !sameFailure(entry)(each))].slice(0, loggedFailures)
153  }
154  return async (failure) => {
155    if (!isLogEntry(failure) || !isText(failure.root) || typeof failure.isCritical !== 'boolean') throw new Error(`${failedMethod} takes the failure's mod, id, message, details, at, and root as text, and isCritical as true or false.`)
156    const { mod: name, id, message, details, at, contact } = failure
157    const added = writing.then(() => add({ mod: name, id, message, details, at, ...(contact === undefined ? {} : { contact }) }))
158    writing = Promise.allSettled([added])
159    await added
160    return { showsToast: failure.isCritical || marketplaceOf(failure.root, failure.mod) === undefined || (await readPreferences(mod)).showsInstalledModErrors }
161  }
162}
163
164async function writePreference(mod: Mod<object>, key: keyof Preferences, isOn: boolean): Promise<void> {
165  const store = await storeOf(mod)
166  const path = preferencesPath(store)
167  const saved = await readJson(path)
168  parsePreferences(saved, path)
169  await fs.write(path, `${JSON.stringify({ ...(isObject(saved) ? saved : {}), [key]: isOn }, null, 2)}\n`)
170  await fs.write(storeChangedPath(store), '')
171}
172
173function timeOf(at: string): string {
174  const date = new Date(at)
175  const two = (value: number) => String(value).padStart(2, '0')
176  return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} ${two(date.getHours())}:${two(date.getMinutes())}`
177}
178
179function widgetsLayout<State extends SettingsState>(current: Mod<State>, widgets: Widgets): RenderElement {
180  const widgetFor = (key: string, area: Area): PlacedWidget => widgets.widgets().find((widget) => widget.key === key) ?? { key, mod: key.slice(0, key.indexOf('/')), title: key, areas: [area] }
181  const chip = (key: string, area: Area) => {
182    const widget = widgetFor(key, area)
183    const isRunning = widgets.widgets().some((each) => each.key === key)
184    const isHidden = widgets.layout().hidden.includes(widget.key)
185    const isSelected = current.state.session.widget === widget.key
186    const label = `${isSelected ? '▸ ' : ''}${widget.title}${widget.mod === 'claude' || widget.title === widget.key ? '' : ` (${widget.mod})`}${isRunning ? '' : ' (not running)'}${isHidden ? ' (hidden)' : ''}`
187    return Button({ plain: true, key: `widget:${widget.key}`, label, ...(isHidden || !isRunning ? { dimColor: true } : {}), onPress: () => void (current.state.session.widget = widget.key) })
188  }
189  const layout = widgets.layout()
190  const sections = areas.map((area) => {
191    const rows = layout.areas[area].map((row, index) => Box({ key: `row:${area}:${index}`, columnGap: 2, flexWrap: 'wrap', children: [...row.left.map((key) => chip(key, area)), Text({ dimColor: true, children: '│' }), ...row.right.map((key) => chip(key, area))] }))
192    const builtIns = area === BelowPrompt ? [Box({ columnGap: 2, flexWrap: 'wrap', children: builtInWidgets.map(({ key }) => chip(key, area)) })] : []
193    return Box({ flexDirection: 'column', children: [Text({ bold: true, children: areaTitles[area] }), ...builtIns, ...(rows.length === 0 ? [Text({ dimColor: true, children: 'No widgets' })] : rows)] })
194  })
195  const selected = current.state.session.widget
196  const area = selected === null ? undefined : placedIn(layout, selected)
197  const isBuiltIn = builtInWidgets.some((widget) => widget.key === selected)
198  const actions =
199    selected === null || (area === undefined && !isBuiltIn)
200      ? [Text({ dimColor: true, children: 'Pick a widget to move it, hide it, or show it.' })]
201      : [
202          Box({
203            columnGap: 2,
204            flexWrap: 'wrap',
205            children: [
206              ...(area === undefined ? [] : moves.map(({ move, hotkey, label }) => Button({ plain: true, key: `move:${move}`, hotkey, label, onPress: () => void widgets.change((now) => moved(now, widgetFor(selected, area), move)) }))),
207              Button({ plain: true, key: 'hide', hotkey: 'x', label: layout.hidden.includes(selected) ? 'Show' : 'Hide', onPress: () => void widgets.change((now) => toggled(now, selected)) }),
208            ],
209          }),
210        ]
211  return Box({ flexDirection: 'column', gap: 1, children: [...sections, ...actions] })
212}
213
214export function settings<State extends SettingsState>(mod: Mod<State>) {
215  return (pane: Pane, changed: () => void): SettingsView => {
216    const { pages, widgets, claude } = engineOf(mod)
217    if (pages === undefined || widgets === undefined) throw new Error('cmod draws no Settings, because the cmod plugin started without its pages and widgets.')
218
219    const read = (path: string) => fs.read(path).catch(ifMissing(undefined))
220
221    const viewOf = async (name: string, root: string, version: string, isOn: boolean, granted: readonly string[], rows: readonly ConfigRow[], combos: ReadonlyMap<string, string>): Promise<ModView> => {
222      const manifest: unknown = await read(`${root}/package.json`).then((text) => (text === undefined ? undefined : JSON.parse(text)))
223      const plugin: unknown = await read(`${root}/.claude-plugin/plugin.json`).then((text) => (text === undefined ? undefined : JSON.parse(text)))
224      const steps = isObject(manifest) ? readSteps(manifest) : undefined
225      const ask = async (method: string): Promise<readonly string[]> => {
226        if (name === mod.name) return []
227        const answer = await claude.cmod.call({ to: name, method, input: null }).catch((error: unknown) => {
228          mod.log(`${name} did not answer ${method}: ${messageOf(error)}`)
229          return undefined
230        })
231        return Array.isArray(answer) ? (answer as string[]) : []
232      }
233      return {
234        name,
235        version,
236        description: isObject(plugin) && typeof plugin['description'] === 'string' ? plugin['description'] : undefined,
237        isOn,
238        permissions: (steps?.permissions ?? []).map((item) => ({ item, isOn: granted.includes(item) })),
239        hotkeys: Object.entries(steps?.hotkeys ?? {}).map(([hotkey, { title }]) => ({ name: hotkey, title, combo: combos.get(hotkeyCommand(name, hotkey)) })),
240        options: rows.filter((row) => row.key.startsWith(`${name}.`)),
241        pendingSteps: await ask(pendingStepsMethod),
242        changelog: changelogSections((await read(`${root}/CHANGELOG.md`)) ?? ''),
243      }
244    }
245
246    const load = async (): Promise<readonly ModView[]> => {
247      const store = await storeOf(mod)
248      const consent = await readConsent(mod)
249      const rows = await claude.config.list()
250      const combos = await readCombos(claude, await configRootOf(mod))
251      const enabledPlugins = (await claude.settings.read())['enabledPlugins']
252      const enabled = Object.entries(isObject(enabledPlugins) ? enabledPlugins : {}).map(([id, isEnabled]) => ({ name: id.replace(/@[^@]*$/, ''), isEnabled }))
253      const turnedOff = enabled.filter(({ name, isEnabled }) => isEnabled === false && !enabled.some((each) => each.name === name && each.isEnabled === true)).map(({ name }) => name)
254      const names = (await fs.exists(`${store}/records`)) ? (await fs.list(`${store}/records`)).filter((entry) => entry.name.endsWith('.json')).map((entry) => entry.name.slice(0, -'.json'.length)) : []
255      const records = (await Promise.all(names.filter((name) => name !== mod.name).map((name) => readRecord(read, store, name)))).filter((record) => record !== undefined)
256      const own = JSON.parse((await read(`${mod.folder}/.claude-plugin/plugin.json`)) ?? '{}') as { readonly version?: string }
257      const cmod = await viewOf(mod.name, mod.folder, own.version ?? '', true, [], [], combos)
258      const views = await Promise.all(records.map((record) => viewOf(record.name, record.root, record.version, !turnedOff.includes(record.name), consent[record.name] ?? [], rows, combos)))
259      return [cmod, ...views.sort((left, right) => left.name.localeCompare(right.name))]
260    }
261
262    let hasLoaded = false
263    const refresh = async () => {
264      hasLoaded = true
265      const failed = (what: string) => (error: unknown) => void (mod.state.session.notice = `${what} did not load: ${messageOf(error)}`)
266      await load().then((views) => void (mod.state.memory.views = views), failed('The mods'))
267      await readLog(mod).then((log) => void (mod.state.memory.log = log), failed('The Log'))
268      await readPreferences(mod).then((preferences) => void (mod.state.memory.preferences = preferences), failed('The preferences'))
269    }
270
271    const act = (task: () => Promise<string | undefined>) =>
272      void task()
273        .then((notice) => {
274          mod.state.session.notice = notice ?? null
275          return refresh()
276        })
277        .catch((error: unknown) => void (mod.state.session.notice = messageOf(error)))
278
279    const runCmod = async (argv: readonly string[], done: string, timeoutMs?: number) => {
280      const { exitCode, stdout, stderr } = await process.run(['cmod', ...argv], timeoutMs === undefined ? {} : { timeoutMs })
281      return exitCode === 0 ? done || stdout.trim() : `cmod ${argv.slice(0, 2).join(' ')} ${formatExit(exitCode, cmodError(stderr, argv[0]))}`
282    }
283
284    const toggle = (name: string, { item, isOn }: Permission) => {
285      const split = item.indexOf(':')
286      const words = split === -1 ? [item] : [item.slice(0, split), item.slice(split + 1)]
287      act(() => runCmod(['permission', name, ...words, isOn ? 'off' : 'on'], ''))
288    }
289
290    const remove = (name: string) =>
291      act(async () => {
292        mod.state.memory.removing = null
293        mod.state.session.notice = `Removing ${name}…`
294        return runCmod(['remove', name], `Removed ${name}.`, longestMs)
295      })
296
297    const turn = (name: string, isOn: boolean) => act(() => runCmod([isOn ? 'enable' : 'disable', name], `Turned ${name} ${isOn ? 'on' : 'off'}.`))
298
299    const setOption = (name: string, row: ConfigRow, text: string) => act(() => runCmod(['option', name, row.key.slice(name.length + 1), text.split(',').map((item) => item.trim()).join(',')], `Saved ${row.label}. ${name} reads it at its next start.`))
300
301    const bind = (name: string, hotkey: HotkeyView, combo: string) => act(() => runCmod(['hotkey', name, hotkey.name, combo.trim()], `Bound ${combo.trim()} to ${hotkey.title}.`))
302
303    const sectionsOf = (view: ModView) => {
304      const own = pages.declared().find((each) => each.mod === view.name)?.pages.filter((page) => page.place === 'settings') ?? []
305      return [
306        ...own.map((page) => ({ key: `${pageSection}${page.id}`, label: page.title })),
307        ...(view.name === mod.name ? [] : [{ key: 'options', label: 'Options' }, { key: 'permissions', label: 'Permissions' }]),
308        { key: 'hotkeys', label: 'Hotkeys' },
309        ...(view.name === mod.name
310          ? [
311              { key: 'widgets', label: 'Widgets' },
312              { key: 'log', label: 'Log' },
313              { key: 'preferences', label: 'Preferences' },
314            ]
315          : []),
316        ...(view.changelog.length === 0 ? [] : [{ key: 'changelog', label: 'Changelog' }]),
317      ]
318    }
319
320    const shownOf = () => {
321      const { selected, section } = mod.state.session
322      const view = mod.state.memory.views.find((each) => each.name === selected) ?? mod.state.memory.views[0]
323      const sections = view === undefined ? [] : sectionsOf(view)
324      return { view, section: sections.some(({ key }) => key === section) ? section : (sections[0]?.key ?? 'hotkeys') }
325    }
326
327    const failuresLog = (): RenderElement => {
328      const { log, reporting } = mod.state.memory
329      if (log.length === 0) return Text({ dimColor: true, children: 'No mod has failed.' })
330      const copy = (entry: LogEntry) =>
331        act(async () => {
332          await clipboard.write(entry.details)
333          return 'Copied the error.'
334        })
335      const askClaude = (entry: LogEntry) =>
336        act(async () => {
337          mod.state.memory.reporting = null
338          await claude.prompt.submit({ text: reportPrompt(entry.mod, entry.contact, entry.details), asUser: true })
339          return undefined
340        })
341      return Box({
342        flexDirection: 'column',
343        gap: 1,
344        children: log.map((entry) => {
345          const key = `${entry.mod}/${entry.id}`
346          const choices =
347            reporting === key
348              ? [
349                  Button({ plain: true, key: `ask-claude:${key}`, label: 'Ask Claude to report it', onPress: () => askClaude(entry) }),
350                  ...(entry.contact === undefined ? [] : [reportLink(entry.contact, entry.mod, entry.message, entry.details)]),
351                  Button({ plain: true, dimColor: true, key: `back:${key}`, label: 'Back', onPress: () => void (mod.state.memory.reporting = null) }),
352                ]
353              : [
354                  Button({ plain: true, key: `copy:${key}`, label: 'Copy', onPress: () => copy(entry) }),
355                  Button({ plain: true, key: `report:${key}`, label: 'Report', onPress: () => void (mod.state.memory.reporting = key) }),
356                ]
357          return Box({
358            key: `log:${key}`,
359            flexDirection: 'column',
360            children: [
361              Text({ wrap: 'truncate-end', children: [Text({ bold: true, children: entry.mod }), Text({ dimColor: true, children: ` · ${timeOf(entry.at)}` })] }),
362              Text({ wrap: 'wrap', children: entry.message }),
363              Box({ gap: 2, flexWrap: 'wrap', children: choices }),
364            ],
365          })
366        }),
367      })
368    }
369
370    const drawSection = (view: ModView, section: string, columns: number, isFocused: boolean): RenderElement => {
371      if (section.startsWith(pageSection)) return pages.element(view.name, section.slice(pageSection.length), mod.state.session.pageParams, columns, isFocused) ?? Text({ dimColor: true, children: 'Drawing…' })
372      if (section === 'widgets') return widgetsLayout(mod, widgets)
373      if (section === 'log') return failuresLog()
374      if (section === 'preferences') {
375        return Box({
376          flexDirection: 'column',
377          children: Object.entries(preferenceTitles).map(([key, title]) => {
378            const isOn = mod.state.memory.preferences[key as keyof Preferences]
379            const turn = async () => {
380              await writePreference(mod, key as keyof Preferences, !isOn)
381              return undefined
382            }
383            return Button({ plain: true, key: `preference:${key}`, label: `${isOn ? '[x]' : '[ ]'} ${title}`, onPress: () => act(turn) })
384          }),
385        })
386      }
387      if (section === 'options') {
388        if (view.options.length === 0) return Text({ dimColor: true, children: `${view.name} has no options.` })
389        return Box({
390          flexDirection: 'column',
391          gap: 1,
392          children: view.options.map((row) =>
393            Box({
394              flexDirection: 'column',
395              children: [
396                Text({ children: [Text({ bold: true, children: row.label }), row.isLocked ? Text({ dimColor: true, children: '  set by your organization' }) : ''] }),
397                row.isLocked ? Text({ children: String(row.value) }) : Input({ key: `option:${row.key}`, label: 'Value', value: Array.isArray(row.value) ? row.value.join(', ') : String(row.value), submitLabel: 'save', onSubmit: (text: string) => setOption(view.name, row, text) }),
398              ],
399            }),
400          ),
401        })
402      }
403      if (section === 'permissions') {
404        if (view.permissions.length === 0) return Text({ dimColor: true, children: `${view.name} asks for no permissions.` })
405        return Box({ flexDirection: 'column', children: view.permissions.map((permission) => Button({ plain: true, key: `permission:${permission.item}`, label: `${permission.isOn ? '[x]' : '[ ]'} ${permissionWords(permission.item)}`, onPress: () => toggle(view.name, permission) })) })
406      }
407      if (section === 'hotkeys') {
408        if (view.hotkeys.length === 0) return Text({ dimColor: true, children: `${view.name} has no hotkeys.` })
409        return Box({
410          flexDirection: 'column',
411          gap: 1,
412          children: view.hotkeys.map((hotkey) =>
413            Box({
414              flexDirection: 'column',
415              children: [
416                Text({ children: [Text({ bold: true, children: hotkey.title }), ...(hotkey.combo === undefined ? [Text({ dimColor: true, children: ' · unbound' })] : [])] }),
417                Input({ key: `hotkey:${hotkey.name}`, label: 'Combo', value: hotkey.combo ?? '', placeholder: 'none', submitLabel: 'bind', onSubmit: (combo: string) => bind(view.name, hotkey, combo) }),
418              ],
419            }),
420          ),
421        })
422      }
423      return Box({
424        flexDirection: 'column',
425        gap: 1,
426        children: view.changelog.map(({ version, date, text }) =>
427          Box({
428            key: `changelog:${version}`,
429            flexDirection: 'column',
430            children: [
431              Text({ children: [Text({ bold: true, children: version }), Text({ dimColor: true, children: `${date === undefined ? '' : ` · ${date}`}${version === view.version ? ' · installed' : ''}` })] }),
432              Markdown({ text: text === '' ? '_No changes listed._' : text }),
433            ],
434          }),
435        ),
436      })
437    }
438
439    return {
440      draw(columns, isFocused) {
441        if (!hasLoaded) void refresh()
442        const { removing, views } = mod.state.memory
443        const { notice } = mod.state.session
444        const { view, section: shownSection } = shownOf()
445        if (view === undefined) return Text({ dimColor: true, children: notice ?? 'Reading your mods…' })
446        const sections = sectionsOf(view)
447        const status = (each: ModView) => (!each.isOn ? Text({ dimColor: true, children: '○ ' }) : each.pendingSteps.length > 0 ? Text({ color: 'warning', children: '● ' }) : Text({ dimColor: true, children: '● ' }))
448        const rowLabel = (each: ModView) => `${each.name}${each.isOn ? '' : ' (off)'}`
449        const listColumns = Math.max(...views.map((each) => rowLabel(each).length)) + statusColumns + rowPadding + panelColumns
450        const isWide = columns - listColumns - 1 >= detailMinColumns
451        const mods = Panel({
452          title: 'Mods',
453          children: Box({
454            flexDirection: 'column',
455            children: views.map((each) =>
456              each === view
457                ? Box({ backgroundColor: selectedColor, paddingX: 1, children: Text({ wrap: 'truncate-end', children: [status(each), Text({ bold: true, children: rowLabel(each) })] }) })
458                : Box({
459                    paddingX: 1,
460                    children: Button({
461                      plain: true,
462                      dimColor: true,
463                      key: `mod:${each.name}`,
464                      onPress: () => {
465                        mod.state.session.selected = each.name
466                        mod.state.session.pageParams = null
467                        mod.state.memory.removing = null
468                        changed()
469                      },
470                      children: [status(each), rowLabel(each)],
471                    }),
472                  }),
473            ),
474          }),
475        })
476        const actions =
477          view.name === mod.name || removing === view.name
478            ? []
479            : [
480                Box({
481                  gap: 2,
482                  flexShrink: 0,
483                  children: [filledButton({ key: 'turn', label: view.isOn ? 'Turn off' : 'Turn on', onPress: () => turn(view.name, !view.isOn) }), filledButton({ key: 'remove', label: 'Remove', onPress: () => void (mod.state.memory.removing = view.name) })],
484                }),
485              ]
486        const header = Box({
487          flexDirection: 'column',
488          children: [
489            Box({ justifyContent: 'space-between', columnGap: 2, flexWrap: 'wrap', children: [Text({ dimColor: true, children: view.version }), ...actions] }),
490            ...(view.description === undefined ? [] : [Text({ dimColor: true, wrap: 'wrap', children: view.description })]),
491          ],
492        })
493        const removal =
494          removing === view.name
495            ? [
496                Box({
497                  flexDirection: 'column',
498                  children: [
499                    Text({ color: 'warning', wrap: 'wrap', children: `Remove ${view.name}? Its uninstall step runs, and Claude Code deletes it.` }),
500                    Box({ gap: 2, flexShrink: 0, children: [filledButton({ key: 'keep', variant: 'primary', label: 'Keep', onPress: () => void (mod.state.memory.removing = null) }), filledButton({ key: 'remove-confirmed', label: 'Remove', onPress: () => remove(view.name) })] }),
501                  ],
502                }),
503              ]
504            : []
505        const finishSetup = () =>
506          act(async () => {
507            const opened: unknown = await claude.cmod.call({ to: view.name, method: finishStepsMethod, input: null })
508            if (isObject(opened)) pages.update(view.name, opened)
509            return undefined
510          })
511        const attention = [
512          ...(view.isOn ? [] : [Text({ color: 'warning', wrap: 'wrap', children: 'Off: Claude Code does not load it.' })]),
513          ...(view.pendingSteps.length === 0 ? [] : [Box({ flexDirection: 'column', children: [Text({ color: 'warning', wrap: 'wrap', children: `Needs setup: ${view.pendingSteps.join(', ')}` }), filledButton({ key: 'finish', variant: 'primary', label: 'Finish setup', onPress: finishSetup })] })]),
514        ]
515        const row = Box({
516          flexWrap: 'wrap',
517          children: sections.map(({ key, label }) =>
518            key === shownSection
519              ? Text({ backgroundColor: selectedColor, bold: true, wrap: 'truncate-end', children: ` ${label} ` })
520              : Box({
521                  paddingX: 1,
522                  flexShrink: 0,
523                  children: Button({
524                    plain: true,
525                    dimColor: true,
526                    key: `section:${key}`,
527                    label,
528                    onPress: () => {
529                      mod.state.session.section = key
530                      mod.state.session.pageParams = null
531                      changed()
532                    },
533                  }),
534                }),
535          ),
536        })
537        const detailColumns = (isWide ? columns - listColumns - 1 : columns) - panelColumns
538        const details = Panel({
539          title: view.name,
540          children: Box({
541            flexDirection: 'column',
542            gap: 1,
543            children: [header, ...removal, ...attention, row, drawSection(view, shownSection, detailColumns, isFocused), ...(notice === null ? [] : [Text({ dimColor: true, wrap: 'wrap', children: notice })])],
544          }),
545        })
546        return isWide ? Box({ flexGrow: 1, columnGap: 1, children: [Box({ width: listColumns, flexShrink: 0, children: mods }), details] }) : Box({ flexDirection: 'column', flexGrow: 1, gap: 1, children: [Box({ flexDirection: 'column', flexShrink: 0, children: mods }), details] })
547      },
548      shownPage() {
549        const { view, section } = shownOf()
550        return view !== undefined && section.startsWith(pageSection) ? { mod: view.name, page: section.slice(pageSection.length) } : undefined
551      },
552      closePage(name, page) {
553        const view = mod.state.memory.views.find((each) => each.name === name)
554        if (mod.state.session.selected !== name || mod.state.session.section !== `${pageSection}${page}` || view === undefined) return false
555        mod.state.session.section = sectionsOf(view).find(({ key }) => !key.startsWith(pageSection))?.key ?? 'hotkeys'
556        mod.state.session.pageParams = null
557        return true
558      },
559      async show(name, section, params) {
560        await refresh()
561        const view = mod.state.memory.views.find((each) => each.name === name)
562        if (view === undefined) throw new Error(`${name} is not a mod cmod set up.`)
563        mod.state.session.selected = name
564        mod.state.memory.removing = null
565        mod.state.session.section = section ?? sectionsOf(view)[0]?.key ?? 'hotkeys'
566        mod.state.session.pageParams = params ?? null
567        if (section !== 'changelog') return
568        const shown = view.changelog.some(({ version }) => version === view.version) ? view.version : unreleased
569        await pane.scrollTo({ key: `changelog:${shown}` }, { block: 'start' })
570      },
571    }
572  }
573}
574
src/sidebar.ts 241 lines
1import type { RenderElement } from 'claude-code'
2import { Dashboard, type Mod, type Pane } from '../node_modules/@cmodjs/core/mod.js'
3import { filledButton } from '../node_modules/@cmodjs/core/runtime/buttons.js'
4import { engineOf } from '../node_modules/@cmodjs/core/runtime/engine.js'
5import { installPage } from '../node_modules/@cmodjs/core/runtime/installer.js'
6import type { PageRequest, SettingsTab } from '../node_modules/@cmodjs/core/runtime/ui.js'
7import { Panel } from '../node_modules/@cmodjs/core/ui/components.js'
8import { Box, Button, Text } from '../node_modules/@cmodjs/core/ui/elements.js'
9
10export type OpenPage = { readonly mod: string; readonly page: string; readonly params: unknown }
11
12export type SidebarState = { readonly session: { pages: readonly OpenPage[]; shown: string } }
13
14const dashboardTab = 'dashboard'
15
16const settingsTab = 'settings'
17
18const pageHotkeys = 8
19
20const barColor = 'userMessageBackground'
21
22const shownColor = 'claude'
23
24const focusedKeys = [
25  ['↑↓', 'scroll'],
26  ['tab', 'move'],
27  ['esc', 'hide'],
28] as const
29
30const unfocusedKeys = [['click', 'focus']] as const
31
32const panelColumns = 4
33
34type TabView = { readonly key: string; readonly label: string; readonly hotkey: string | undefined; readonly isShown: boolean; readonly onClose: (() => void) | undefined }
35
36const tabText = ({ label, hotkey }: Pick<TabView, 'label' | 'hotkey'>) => (hotkey === undefined ? label : `${hotkey}: ${label}`)
37
38const closeGlyph = ' × '
39
40const tabColumns = (each: TabView) => [...tabText(each)].length + 2 + (each.onClose === undefined ? 0 : 1 + [...closeGlyph].length)
41
42export const sidebarSession: SidebarState['session'] = { pages: [], shown: dashboardTab }
43
44export type SettingsView = {
45  draw(columns: number, isFocused: boolean): RenderElement
46  show(mod: string, section?: SettingsTab | 'widgets' | `page:${string}`, params?: unknown): Promise<void>
47  shownPage(): Pick<OpenPage, 'mod' | 'page'> | undefined
48  closePage(mod: string, page: string): boolean
49}
50
51const keyOf = ({ mod, page }: Pick<OpenPage, 'mod' | 'page'>) => `${mod}/${page}`
52
53export function sidebar<State extends SidebarState>(mod: Mod<State>, settings: (sidebar: Pane, changed: () => void) => SettingsView) {
54  const { pages, widgets } = engineOf(mod)
55  if (pages === undefined || widgets === undefined) throw new Error('cmod draws no Sidebar, because the cmod plugin started without its pages and widgets.')
56  const told = new Set<string>()
57
58  const titleOf = (open: OpenPage) => (open.page === installPage ? `Install ${open.mod}` : (pages.declared().find((each) => each.mod === open.mod)?.pages.find((page) => page.id === open.page)?.title ?? open.page))
59
60  const tell = () => {
61    const { pages: open, shown } = mod.state.session
62    const isShown = pane.isShown
63    const inSettings = isShown && shown === settingsTab ? view.shownPage() : undefined
64    const mods = new Set([...told, ...open.map((each) => each.mod), ...(inSettings === undefined ? [] : [inSettings.mod])])
65    for (const name of mods) {
66      const own = open.filter((each) => each.mod === name)
67      const shownPage = inSettings?.mod === name ? inSettings.page : isShown ? (own.find((each) => keyOf(each) === shown)?.page ?? null) : null
68      pages.tell(name, { open: own.map(({ page, params }) => ({ id: page, params })), shown: shownPage, isFocused: shownPage !== null && pane.isFocused })
69      if (own.length === 0 && shownPage === null) told.delete(name)
70      else told.add(name)
71    }
72  }
73
74  const show = (tab: string) => {
75    mod.state.session.shown = tab
76    tell()
77  }
78
79  const closePage = async (key: string) => {
80    const { pages: open, shown } = mod.state.session
81    const index = open.findIndex((each) => keyOf(each) === key)
82    if (index === -1) return
83    const left = open.filter((each) => keyOf(each) !== key)
84    mod.state.session.pages = left
85    if (shown !== key) return tell()
86    const next = left[Math.min(index, left.length - 1)]
87    if (next === undefined) {
88      mod.state.session.shown = dashboardTab
89      await pane.close()
90      return tell()
91    }
92    show(keyOf(next))
93  }
94
95  const tab = ({ key, label, hotkey, isShown, onClose }: TabView): RenderElement => {
96    const closes = onClose === undefined ? [] : [Button({ plain: true, key: `close:${key}`, onPress: onClose, children: Text({ ...(isShown ? { color: shownColor, backgroundColor: 'inverseText' } : { color: barColor, backgroundColor: 'inactive' }), children: closeGlyph }) })]
97    return Box({
98      flexShrink: 0,
99      paddingX: 1,
100      columnGap: 1,
101      ...(isShown ? { backgroundColor: shownColor } : {}),
102      children: [isShown ? Text({ color: 'inverseText', bold: true, children: tabText({ label, hotkey }) }) : Button({ plain: true, dimColor: true, key: `tab:${key}`, ...(hotkey === undefined ? {} : { hotkey }), label, onPress: () => show(key) }), ...closes],
103    })
104  }
105
106  const edge = (glyph: string, left: readonly TabView[], right: TabView, columns: number): RenderElement => {
107    const widths = left.map(tabColumns)
108    const rightColumns = tabColumns(right)
109    const leftColumns = widths.reduce((sum, width) => sum + width, 0)
110    if (leftColumns + rightColumns > columns) return Text({ color: barColor, children: glyph.repeat(columns) })
111    const shown = left.findIndex((each) => each.isShown)
112    const start = shown === -1 ? columns - rightColumns : widths.slice(0, shown).reduce((sum, width) => sum + width, 0)
113    const width = shown === -1 ? rightColumns : (widths[shown] ?? 0)
114    return Text({ children: [Text({ color: barColor, children: glyph.repeat(start) }), Text({ color: shownColor, children: glyph.repeat(width) }), Text({ color: barColor, children: glyph.repeat(columns - start - width) })] })
115  }
116
117  const arrangeWidgets = async () => {
118    show(settingsTab)
119    await view.show(mod.name, 'widgets')
120    tell()
121  }
122
123  const emptyDashboard = () =>
124    Box({
125      flexDirection: 'column',
126      gap: 1,
127      children: [
128        Box({ flexDirection: 'column', children: [Text({ children: 'Nothing is on the Dashboard yet.' }), Text({ dimColor: true, wrap: 'wrap', children: 'Place the widgets your mods add here, in Settings.' })] }),
129        filledButton({ key: 'arrange-widgets', variant: 'primary', label: 'Arrange widgets', onPress: () => void arrangeWidgets() }),
130      ],
131    })
132
133  const body = (columns: number, isFocused: boolean): RenderElement => {
134    const { pages: open, shown } = mod.state.session
135    if (shown === settingsTab) return view.draw(columns, isFocused)
136    const page = open.find((each) => keyOf(each) === shown)
137    if (page === undefined) {
138      const rows = widgets.rows(Dashboard, columns - panelColumns)
139      return Panel({ title: 'Widgets', children: rows.length === 0 ? emptyDashboard() : Box({ flexDirection: 'column', children: rows }) })
140    }
141    return Panel({ title: page.mod, children: pages.element(page.mod, page.page, page.params, columns - panelColumns, isFocused) ?? Text({ dimColor: true, children: `Drawing ${titleOf(page)}…` }) })
142  }
143
144  const pane: Pane = mod.panes.add({
145    id: 'sidebar',
146    title: 'Sidebar',
147    closeOnEscape: true,
148    render(current, { bodyColumns, isFocused, placement, scroll }) {
149      const { pages: open, shown } = current.state.session
150      const isPageShown = open.some((each) => keyOf(each) === shown)
151      const shownTab = shown === settingsTab || isPageShown ? shown : dashboardTab
152      const left: TabView[] = [
153        { key: dashboardTab, label: 'Dashboard', hotkey: '0', isShown: shownTab === dashboardTab, onClose: undefined },
154        ...open.map((each, index): TabView => {
155          const key = keyOf(each)
156          return { key, label: titleOf(each), hotkey: index < pageHotkeys ? `${index + 1}` : undefined, isShown: key === shownTab, onClose: () => void closePage(key) }
157        }),
158      ]
159      const right: TabView = { key: settingsTab, label: 'Settings', hotkey: '9', isShown: shownTab === settingsTab, onClose: undefined }
160      const tabBar = Box({
161        flexDirection: 'column',
162        children: [
163          edge('▄', left, right, bodyColumns),
164          Box({ backgroundColor: barColor, justifyContent: 'space-between', children: [Box({ flexWrap: 'wrap', flexShrink: 1, minWidth: 0, children: left.map(tab) }), tab(right)] }),
165          edge('▀', left, right, bodyColumns),
166        ],
167      })
168      const keyBar = Box({
169        backgroundColor: barColor,
170        paddingX: 1,
171        columnGap: 2,
172        flexWrap: 'wrap',
173        children: (isFocused ? focusedKeys : unfocusedKeys).map(([keys, does]) => Text({ wrap: 'truncate-end', children: [keys, Text({ dimColor: true, children: ` ${does}` })] })),
174      })
175      return Box({
176        flexDirection: 'column',
177        gap: 1,
178        ...(placement === 'dock' ? { minHeight: scroll.bodyRows } : {}),
179        children: [tabBar, Box({ flexDirection: 'column', flexGrow: 1, paddingX: 1, children: body(bodyColumns - 2, isFocused) }), keyBar],
180      })
181    },
182    onClose: () => tell(),
183  })
184
185  const view = settings(pane, () => tell())
186
187  const placeOf = (name: string, page: string) => pages.declared().find((each) => each.mod === name)?.pages.find((each) => each.id === page)?.place
188
189  const apply = async (name: string, requests: readonly PageRequest[]) => {
190    for (const request of requests) {
191      if ('open' in request && placeOf(name, request.open) === 'settings') {
192        show(settingsTab)
193        await pane.open({ focus: true })
194        await view.show(name, `page:${request.open}`, request.params)
195      } else if ('open' in request) {
196        const opened: OpenPage = { mod: name, page: request.open, params: request.params }
197        const open = mod.state.session.pages
198        mod.state.session.pages = open.some((each) => keyOf(each) === keyOf(opened)) ? open.map((each) => (keyOf(each) === keyOf(opened) ? opened : each)) : [...open, opened]
199        show(keyOf(opened))
200        await pane.open(request.focus === true ? { focus: true } : {})
201      } else if ('close' in request) {
202        if (!view.closePage(name, request.close)) await closePage(keyOf({ mod: name, page: request.close }))
203      } else if ('scroll' in request) {
204        const to = typeof request.to === 'string' ? request.to : { key: `${name}/${request.scroll}:${request.to.key}` }
205        await pane.scrollTo(to, request.block === undefined ? {} : { block: request.block })
206      } else if ('settings' in request) {
207        show(settingsTab)
208        await pane.open({ focus: true })
209        await view.show(name, request.tab)
210      } else {
211        mod.log(`${name} sent a page request this cmod does not know, so it skips it: ${JSON.stringify(request)}`)
212      }
213    }
214    tell()
215  }
216  pages.apply(apply)
217
218  return {
219    pane,
220    async toggle() {
221      await pane.toggle({ focus: true })
222      tell()
223    },
224    async toggleSettings() {
225      if (pane.isShown && mod.state.session.shown === settingsTab) {
226        await pane.close()
227        return tell()
228      }
229      show(settingsTab)
230      await pane.open({ focus: true })
231      tell()
232    },
233    async openSettings(name?: string) {
234      show(settingsTab)
235      await pane.open({ focus: true })
236      if (name !== undefined) await view.show(name)
237      tell()
238    },
239  }
240}
241
src/tools.ts 65 lines
1import { tool } from '../node_modules/@cmodjs/core/jobs/tool.js'
2import { commands, Prompt, sessions, type Mod } from '../node_modules/@cmodjs/core/mod.js'
3import { engineOf } from '../node_modules/@cmodjs/core/runtime/engine.js'
4import type { CmodPluginState } from './mod.js'
5
6const carryOn = 'The conversation was compacted. Carry on with the work from before the compaction.'
7
8export function addClaudeTools(mod: Mod<CmodPluginState>): void {
9  const { report } = engineOf(mod)
10  let compaction: { readonly keep?: string } | undefined
11
12  const compact = async ({ keep }: { readonly keep?: string }) => {
13    try {
14      await commands.run('compact', keep)
15      await sessions.current.send({ type: Prompt, text: carryOn })
16    } catch (error) {
17      report({ id: 'compact', message: 'Could not compact the conversation', error })
18    }
19  }
20
21  sessions.current.onTurnEnd(() => {
22    const asked = compaction
23    compaction = undefined
24    if (asked !== undefined) mod.after(1, () => void compact(asked))
25  })
26
27  mod.use(
28    tool({
29      name: 'compact',
30      description: 'Compact this conversation once your answer ends: a summary replaces the conversation so far, and a prompt then lets you carry on. Use it when the context window is filling up and the work so far fits in a summary.',
31      inputSchema: {
32        type: 'object',
33        properties: { keep: { type: 'string', description: 'What the summary must keep, such as the plan, the decisions, and the files changed.' } },
34        additionalProperties: false,
35      },
36      execute: ({ keep }) => {
37        compaction = keep === undefined ? {} : { keep }
38        return 'The conversation compacts once this answer ends, and a prompt then lets you carry on. End your answer now.'
39      },
40    }),
41  )
42  mod.use(
43    tool({
44      name: 'start_background_agent',
45      description: 'Start an agent in a new background Claude Code session. It works on the task on its own, sees none of this conversation, and keeps running after this session ends.',
46      inputSchema: {
47        type: 'object',
48        properties: {
49          task: { type: 'string', description: 'Everything the agent needs to do the task, because it sees none of this conversation.' },
50          title: { type: 'string', description: 'A few words that name the task.' },
51          agentType: { type: 'string', description: 'The agent definition the session runs, such as Explore. Leave it out for a plain session.' },
52          model: { type: 'string', description: 'The model the session runs on, such as sonnet. Leave it out for the default model.' },
53          cwd: { type: 'string', description: 'The folder the session works in. Leave it out for this session’s folder.' },
54        },
55        required: ['task', 'title'],
56        additionalProperties: false,
57      },
58      execute: async ({ task, title, agentType, model, cwd }) => {
59        const started = await sessions.current.startTask({ prompt: task, title, isBackground: true, ...(agentType === undefined ? {} : { agentType }), ...(model === undefined ? {} : { model }), ...(cwd === undefined ? {} : { cwd }) })
60        return `Started a background agent in session ${started.id}. It answers there, not in this conversation.`
61      },
62    }),
63  )
64}
65
types/index.d.ts 11 lines
1export type Cmod = {
2  call(input: { to: string; method: string; input: unknown }): Promise<unknown>
3}
4
5declare module 'claude-code' {
6  interface EngineInterface {
7    cmod: Cmod
8  }
9  interface CmodDependencies {}
10}
11