SLOPSHOPPER

Dot

An always-on assistant with a name and a face: give it goals, and it keeps working on them in background rounds, asks before risky actions, briefs you in the…

panebandcommandtoasttimer
v1.18.1MITupdated 2026-10-13lucasleandro08/claude-mods/plugins/dot
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · dot
│ ┃ dot ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ This mod is off. Turn it on in /mods. ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ⏺ 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 │ │ › /dot │ ⎿ dot: This mod is off. Turn it on in /mods. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · dot
This mod is off. Turn it on in /mods.
README

claude-mods

Dracula-themed mods for Claude Code: a live diff pane, Kubernetes, Docker, CodeBuild and worktree panes, a pull request dashboard, AWS SSO status, guardrails for risky shell commands and a few workflow helpers. Each mod is its own plugin, so install only the ones you want.

Mods use Claude Code's function hooks API, which is in early access and may change between releases. Mods run on your machine with your permissions: read the code before installing, like any plugin.

Install

In Claude Code (terminal or the desktop app's Code tab):

/plugin marketplace add lucasleandro08/claude-mods
/plugin install mod-manager@dracula-mods

The marketplace is named dracula-mods. Open /mods (or click the ⚙ Mods chip above the prompt; the pane also opens by itself while no mod is on): install the mods you want from there (Install or Install all) and turn them on. Every mod ships turned off. Your choices are saved in ~/.claude/dracula-mods.json, so they hold in every session; each mod's other options are in /config.

Mods

ModWhat it doesCommands
mod-managerThe only mod on by default: a pane that lists every mod with an on/off switch and an Install button for the ones not installed yet (it runs claude plugin install, or puts the /plugin install command in your prompt when the CLI is not found), plus a ⚙ Mods · n/12 chip above the prompt. After an install it runs /reload-plugins, so the new mod shows up in the session you are in; ↻ Reload does the same by hand./mods, /mods reload
live-diffA pane with the diff of every Edit and Write Claude makes: file navigator with M/A status, +/- counts, line numbers and red/green rows. A Δ Diff chip above the prompt reopens it./diff, /diff-clear
kube-paneA ⎈ context chip above the prompt (red on production) and a pods pane: context and namespace pickers, filter, pages, unhealthy pods first, and a ⌘ Shell button that opens kubectl exec in the app's Terminal, with a container picker for multi-container pods. Switching context only affects Claude's session: your kubeconfig is never written./pods
pr-paneYour open pull requests grouped by repo, with CI status, the Codex review state and whether each PR already reached your integration branch. A ⑂ PRs chip flags failing CI and Codex findings. Needs the GitHub CLI./prs
guardrailsBlocks risky commands before they run: killing a port owned by a Docker container, pkill docker, printing secrets (env, printenv, echo $API_TOKEN), rewriting the kubeconfig. Asks before kubectl writes on production contexts. Each rule can be switched off.—
promote-branch/promote previews merging the current branch into your integration branch (commits, files, test files touched). /promote go does a full merge in a temporary worktree and pushes it, refusing dirty trees and protected branches./promote, /promote go
codex-loopHands Claude the review loop with the Codex GitHub bot: request a review, weigh each finding, fix or 👎 it, reply, resolve, repeat until 👍, for at most 5 rounds (and 15 minutes of waiting per round) before it stops and reports what is still open./codex-loop <PR> [--max <rounds>]
turn-doneA toast and a chime when a long turn finishes.—
aws-profileEach AWS profile above the prompt with whether its login still works (aws sts get-caller-identity, only the exit code is kept). Expired ones get a login button that runs aws sso login --profile … in the app's Terminal and turns green once you finish. The AWS_PROFILE Claude Code runs with is marked ●; production profiles are red.—
docker-paneA 🐳 Docker · n up chip (unhealthy and stale counts) and a pane grouped by compose project: ports, health, Start/Stop/Restart by container name (never by port), Logs and compose Recreate in the app's Terminal. Flags containers created before your last git checkout in the session's repo, the usual cause of a test failing for no reason./docker
deploy-watchWatches AWS CodeBuild projects: a 🚀 chip with the last build, a warning (chip and toast) when a git push to a project's branch started no build after a few minutes, and a pane with recent builds, their logs in the Terminal and a Start build button that asks first./deploys
worktreesA 🌳 n worktrees chip and a pane with every worktree of the session's repo and of the repos under your roots: branch, uncommitted changes, PR state, a Terminal button, and Remove (asks first, never --force) for clean worktrees whose branch is merged./worktrees
dotAn always-on assistant with a name and a face: Vlad, a chibi vampire drawn in SVG that lives in its own pane and animates by mood (working, waiting on you, idle, paused), with what it is doing right under its name; the mods bar keeps a one-word tile that opens it. Rename it with /dot name. Give it goals in its pane or with /dot <goal>; background rounds (the desktop app's scheduled tasks, every 30 min) pick one goal at a time and work on it, following ~/.claude-dot/rules.md: act alone, ask first, or hand off to you. When it needs a decision it notifies you and the goal shows under Waiting on you, where you answer it. A weekday morning briefing sums up what needs you. Its pane reads like a conversation: what you asked, what it answered, and whether a round is running, when the last one ran and when the next comes; the round interval and the briefing time are picked right there. Its files live in ~/.claude-dot/ (goals, memory, rules), outside ~/.claude, which always asks before edits. Rounds run unattended, so allow the folder once in ~/.claude/settings.json → permissions.allow: Read(~/.claude-dot/) and Edit(~/.claude-dot/) (Edit covers every file-writing tool). Rounds never use the shell: they read with Read, Grep and Glob, and anything that needs a command comes back to you as a question. To let them read Slack, email or other connected apps, add each read tool of the connector to permissions.allow (e.g. mcp__<server>__slack_search_public_and_private, …__slack_read_channel, …__slack_read_thread); write tools stay "ask first". With mcp__ccd_session_mgmt__list_sessions, get_session, list_events, search_session_transcripts and send_message allowed, it sees what your other Claude Code sessions are doing and can message one when a goal asks for it. It keeps a map of them in ~/.claude-dot/sessions.md (what each session is for) to pick who should do a piece of work, reads your global memory index (~/.claude/projects/<home>/memory/MEMORY.md, allow Read(~/.claude/projects/*/memory/**)) for context, turns on a 30-minute watch of Slack and calendar from Settings (or /dot watch) that pings you only when something new arrives, and archives its own finished rounds so the sidebar only shows the live one. Context stays small on purpose: each round is a fresh session, stops after about 25 tool calls and leaves a checkpoint note the next round picks up; memory.md is rewritten each round (30 facts at most, no task progress), the sessions map keeps 20 lines, and done goals past the newest 10 move to archive.json. When a round ends with work left, the next one starts right away (up to 8 in a row). A round still running after autoStopMinutes (10 by default) is waiting on an approval: its session is stopped and archived, and the goal asks you how to go on. Rounds run while the desktop app is open./dot, /dot <goal>, `/dot on \pause \resume \run`

Options

ModOptionDefault
mod-managerShow the Mods chip · open on start until a mod is on · claude CLI pathon · on · PATH
kube-paneProduction context pattern · default namespace · refresh interval · pods per page · kubectl pathprod · default · 15 s · 25 · PATH
pr-paneIntegration branch · Codex bot login · refresh interval · PRs to load · gh pathstaging · chatgpt-codex-connector[bot] · 5 min · 50 · PATH
guardrailsProduction pattern · confirm production writes · block kubeconfig changes · block printing secrets · protect Docker portsprod · on · on · on · on
promote-branchTarget branch · protected branchesstaging · main,master
live-diffContext lines · edits kept2 · 100
turn-doneLong turn threshold · play sound60 s · on
codex-loopCodex bot login · maximum review rounds · wait for Codexchatgpt-codex-connector[bot] · 5 · 15 min
aws-profileProduction pattern · profiles · check interval · aws pathprod · all · 5 min · PATH
docker-paneRefresh interval · docker path60 s (10 s while open) · PATH
deploy-watchProjects (name=branch, comma-separated) · AWS profile · region · poll interval · missing build warning · production pattern · aws pathnone · CLI default · profile's · 60 s · 3 min · prod · PATH
worktreesRoots (folders holding your repos) · refresh interval · gh pathsession repo only · 5 min · PATH
dotWork round interval · morning briefing (weekdays) · open its pane on start30 min · 09:00 · on

With the mod-manager on, every mod's chip is drawn in one bar above the prompt: a tile per mod, its name dimmed over its value (like a usage band), wrapping between tiles with a blank row between lines; each mod publishes its chip as state and the bar sends presses back to it. Without the manager, or if it stops, each mod draws its own row again. Either way the band keeps whatever other mods draw beneath it.

Rolling out to a whole organization

Admins can register the marketplace and install mods for everyone through managed settings (extraKnownMarketplaces and enabledPlugins); people then turn on what they use in /mods. See Plugins for organizations and Mods for admins.

Development

git clone https://github.com/lucasleandro08/claude-mods
cd claude-mods
scripts/check.sh            # validate + test every plugin (CLAUDE_BIN overrides the CLI path)
scripts/check.sh kube-pane  # only one

Load your checkout instead of the published version by adding it as a local marketplace and installing from it:

claude plugin marketplace add ~/claude-mods
claude plugin install mod-manager@dracula-mods --scope user

Plugins of a marketplace added from a local folder load in place, so edits and newly installed mods reach open sessions with /reload-plugins (or ↻ Reload in /mods); see Plugin loading. Avoid CLAUDE_CODE_PLUGIN_DIRS for this: it is read only when a session starts, so a mod added to it shows up only in new sessions.

Layout

.claude-plugin/marketplace.json
plugins/<mod>/
  .claude-plugin/plugin.json   manifest and /config options
  hooks/register.tsx           event wiring, state atoms, everything that touches $
  src/                         pure logic (diffing, parsing kubectl and gh output, rules)
  src/shared/                  vendored copies of scripts/shared (theme, binary lookup)
  ui/                          components the panes and chips draw
  types/index.d.ts             state contract
  tests/                       claude plugin test suites
scripts/shared/                source of the shared files; scripts/sync-shared.sh copies them

Two rules of the hooks runtime shape this layout: $ can only be passed to functions declared in register.tsx itself, and state atoms must be declared there too. Plugins cannot import files from each other, which is why small shared helpers are vendored.

License

MIT


🇧🇷 Em português: mods para o Claude Code com tema Dracula. Instale com /plugin marketplace add lucasleandro08/claude-mods e /plugin install mod-manager@dracula-mods, instale os mods que quiser e ligue cada um em /mods (todos vêm desligados); as demais opções ficam em /config.

After pulling or editing mods

/reload-plugins reads each mod from its folder, but at startup Claude Code loads the installed copy. Run scripts/update-installed.sh after changing a mod (with its version bumped), or a restart brings the old version back.

Source 9 files
hooks/register.tsx 473 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register } from 'claude-code'
3
4import type { Goal, Profile } from '../types'
5import {
6  addGoal, allowRules, answerGoal, finishedRunIds, overdueRunIds, shellCommandsAllowed, memoryStats, splitArchive, markStuck, runningRunIds, writeToolsAllowed, BRIEFING_TASK, briefingCron, briefingPrompt, DEFAULT_PROFILE, DEFAULT_RULES, dotPaths, everyMinutesCron,
7  IDLE_ROUND, WATCH_CRON, WATCH_TASK, watchPrompt, newlyAnswered, newlyWaiting, parseGoals, parseRound, stampChanged, stampRound, parseProfile, removeGoal, serialize, setStatus, taskPointer, WORK_TASK, workPrompt,
8} from '../src/dot'
9import { isOn, OFF_TEXT, parseState, statePath } from '../src/shared/toggle'
10import { barIsLive, sameChip, type Chip, type ChipPress } from '../src/shared/chip'
11import { DRACULA } from '../src/shared/theme'
12import { dotChip } from '../ui/chip'
13import { DotPane, PaneError } from '../ui/pane'
14
15const MOD = 'dot'
16const CHECK_MS = 5000
17const active = atom({ plugin: 'dot', key: 'active' } as const, false)
18let checkedAt = 0
19
20async function isActive($: EngineInterface) {
21  if (Date.now() - checkedAt > CHECK_MS) {
22    checkedAt = Date.now()
23    const home = await $.env.get('HOME').catch(() => undefined)
24    const text = await $.fs.read(statePath(home)).catch(() => '')
25    const on = isOn(parseState(text), MOD)
26    await update($, active, prev => (prev === on ? prev : on))
27  }
28  return read($, active)
29}
30
31
32const chip = atom({ plugin: 'dot', key: 'chip' } as const, null)
33
34async function barOwnsChips($: EngineInterface) {
35  const { value } = await $.state.get({ plugin: 'mod-manager', key: 'bar' })
36  return barIsLive(value, Date.now())
37}
38
39async function setChip($: EngineInterface, next: Chip | null) {
40  await update($, chip, prev => (sameChip(prev, next) ? prev : next))
41}
42
43const PANE_ID = 'dot'
44const USAGE = 'Usage: /dot · /dot <goal> · /dot pause | resume | run | on | clear | watch [off] · /dot name <name> [emoji]'
45
46const profile = atom({ plugin: 'dot', key: 'profile' } as const, DEFAULT_PROFILE)
47const goals = atom({ plugin: 'dot', key: 'goals' } as const, [])
48const round = atom({ plugin: 'dot', key: 'round' } as const, IDLE_ROUND)
49const isOpen = atom({ plugin: 'dot', key: 'isOpen' } as const, false)
50const notice = atom({ plugin: 'dot', key: 'notice' } as const, null)
51const showSettings = atom({ plugin: 'dot', key: 'showSettings' } as const, false)
52// Rounds chained back to back while work is left; capped so a goal that never finishes can't loop forever
53const chained = atom({ plugin: 'dot', key: 'chained' } as const, 0)
54const MAX_CHAINED = 8
55// Clear asks once more; a second press within this window clears
56const confirmClear = atom({ plugin: 'dot', key: 'confirmClear' } as const, 0)
57const CONFIRM_MS = 5000
58const memory = atom({ plugin: 'dot', key: 'memory' } as const, { bullets: 0, chars: 0 })
59type Settings = { everyMinutes: number; briefing: string; openOnStart: boolean; autoStopMinutes: number }
60
61function readSettings(options: PluginOptions): Settings {
62  return {
63    everyMinutes: Math.max(5, Number(options.workEveryMinutes ?? 30) || 30),
64    briefing: String(options.briefingTime ?? '09:00'),
65    openOnStart: options.openOnStart !== false,
66    autoStopMinutes: Math.max(3, Number(options.autoStopMinutes ?? 10) || 10),
67  }
68}
69
70async function paths($: EngineInterface) {
71  return dotPaths((await $.env.get('HOME')) ?? '')
72}
73
74async function readText($: EngineInterface, path: string) {
75  return $.fs.read(path).catch(() => undefined)
76}
77
78async function ensureFiles($: EngineInterface, settings?: Settings) {
79  const p = await paths($)
80  const stored = await readText($, p.profile)
81  const current = stored === undefined && settings
82    ? { ...parseProfile(''), everyMinutes: settings.everyMinutes, briefing: briefingCron(settings.briefing) ? settings.briefing : '' }
83    : parseProfile(stored ?? '')
84  // Replies from before this version count as read, so the first load doesn't flag everything as new
85  if (stored === undefined || !stored.includes('"seenAt"')) await $.fs.write(p.profile, serialize({ ...current, seenAt: current.seenAt || Date.now() }))
86  if ((await readText($, p.goals)) === undefined) await $.fs.write(p.goals, serialize([]))
87  if ((await readText($, p.memory)) === undefined) await $.fs.write(p.memory, '# Memory\n')
88  if ((await readText($, p.sessions)) === undefined) await $.fs.write(p.sessions, '# Claude Code sessions\n')
89  if ((await readText($, p.rules)) === undefined) await $.fs.write(p.rules, DEFAULT_RULES)
90  const home = (await $.env.get('HOME')) ?? ''
91  const settingsText = (await readText($, `${home}/.claude/settings.json`)) ?? ''
92  await $.fs.write(p.work, `${workPrompt(current.name, p, writeToolsAllowed(settingsText), shellCommandsAllowed(settingsText))}\n`)
93  await $.fs.write(p.briefing, `${briefingPrompt(current.name, p)}\n`)
94  await $.fs.write(p.watch, `${watchPrompt(current.name, p)}\n`)
95  return p
96}
97
98async function publishChip($: EngineInterface) {
99  await setChip($, (await read($, active)) ? dotChip(await read($, profile), await read($, goals), await read($, round)) : null)
100}
101
102async function sync($: EngineInterface) {
103  if (!(await isActive($))) return publishChip($)
104  const p = await paths($)
105  const nextProfile = parseProfile((await readText($, p.profile)) ?? '')
106  const before = await read($, goals)
107  const stamped = stampChanged(before, parseGoals((await readText($, p.goals)) ?? '[]'), Date.now())
108  let nextGoals = stamped.goals
109  let goalsChanged = stamped.changed
110  // Only between rounds, so a round never loses a write it is making to goals.json
111  if ((await read($, round)).state !== 'running') {
112    const { kept, archived } = splitArchive(nextGoals)
113    if (archived.length > 0) {
114      const stored = parseGoals((await readText($, p.archive)) ?? '[]')
115      await $.fs.write(p.archive, serialize([...stored, ...archived]))
116      nextGoals = kept
117      goalsChanged = true
118    }
119  }
120  if (goalsChanged) await $.fs.write(p.goals, serialize(nextGoals))
121  const stats = memoryStats((await readText($, p.memory)) ?? '')
122  await update($, memory, prev => (prev.bullets === stats.bullets && prev.chars === stats.chars ? prev : stats))
123  await update($, profile, prev => (JSON.stringify(prev) === JSON.stringify(nextProfile) ? prev : nextProfile))
124  await update($, goals, prev => (JSON.stringify(prev) === JSON.stringify(nextGoals) ? prev : nextGoals))
125  const stampedRound = stampRound(await read($, round), parseRound((await readText($, p.round)) ?? ''), await nowMs($))
126  if (stampedRound.changed) await $.fs.write(p.round, serialize(stampedRound.round))
127  const wasRunning = (await read($, round)).state === 'running'
128  await update($, round, prev => (JSON.stringify(prev) === JSON.stringify(stampedRound.round) ? prev : stampedRound.round))
129  if (wasRunning && stampedRound.round.state === 'idle') void archiveFinished($).catch(() => undefined)
130  if (wasRunning && stampedRound.round.state === 'idle' && nextGoals.some(g => g.status === 'working' || g.status === 'queued')) {
131    if ((await read($, chained)) < MAX_CHAINED) {
132      await update($, chained, n => n + 1)
133      await startSoon($)
134    }
135  }
136  await publishChip($)
137  if (before.length > 0) {
138    for (const goal of newlyWaiting(before, nextGoals)) $.ui.toast(`${nextProfile.emoji} ${nextProfile.name} needs your answer: ${goal.question || goal.title}`, { timeoutMs: 15_000 })
139    for (const goal of newlyAnswered(before, nextGoals)) if (goal.status !== 'waiting') $.ui.toast(`${nextProfile.emoji} ${nextProfile.name} replied: ${goal.title}`, { timeoutMs: 10_000 })
140  }
141}
142
143async function changeGoals($: EngineInterface, change: (list: Goal[], now: number) => Goal[]) {
144  const p = await ensureFiles($)
145  const next = change(parseGoals((await readText($, p.goals)) ?? '[]'), Date.now())
146  await $.fs.write(p.goals, serialize(next))
147  await update($, goals, () => next)
148}
149
150async function changeProfile($: EngineInterface, change: (current: Profile) => Profile) {
151  const p = await ensureFiles($)
152  const next = change(parseProfile((await readText($, p.profile)) ?? ''))
153  await $.fs.write(p.profile, serialize(next))
154  await update($, profile, () => next)
155  await ensureFiles($)
156}
157
158async function say($: EngineInterface, tone: 'ok' | 'error' | 'info', text: string) {
159  await update($, notice, () => ({ tone, text }))
160}
161
162// The scheduled-tasks tools belong to the desktop app; a refused or failed call resolves with isError instead of throwing
163async function nowMs($: EngineInterface) {
164  return $.clock.now().catch(() => Date.now())
165}
166
167async function toolText($: EngineInterface, tool: string, input: Record<string, unknown>) {
168  try {
169    const ran = (await $.tool.call({ tool, ...input } as never)) as { isError?: boolean; deny?: string; text?: string } | undefined
170    return ran?.isError === true || ran?.deny !== undefined ? undefined : ran?.text
171  } catch {
172    return undefined
173  }
174}
175
176// Finished rounds leave a session each in the sidebar; archive them so only the live one shows
177async function archiveFinished($: EngineInterface) {
178  for (const taskId of [WORK_TASK, BRIEFING_TASK, WATCH_TASK]) {
179    const ids = finishedRunIds((await toolText($, 'mcp__scheduled-tasks__list_task_runs', { taskId, limit: 50 })) ?? '')
180    for (const id of ids) await callTool($, 'mcp__ccd_session_mgmt__archive_session', { session_id: id, reason: 'finished dot round' })
181  }
182}
183
184// A round past the limit is waiting on an approval nobody will give: stop it, archive its session, free the round
185async function stopStuck($: EngineInterface, minutes: number) {
186  const now = await nowMs($)
187  // The watch and the briefing have no round.json; their run's start time tells
188  for (const taskId of [WATCH_TASK, BRIEFING_TASK]) {
189    const ids = overdueRunIds((await toolText($, 'mcp__scheduled-tasks__list_task_runs', { taskId, limit: 5 })) ?? '', now, minutes)
190    for (const id of ids) {
191      await callTool($, 'mcp__ccd_session_mgmt__stop_session', { session_id: id })
192      await callTool($, 'mcp__ccd_session_mgmt__archive_session', { session_id: id, reason: 'dot run waited too long for an approval' })
193    }
194  }
195  const current = await read($, round)
196  if (current.state !== 'running' || current.at <= 0 || now - current.at < minutes * 60_000) return
197  const p = await paths($)
198  const idle = { state: 'idle' as const, goal: current.goal, summary: `Stopped after ${minutes} min: it was waiting for an approval.`, at: now }
199  await $.fs.write(p.round, serialize(idle))
200  await update($, round, () => idle)
201  await changeGoals($, (list, now) => markStuck(list, current.goal, minutes, now))
202  const ids = runningRunIds((await toolText($, 'mcp__scheduled-tasks__list_task_runs', { taskId: WORK_TASK, limit: 5 })) ?? '')
203  for (const id of ids) {
204    await callTool($, 'mcp__ccd_session_mgmt__stop_session', { session_id: id })
205    await callTool($, 'mcp__ccd_session_mgmt__archive_session', { session_id: id, reason: 'dot round waited too long for an approval' })
206  }
207}
208
209async function callTool($: EngineInterface, tool: string, input: Record<string, unknown>) {
210  try {
211    const ran = (await $.tool.call({ tool, ...input } as never)) as { isError?: boolean; deny?: string } | undefined
212    return ran?.isError !== true && ran?.deny === undefined
213  } catch {
214    return false
215  }
216}
217
218async function upsertTask($: EngineInterface, taskId: string, title: string, cron: string, promptPath: string) {
219  const fields = { taskId, title, cronExpression: cron, prompt: taskPointer(promptPath), notifyOnCompletion: false }
220  if (await callTool($, 'mcp__scheduled-tasks__update_scheduled_task', { ...fields, enabled: true })) return true
221  return callTool($, 'mcp__scheduled-tasks__create_scheduled_task', { ...fields, description: `${title} (dot mod)` })
222}
223
224async function schedule($: EngineInterface, settings: Settings) {
225  const p = await ensureFiles($, settings)
226  const me = parseProfile((await readText($, p.profile)) ?? '')
227  await update($, profile, () => me)
228  const workCron = everyMinutesCron(me.everyMinutes)
229  const morning = briefingCron(me.briefing)
230  const worked = await upsertTask($, WORK_TASK, `${me.name} · work`, workCron, p.work)
231  const briefed = morning === undefined || (await upsertTask($, BRIEFING_TASK, `${me.name} · briefing`, morning, p.briefing))
232  if (worked && briefed) {
233    await changeProfile($, current => ({ ...current, scheduled: true, paused: false }))
234    return say($, 'ok', `${me.name} now works in the background, every ${me.everyMinutes} min.`)
235  }
236  const ask = [
237    `Set up the background work of my dot ${me.name} with the scheduled-tasks tools (create, or update if it exists):`,
238    `- taskId "${WORK_TASK}", cron "${workCron}", prompt "${taskPointer(p.work)}"`,
239    morning ? `- taskId "${BRIEFING_TASK}", cron "${morning}", prompt "${taskPointer(p.briefing)}"` : '',
240    `Then set "scheduled": true in ${p.profile}, and add ${allowRules().map(rule => `"${rule}"`).join(', ')} to permissions.allow in my user settings so rounds never wait for an approval.`,
241  ].filter(Boolean).join('\n')
242  const filled = await $.prompt.fill({ text: ask, mode: 'replace' }).catch(() => ({ isFilled: false }))
243  await say($, filled.isFilled ? 'info' : 'error', filled.isFilled ? 'The setup request is in your prompt. Press Enter to finish it.' : "The scheduling tools aren't reachable from here. Run /dot on in a session of the desktop app.")
244}
245
246async function setEvery($: EngineInterface, minutes: number) {
247  await changeProfile($, current => ({ ...current, everyMinutes: minutes }))
248  const me = await read($, profile)
249  if (!me.scheduled) return say($, 'info', `Rounds set to every ${minutes} min. Turn on background work to start them.`)
250  const ok = await upsertTask($, WORK_TASK, `${me.name} · work`, everyMinutesCron(minutes), (await paths($)).work)
251  await say($, ok ? 'ok' : 'error', ok ? `Rounds now run every ${minutes} min.` : "Couldn't change the schedule. Try again from a desktop app session.")
252}
253
254async function setBriefing($: EngineInterface, time: string) {
255  const value = time === 'off' ? '' : time
256  await changeProfile($, current => ({ ...current, briefing: value }))
257  const me = await read($, profile)
258  if (!me.scheduled) return
259  const cron = briefingCron(value)
260  const ok = cron === undefined
261    ? await callTool($, 'mcp__scheduled-tasks__update_scheduled_task', { taskId: BRIEFING_TASK, enabled: false })
262    : await upsertTask($, BRIEFING_TASK, `${me.name} · briefing`, cron, (await paths($)).briefing)
263  await say($, ok ? 'ok' : 'error', ok ? (cron ? `Weekday briefing at ${value}.` : 'Briefing turned off.') : "Couldn't change the briefing. Try again from a desktop app session.")
264}
265
266async function setWatch($: EngineInterface, enabled: boolean) {
267  await changeProfile($, current => ({ ...current, watch: enabled }))
268  const me = await read($, profile)
269  const ok = enabled
270    ? await upsertTask($, WATCH_TASK, `${me.name} · watch`, WATCH_CRON, (await paths($)).watch)
271    : await callTool($, 'mcp__scheduled-tasks__update_scheduled_task', { taskId: WATCH_TASK, enabled: false })
272  await say($, ok ? 'ok' : 'error', ok
273    ? (enabled ? `${me.name} checks Slack and your calendar every 30 min and tells you what's new.` : 'Watch turned off.')
274    : "Couldn't change the watch. Try again from a desktop app session.")
275}
276
277async function togglePause($: EngineInterface) {
278  const paused = !(await read($, profile)).paused
279  await changeProfile($, current => ({ ...current, paused }))
280  const watching = (await read($, profile)).watch
281  for (const taskId of [WORK_TASK, BRIEFING_TASK, ...(watching ? [WATCH_TASK] : [])]) await callTool($, 'mcp__scheduled-tasks__update_scheduled_task', { taskId, enabled: !paused })
282  await say($, 'info', paused ? 'Paused. No rounds run until you resume.' : 'Resumed. The next round picks up the queue.')
283}
284
285async function runNow($: EngineInterface) {
286  const me = await read($, profile)
287  if (!me.scheduled) return say($, 'error', 'Background work is off. Turn it on first.')
288  const ran = await callTool($, 'mcp__scheduled-tasks__run_scheduled_task', { taskId: WORK_TASK })
289  await say($, ran ? 'ok' : 'error', ran
290    ? 'A round started. Progress shows up here as it works.'
291    : `A round is already running or waiting for your approval. Open the "${me.name} · work" session in the sidebar.`)
292}
293
294// A new message or reply starts a round at once instead of waiting for the schedule; a round already running picks it up
295async function markSeen($: EngineInterface) {
296  const now = await nowMs($)
297  await changeProfile($, current => ({ ...current, seenAt: now }))
298}
299
300// Moves every goal to archive.json (nothing is lost) and leaves the chat empty
301async function clearChat($: EngineInterface) {
302  const p = await ensureFiles($)
303  const current = parseGoals((await readText($, p.goals)) ?? '[]')
304  if (current.length > 0) {
305    const stored = parseGoals((await readText($, p.archive)) ?? '[]')
306    await $.fs.write(p.archive, serialize([...stored, ...current]))
307  }
308  await $.fs.write(p.goals, serialize([]))
309  await update($, goals, () => [])
310  await update($, confirmClear, () => 0)
311  await markSeen($)
312}
313
314async function pressClear($: EngineInterface) {
315  const now = await nowMs($)
316  if (now - (await read($, confirmClear)) < CONFIRM_MS) return clearChat($)
317  await update($, confirmClear, () => now)
318  $.clock.after(CONFIRM_MS, () => void update($, confirmClear, () => 0).catch(() => undefined))
319}
320
321async function startSoon($: EngineInterface, fromUser = false) {
322  if (fromUser) {
323    await update($, chained, () => 0)
324    await markSeen($)
325  }
326  const me = await read($, profile)
327  if (!me.scheduled || me.paused || (await read($, round)).state === 'running') return
328  await callTool($, 'mcp__scheduled-tasks__run_scheduled_task', { taskId: WORK_TASK })
329}
330
331async function openPane($: EngineInterface) {
332  await ensureFiles($)
333  const opened = await $.ui.open({ id: PANE_ID, title: (await read($, profile)).name })
334  if (opened.isPlaced) await update($, isOpen, () => true)
335  await sync($)
336}
337
338async function press($: EngineInterface, pressed: ChipPress | null) {
339  if (pressed?.plugin === MOD && (await isActive($))) await openPane($)
340}
341
342export const register: Register = (on, options) => {
343  const settings = readSettings(options)
344
345  on('state.set', async ($, e, next) => {
346    const ran = await next(e)
347    if (e.plugin === 'mod-manager' && e.key === 'press') await press($, e.value as ChipPress | null)
348    return ran
349  })
350
351  on('session.start', async ($, e, next) => {
352    await $.command.register({ name: 'dot', description: 'Your always-on assistant: /dot, /dot <goal>, /dot pause|resume|run|on|clear|watch' })
353    $.clock.every(CHECK_MS, () => void sync($).catch(() => undefined))
354    $.clock.every(60_000, () => void stopStuck($, settings.autoStopMinutes).catch(() => undefined))
355    if (settings.openOnStart) $.clock.after(1000, () => void isActive($).then(enabled => (enabled ? openPane($) : undefined)).catch(() => undefined))
356    return next(e)
357  })
358
359  on('command.run', { command: 'dot' }, async ($, e) => {
360    if (!(await isActive($))) return { text: OFF_TEXT }
361    const args = e.args.trim()
362    const [verb = '', ...rest] = args.split(/\s+/)
363    const me = await read($, profile)
364
365    if (args === '') {
366      await openPane($)
367      return { text: `${me.emoji} ${me.name} opened.` }
368    }
369    if (verb === 'pause' || verb === 'resume') {
370      if (me.paused === (verb === 'pause')) return { text: `${me.name} is already ${me.paused ? 'paused' : 'running'}.` }
371      await togglePause($)
372      return { text: `${me.name} ${verb === 'pause' ? 'paused' : 'resumed'}.` }
373    }
374    if (verb === 'run') {
375      await runNow($)
376      return { text: (await read($, notice))?.text ?? '' }
377    }
378    if (verb === 'on') {
379      await schedule($, settings)
380      return { text: (await read($, notice))?.text ?? '' }
381    }
382    if (verb === 'watch') {
383      await setWatch($, rest[0] !== 'off')
384      return { text: (await read($, notice))?.text ?? '' }
385    }
386        if (verb === 'clear') {
387      await clearChat($)
388      return { text: `${me.name}'s chat is clear. Old conversations are in ${(await paths($)).archive}.` }
389    }
390    if (verb === 'name') {
391      const [name, emoji] = rest
392      if (!name) return { text: USAGE }
393      await changeProfile($, current => ({ ...current, name, emoji: emoji ?? current.emoji }))
394      return { text: `Renamed to ${emoji ?? me.emoji} ${name}.` }
395    }
396    await changeGoals($, (list, now) => addGoal(list, args, now))
397    await startSoon($, true)
398    return { text: `${me.emoji} ${me.name} is on it: ${args}` }
399  })
400
401  on('ui.close', async ($, e, next) => {
402    if (e.id === PANE_ID) await update($, isOpen, () => false)
403    return next(e)
404  })
405
406  // Only a tile in the mods bar (or one line without it); the dot itself lives in its own pane
407  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
408    if (!(await read($, active)) || (await barOwnsChips($))) return next(e)
409    const rest = await next(e)
410    const own = await read($, chip)
411    if (e.props.hasSurvey || !own) return rest
412
413    const ui = $.ui.resolve(e)
414    return (
415      <ui.Box flexDirection="column">
416        <ui.Box flexDirection="row" gap={1} alignItems="center" marginBottom={1}>
417          <ui.Text color={DRACULA.purple}>{own.icon}</ui.Text>
418          <ui.Button key="open-dot" label={`${(await read($, profile)).name} · ${own.parts[0]?.text ?? ''}`} dimColor onPress={() => openPane($)} />
419        </ui.Box>
420        {rest}
421      </ui.Box>
422    )
423  })
424
425  on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
426    const ui = $.ui.resolve(e)
427    if (!(await read($, active))) {
428      return <ui.Box padding={1}><ui.Text color="#6272a4">{OFF_TEXT}</ui.Text></ui.Box>
429    }
430    try {
431      return (
432        <DotPane
433          ui={ui}
434          profile={await read($, profile)}
435          goals={await read($, goals)}
436          round={await read($, round)}
437          now={await nowMs($)}
438          notice={await read($, notice)}
439          dotDir={(await paths($)).dir}
440          showSettings={await read($, showSettings)}
441          memory={await read($, memory)}
442          onToggleSettings={() => update($, showSettings, open => !open)}
443          onSeen={() => markSeen($)}
444          confirmClear={(await read($, confirmClear)) > 0}
445          onClear={() => pressClear($)}
446          onWatch={enabled => setWatch($, enabled)}
447          onAdd={async title => {
448            // While it waits on you, the main field answers that question instead of opening a new thread
449            const asking = (await read($, goals)).find(goal => goal.status === 'waiting')
450            await changeGoals($, (list, now) => (asking ? answerGoal(list, asking.id, title, now) : addGoal(list, title, now)))
451            await startSoon($, true)
452          }}
453          onAnswer={async (id, answer) => {
454            await changeGoals($, (list, now) => answerGoal(list, id, answer, now))
455            await startSoon($, true)
456          }}
457          onDone={id => changeGoals($, (list, now) => setStatus(list, id, 'done', now))}
458          onRemove={id => changeGoals($, list => removeGoal(list, id))}
459          onPause={() => togglePause($)}
460          onRunNow={() => runNow($)}
461          onSchedule={() => schedule($, settings)}
462          onEvery={minutes => setEvery($, minutes)}
463          onBriefing={time => setBriefing($, time)}
464        />
465      )
466    } catch (err) {
467      const message = err instanceof Error ? err.message : String(err)
468      $.ui.log(`dot render failed: ${message}`)
469      return <PaneError ui={ui} message={message} />
470    }
471  })
472}
473
src/dot.ts 424 lines
1import type { Goal, GoalStatus, Profile, RoundStatus } from '../types'
2
3export const DOT_DIR = '.claude-dot'
4export const WORK_TASK = 'dot-work'
5export const BRIEFING_TASK = 'dot-briefing'
6export const WATCH_TASK = 'dot-watch'
7export const WATCH_GOAL_ID = 'watch'
8export const WATCH_CRON = '*/30 * * * *'
9export const DEFAULT_PROFILE: Profile = { name: 'Vlad', emoji: '🧛', paused: false, scheduled: false, everyMinutes: 30, briefing: '09:00', seenAt: 0, watch: false }
10export const IDLE_ROUND: RoundStatus = { state: 'idle', goal: '', summary: '', at: 0 }
11export const ROUND_CHOICES = [15, 30, 60, 120] as const
12export const BRIEFING_CHOICES = ['off', '08:00', '09:00', '10:00', '18:00'] as const
13
14export type DotPaths = { dir: string; profile: string; goals: string; round: string; memory: string; rules: string; work: string; briefing: string; sessions: string; archive: string; watch: string; watchState: string; globalMemory: string }
15
16export function dotPaths(home: string): DotPaths {
17  const dir = `${home}/${DOT_DIR}`
18  return {
19    dir,
20    profile: `${dir}/profile.json`,
21    goals: `${dir}/goals.json`,
22    round: `${dir}/round.json`,
23    memory: `${dir}/memory.md`,
24    rules: `${dir}/rules.md`,
25    work: `${dir}/work.md`,
26    briefing: `${dir}/briefing.md`,
27    sessions: `${dir}/sessions.md`,
28    archive: `${dir}/archive.json`,
29    watch: `${dir}/watch.md`,
30    watchState: `${dir}/watch.json`,
31    globalMemory: `${home}/.claude/projects/${home.replace(/[/.]/g, '-')}/memory/MEMORY.md`,
32  }
33}
34
35export function parseProfile(text: string): Profile {
36  try {
37    const parsed = JSON.parse(text) as Partial<Profile>
38    return {
39      name: typeof parsed.name === 'string' && parsed.name.trim() !== '' ? parsed.name.trim() : DEFAULT_PROFILE.name,
40      emoji: typeof parsed.emoji === 'string' && parsed.emoji.trim() !== '' ? parsed.emoji.trim() : DEFAULT_PROFILE.emoji,
41      paused: parsed.paused === true,
42      scheduled: parsed.scheduled === true,
43      everyMinutes: typeof parsed.everyMinutes === 'number' && parsed.everyMinutes >= 5 ? parsed.everyMinutes : DEFAULT_PROFILE.everyMinutes,
44      briefing: typeof parsed.briefing === 'string' ? parsed.briefing : DEFAULT_PROFILE.briefing,
45      seenAt: typeof parsed.seenAt === 'number' ? parsed.seenAt : 0,
46      watch: parsed.watch === true,
47    }
48  } catch {
49    return { ...DEFAULT_PROFILE }
50  }
51}
52
53const STATUSES: readonly GoalStatus[] = ['queued', 'working', 'waiting', 'done']
54
55export function parseGoals(text: string): Goal[] {
56  let parsed: unknown
57  try {
58    parsed = JSON.parse(text)
59  } catch {
60    return []
61  }
62  if (!Array.isArray(parsed)) return []
63  return parsed.flatMap((raw): Goal[] => {
64    const g = raw as Partial<Goal>
65    if (typeof g.id !== 'string' || typeof g.title !== 'string') return []
66    return [{
67      id: g.id,
68      title: g.title,
69      status: STATUSES.includes(g.status as GoalStatus) ? (g.status as GoalStatus) : 'queued',
70      notes: Array.isArray(g.notes) ? g.notes.filter((n): n is string => typeof n === 'string') : [],
71      question: typeof g.question === 'string' ? g.question : '',
72      createdAt: typeof g.createdAt === 'number' ? g.createdAt : 0,
73      updatedAt: typeof g.updatedAt === 'number' ? g.updatedAt : 0,
74    }]
75  })
76}
77
78export function parseRound(text: string): RoundStatus {
79  try {
80    const parsed = JSON.parse(text) as Partial<RoundStatus>
81    return {
82      state: parsed.state === 'running' ? 'running' : 'idle',
83      goal: typeof parsed.goal === 'string' ? parsed.goal : '',
84      summary: typeof parsed.summary === 'string' ? parsed.summary : '',
85      at: typeof parsed.at === 'number' ? parsed.at : 0,
86    }
87  } catch {
88    return { ...IDLE_ROUND }
89  }
90}
91
92// Rounds write their state without a clock; the mod stamps the moment it sees it change
93export function stampRound(before: RoundStatus, after: RoundStatus, now: number): { round: RoundStatus; changed: boolean } {
94  const moved = before.state !== after.state || before.goal !== after.goal || before.summary !== after.summary
95  if (after.at !== 0 && !moved) return { round: after, changed: false }
96  return { round: { ...after, at: moved || after.at === 0 ? now : after.at }, changed: true }
97}
98
99export function nextRoundAt(everyMinutes: number, now: number) {
100  const d = new Date(now)
101  d.setSeconds(0, 0)
102  if (everyMinutes < 60) {
103    const m = d.getMinutes()
104    d.setMinutes(m - (m % everyMinutes) + everyMinutes)
105  } else {
106    const hours = Math.round(everyMinutes / 60)
107    const h = d.getHours()
108    d.setMinutes(0)
109    d.setHours(h - (h % hours) + hours)
110  }
111  return d.getTime()
112}
113
114export function clock(ms: number) {
115  const d = new Date(ms)
116  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
117}
118
119export function serialize(value: unknown) {
120  return `${JSON.stringify(value, null, 2)}\n`
121}
122
123export function addGoal(goals: Goal[], title: string, now: number): Goal[] {
124  const text = title.trim()
125  if (text === '') return goals
126  const id = `g${now.toString(36)}`
127  return [...goals, { id, title: text, status: 'queued', notes: [], question: '', createdAt: now, updatedAt: now }]
128}
129
130export function answerGoal(goals: Goal[], id: string, answer: string, now: number): Goal[] {
131  const text = answer.trim()
132  if (text === '') return goals
133  return goals.map(g =>
134    g.id === id ? { ...g, status: 'queued', notes: [...g.notes, `You: ${text}`], question: '', updatedAt: now } : g,
135  )
136}
137
138export function setStatus(goals: Goal[], id: string, status: GoalStatus, now: number): Goal[] {
139  return goals.map(g => (g.id === id ? { ...g, status, updatedAt: now } : g))
140}
141
142export function removeGoal(goals: Goal[], id: string): Goal[] {
143  return goals.filter(g => g.id !== id)
144}
145
146export function byStatus(goals: Goal[]) {
147  const sorted = [...goals].sort((a, b) => b.updatedAt - a.updatedAt)
148  return {
149    waiting: sorted.filter(g => g.status === 'waiting'),
150    active: sorted.filter(g => g.status === 'working' || g.status === 'queued'),
151    done: sorted.filter(g => g.status === 'done'),
152  }
153}
154
155// Rounds edit goals without touching timestamps; a goal whose content changed gets stamped here
156export function stampChanged(before: Goal[], after: Goal[], now: number): { goals: Goal[]; changed: boolean } {
157  let changed = false
158  const goals = after.map(goal => {
159    const old = before.find(g => g.id === goal.id)
160    const moved = old !== undefined && (old.status !== goal.status || old.notes.length !== goal.notes.length || old.question !== goal.question)
161    const fresh = goal.createdAt === 0
162    if (!moved && !fresh) return goal
163    changed = true
164    return { ...goal, createdAt: goal.createdAt || now, updatedAt: now }
165  })
166  return { goals, changed }
167}
168
169export function newlyWaiting(before: Goal[], after: Goal[]): Goal[] {
170  const was = new Set(before.filter(g => g.status === 'waiting').map(g => g.id))
171  return after.filter(g => g.status === 'waiting' && !was.has(g.id))
172}
173
174export function everyMinutesCron(minutes: number) {
175  const m = Math.max(5, Math.round(minutes))
176  if (m < 60) return `*/${m} * * * *`
177  const hours = Math.max(1, Math.round(m / 60))
178  return hours >= 24 ? '0 9 * * *' : `0 */${hours} * * *`
179}
180
181export function briefingCron(time: string) {
182  const match = time.trim().match(/^(\d{1,2}):(\d{2})$/)
183  if (!match) return undefined
184  const hour = Number(match[1])
185  const minute = Number(match[2])
186  if (hour > 23 || minute > 59) return undefined
187  return `${minute} ${hour} * * 1-5`
188}
189
190export function allowRules(): string[] {
191  return [`Read(~/${DOT_DIR}/**)`, `Edit(~/${DOT_DIR}/**)`]
192}
193
194export const MEMORY_LIMIT = 30
195export const SESSIONS_LIMIT = 20
196export const ROUND_BUDGET = 25
197export const DONE_KEPT = 10
198
199// Done goals past the newest few leave goals.json, so each round reads a small file
200export function splitArchive(goals: Goal[], keep = DONE_KEPT): { kept: Goal[]; archived: Goal[] } {
201  const done = goals.filter(goal => goal.status === 'done').sort((a, b) => b.updatedAt - a.updatedAt)
202  const old = new Set(done.slice(keep).map(goal => goal.id))
203  return { kept: goals.filter(goal => !old.has(goal.id)), archived: goals.filter(goal => old.has(goal.id)) }
204}
205
206export function memoryStats(text: string) {
207  return { bullets: text.split('\n').filter(line => /^\s*[-*] /.test(line)).length, chars: text.length }
208}
209
210export const DEFAULT_RULES = `# Rules
211
212Each action falls in one level. When unsure, use the stricter one.
213
214## Act without asking
215- Read code, files, docs, logs, dashboards and connected apps.
216- Run read-only commands and tests on the local machine.
217- Write notes and drafts inside ~/.claude-dot/ and in local branches or worktrees.
218
219## Ask first (set the goal to "waiting" with a question)
220- Send a message into another Claude Code session, unless the goal itself asks for exactly that.
221- Commit, push, open or comment on pull requests.
222- Send any message (Slack, email, PR comments) on the user's behalf.
223- Change shared configuration, deploy anything, or write to a staging environment.
224
225## Hand off to the user (never do it, explain what to do)
226- Anything in production: writes, restarts, deploys, data changes.
227- Passwords, credentials, secrets, payments, purchases, account settings.
228- Deleting data permanently.
229`
230
231export function workPrompt(name: string, paths: DotPaths, allowedTools: readonly string[] = [], allowedCommands: readonly string[] = []) {
232  return `You are ${name}, the user's always-on assistant. This is one background work round; nobody is watching it live.
233
2341. Read ${paths.profile}. If "paused" is true, stop now without doing anything.
235   Then write ${paths.round} as {"state": "running", "goal": "<title of the goal you pick>", "summary": ""} once you pick a goal (step 3).
2362. Read ${paths.goals} (a JSON array of goals), ${paths.rules}, ${paths.memory} and ${paths.sessions}. Also read the user's global Claude memory index ${paths.globalMemory} (one line per memory file next to it); open the memory files whose line is relevant to the goal, for context on projects, people and preferences. Never edit the global memory.
2373. Pick ONE goal: the oldest with status "queued" first (a new question or an answer from the user, so it never waits behind long jobs), else the oldest "working". If none, stop now: do not invent work.
2384. Set it to "working" and work on it for this round only. Follow the rules file: "Hand off" is never done. "Ask first" is done only once the user approved it: a "You: ..." note on that goal saying yes, "pode", "pode fazer", "faz" or similar counts as approval for what you proposed. Then do it, in parts across rounds when it is big, without asking again.
2395. Before finishing, update that goal in ${paths.goals} (keep every other goal untouched, keep valid JSON):
240   - ALWAYS append one note to "notes" written to the user, as a chat reply: the answer itself when the goal is a question, otherwise what you did or found and what is next. Never finish a round without this note;
241   - status "done" when the goal is complete;
242   - status "waiting" with a one-sentence "question" when you need a decision, an approval or a hand-off, then send a desktop notification (PushNotification) saying "${name}: " and the question;
243   - otherwise keep "working".
244   Leave "createdAt" and "updatedAt" as they are: the dot stamps them. Edit the file with the Edit or Write tool, not the shell.
2456. Rewrite ${paths.memory} as a whole (not just append), at most ${MEMORY_LIMIT} short bullets, no secrets: keep only durable facts about the user, their setup, people, IDs and what works; add what you learned this round; merge duplicates; drop anything stale or contradicted by newer facts or by these instructions. Never put task progress there (batches done, counts, what's next): that belongs in the goal's note.
2467. Last, write ${paths.round} as {"state": "idle", "goal": "<that goal's title>", "summary": "<one short line of what this round did>"}. If there was no goal, leave ${paths.round} untouched.
247
248Keep each round small so you stay focused: once you've made about ${ROUND_BUDGET} tool calls, or read a lot of output, stop where you are. Write the note with what you did, what's left and the exact next step, keep the goal "working", and finish the round; the next round starts fresh from that note.
249
250Nobody can approve anything during this round: any call that asks for approval hangs it forever. So:
251- the shell (Bash) only for these pre-approved commands, run exactly as one command each: no cd, no pipes, no &&, no redirects, no other command (anything else hangs the round): ${allowedCommands.length > 0 ? allowedCommands.join(', ') : 'none'}. For files, use Read, Grep and Glob, which work anywhere under the home folder;
252- for git history, Read <repository>/.git/logs/HEAD: each line is "old new author <email> timestamp timezone<TAB>action: message", the last line is the latest commit; the current branch is in <repository>/.git/HEAD;
253- connected apps (Slack, email, calendar…): their read tools (search, read, list, get) are pre-approved. Load tools with ToolSearch first when they are deferred;
254- the only other tools that run without approval are these (any tool not listed here or above hangs the round, so never call it): ${allowedTools.length > 0 ? allowedTools.join(', ') : 'none'}. When an approved action needs a tool that is not listed, say in the note exactly which tool name the user should add to permissions.allow in ~/.claude/settings.json;
255- your other Claude Code sessions: list_sessions, get_session, list_events and search_session_transcripts (mcp__ccd_session_mgmt__*) show what each one is doing; read them freely. Keep ${paths.sessions} as your map of them (at most ${SESSIONS_LIMIT} lines, newest first): one line per session you looked at or used, "- <title> (<session id>): <repo/branch>, <what it is for>, <last status, date>"; update a line when you learn more and drop sessions that no longer exist. To pick who should do a piece of work, match the goal against that map (title, repo, topic) before messaging anyone. When no session fits, you cannot create one: tell the user in the note to open a new Claude Code session in <folder> and give them the exact first message to paste. send_message (or SendMessage) delivers a message into one as a user turn, so that session acts on it: only send when the goal itself asks you to, or the user approved that exact message in the thread, and say in the note which session you messaged and what;
256- sending a message on the user's behalf (Slack, email): only when the goal itself asks you to send it, or the user approved it in the thread. Write it in the user's voice and language, short, and put the exact text you sent and where (channel or person, with the link) in your note;
257- when the app isn't connected (ToolSearch finds no tool for it), say so in the note and tell the user to connect it in the claude.ai connector settings;
258- if the goal needs any other shell command or a web request, do not try it: set the goal to "waiting" and ask the user to run it (with the exact command) or to add it to permissions.allow as Bash(<command prefix>:*).
259Never print or store secrets. Write notes in the user's language (see the memory file), else the goal's language. Keep notes short and scannable: lead with the answer, then a few short lines or a numbered list.`
260}
261
262export function watchPrompt(name: string, paths: DotPaths) {
263  return `You are ${name}, the user's always-on assistant. This is a quick watch: only check what is new, act on nothing, and finish fast (about 10 tool calls).
264
2651. Read ${paths.profile}. If "paused" is true, stop now.
2662. Read ${paths.watchState} ({"lastCheck": "<ISO time>"}; if missing, use 30 minutes ago) and ${paths.memory}.
2673. Slack (connector read tools, load them with ToolSearch): messages sent to the user after lastCheck that need them: direct messages and group DMs addressed to them, and @mentions of them in channels. Skip the user's own messages, bots and automatic notifications.
2684. Google Calendar (connector read tools): invitations the user received or that changed after lastCheck (new meetings, new times, cancellations), and anything starting in the next 60 minutes that they haven't answered.
2695. If nothing is new, write ${paths.watchState} with {"lastCheck": "<now, ISO>"} and stop. Do not touch any other file.
2706. If something is new:
271   - in ${paths.goals}, find the goal with "id": "${WATCH_GOAL_ID}" (create it if missing: {"id": "${WATCH_GOAL_ID}", "title": "Watch: Slack and calendar", "status": "done", "notes": [], "question": "", "createdAt": 0, "updatedAt": 0}) and append ONE note: a short list, one line per item, who, what in a few words, and the link. Keep every other goal untouched and valid JSON; do not touch timestamps;
272   - send one desktop notification (PushNotification, under 200 characters) starting with "${name}: ", like "${name}: 2 new Slack messages (Igor, Talita) and 1 invite at 15:00";
273   - write ${paths.watchState} with {"lastCheck": "<now, ISO>"}.
274
275Nobody can approve anything here: a call that asks for approval hangs the watch forever. So never use the shell (Bash), not even to read or to get the time; read files with Read, change them only with the Edit or Write tools, and take "now" from the newest Slack or calendar timestamp you saw (or lastCheck plus 30 minutes). Never reply, react, accept or decline anything: only report. Write in the user's language (see the memory file).`
276}
277
278export function briefingPrompt(name: string, paths: DotPaths) {
279  return `You are ${name}, the user's always-on assistant. This is the morning briefing.
280
2811. Read ${paths.profile}. If "paused" is true, stop now.
2822. Read ${paths.goals}, ${paths.rules}, ${paths.memory}, ${paths.sessions} and the global memory index ${paths.globalMemory}.
2833. Look around read-only, following the rules file: goals in progress, what is waiting on the user, and anything in the connected tools that is worth their attention today (open pull requests and CI, failing builds, things the goals depend on). Do not change anything.
2844. Send one desktop notification (PushNotification, under 200 characters) with the most important thing, starting with "${name}: ".
2855. Append the full briefing (a few bullets) as a note to a goal titled "Briefings" in ${paths.goals}, creating it with status "done" if missing (any unique "id"). Do not touch timestamps; edit the file with the Edit or Write tool.
286
287Write in the language of the user's goals.`
288}
289
290export function taskPointer(path: string) {
291  return `Read ${path} and follow it exactly.`
292}
293
294export type Mood = 'working' | 'waiting' | 'done' | 'idle' | 'paused'
295
296const replies = (goal: Goal) => goal.notes.filter(note => !note.startsWith('You: ')).length
297
298// Goals with a reply you haven't acknowledged yet
299export function unreadGoals(goals: Goal[], seenAt: number): Goal[] {
300  return goals.filter(goal => goal.status !== 'queued' && goal.status !== 'waiting' && goal.updatedAt > seenAt && replies(goal) > 0)
301}
302
303// Goals whose reply count grew between two reads: what a round just answered
304export function newlyAnswered(before: Goal[], after: Goal[]): Goal[] {
305  return after.filter(goal => {
306    const old = before.find(g => g.id === goal.id)
307    return old !== undefined && replies(goal) > replies(old)
308  })
309}
310
311// A running round wins: that is it working right now; then a question for you, then replies you haven't seen
312export function moodOf(profile: Profile, goals: Goal[], round?: RoundStatus): Mood {
313  if (profile.paused) return 'paused'
314  if (round ? round.state === 'running' : goals.some(g => g.status === 'working')) return 'working'
315  if (goals.some(g => g.status === 'waiting')) return 'waiting'
316  if (unreadGoals(goals, profile.seenAt).length > 0) return 'done'
317  return 'idle'
318}
319
320export function activityOf(profile: Profile, goals: Goal[]) {
321  const { waiting, active } = byStatus(goals)
322  if (profile.paused) return { status: 'paused', detail: 'No rounds until you resume' }
323  const asking = waiting[0]
324  if (asking) return { status: 'waiting on you', detail: asking.question || asking.title }
325  const current = active.find(g => g.status === 'working')
326  if (current) return { status: 'working', detail: current.notes[current.notes.length - 1] ? `${current.title} · ${current.notes[current.notes.length - 1]}` : current.title }
327  const next = active[active.length - 1]
328  if (next) return { status: profile.scheduled ? 'up next' : 'queued', detail: next.title }
329  return { status: 'idle', detail: 'No goals yet' }
330}
331
332export type NoteLink = { href: string; label: string }
333
334const LINK_NAMES: [RegExp, string][] = [
335  [/slack\.com/, 'Slack'], [/mail\.google\.com/, 'Gmail'], [/meet\.google\.com/, 'Meet'], [/calendar\.google\.com/, 'Calendar'],
336  [/docs\.google\.com/, 'Docs'], [/github\.com/, 'GitHub'], [/notion\.so/, 'Notion'],
337]
338
339// Pulls URLs out of a note so the text reads clean and the links become chips under it
340export function splitLinks(text: string): { body: string; links: NoteLink[] } {
341  const links: NoteLink[] = []
342  const body = text
343    .replace(/\(?(https?:\/\/[^\s)]+)\)?/g, (_, raw: string) => {
344      const trail = /[.,;:!?]+$/.exec(raw)?.[0] ?? ''
345      const href = raw.slice(0, raw.length - trail.length)
346      const host = href.replace(/^https?:\/\//, '').split('/')[0] ?? href
347      const name = LINK_NAMES.find(([pattern]) => pattern.test(host))?.[1] ?? host.replace(/^www\./, '')
348      const same = links.filter(link => link.label.startsWith(name)).length
349      links.push({ href, label: same === 0 ? name : `${name} ${same + 1}` })
350      return trail
351    })
352    .replace(/[ \t]+([,.;:])/g, '$1')
353    .replace(/[ \t]{2,}/g, ' ')
354    .trim()
355  return { body, links }
356}
357
358const READ_TOOL = /__(?:[a-z]+_)?(search|read|list|get)[a-z_]*$/
359
360// Write tools the user allowed in settings, so a round knows what it may call without hanging
361export function writeToolsAllowed(settingsText: string): string[] {
362  try {
363    const allow = (JSON.parse(settingsText) as { permissions?: { allow?: unknown } }).permissions?.allow
364    return Array.isArray(allow) ? allow.filter((rule): rule is string => typeof rule === 'string' && rule.startsWith('mcp__') && !READ_TOOL.test(rule) && !rule.includes('Claude_Browser') && !rule.includes('claude-in-chrome')) : []
365  } catch {
366    return []
367  }
368}
369
370type TaskRun = { session_id?: unknown; status?: unknown; archived?: unknown; started_at?: unknown }
371
372function taskRuns(text: string): TaskRun[] {
373  try {
374    return (JSON.parse(text) as { runs?: TaskRun[] }).runs ?? []
375  } catch {
376    return []
377  }
378}
379
380// Session ids of finished runs still in the sidebar: what the dot archives once a round is over
381export function finishedRunIds(text: string): string[] {
382  return taskRuns(text)
383    .filter(run => run.status !== 'running' && run.archived !== true && typeof run.session_id === 'string')
384    .map(run => run.session_id as string)
385}
386
387// Runs still going after the limit: waiting on an approval nobody will give
388export function overdueRunIds(text: string, now: number, minutes: number): string[] {
389  return taskRuns(text)
390    .filter(run => run.status === 'running' && typeof run.session_id === 'string' && typeof run.started_at === 'string' && now - Date.parse(run.started_at) > minutes * 60_000)
391    .map(run => run.session_id as string)
392}
393
394// Session ids of a task's runs still going, from the list_task_runs answer text
395export function runningRunIds(text: string): string[] {
396  try {
397    const runs = (JSON.parse(text) as { runs?: { session_id?: unknown; status?: unknown }[] }).runs ?? []
398    return runs.filter(run => run.status === 'running' && typeof run.session_id === 'string').map(run => run.session_id as string)
399  } catch {
400    return []
401  }
402}
403
404// The goal a stuck round was on becomes a question, so the next rounds don't walk into the same wall
405export function markStuck(goals: Goal[], title: string, minutes: number, now: number): Goal[] {
406  return goals.map(goal => goal.title === title && goal.status !== 'done'
407    ? { ...goal, status: 'waiting', question: `A round on this stopped after ${minutes} min waiting for an approval nobody could give. Should I try another way, or will you do that step?`, updatedAt: now }
408    : goal)
409}
410
411// Shell prefixes allowed in settings (Bash(<prefix>:*)), so a round knows which commands won't wait for approval
412export function shellCommandsAllowed(settingsText: string): string[] {
413  try {
414    const allow = (JSON.parse(settingsText) as { permissions?: { allow?: unknown } }).permissions?.allow
415    if (!Array.isArray(allow)) return []
416    return allow.flatMap(rule => {
417      const match = typeof rule === 'string' ? /^Bash\((.+?)(?::\*)?\)$/.exec(rule) : null
418      return match ? [match[1] as string] : []
419    })
420  } catch {
421    return []
422  }
423}
424
src/shared/toggle.ts 31 lines
1export const MARKETPLACE = 'dracula-mods'
2export const STATE_FILE = '.claude/dracula-mods.json'
3export const OFF_TEXT = 'This mod is off. Turn it on in /mods.'
4
5export type ModsState = { enabled: Record<string, boolean> }
6
7export function statePath(home: string | undefined) {
8  return `${home ?? ''}/${STATE_FILE}`
9}
10
11export function parseState(text: string): ModsState {
12  try {
13    const parsed = JSON.parse(text) as Partial<ModsState>
14    return { enabled: typeof parsed.enabled === 'object' && parsed.enabled !== null ? parsed.enabled : {} }
15  } catch {
16    return { enabled: {} }
17  }
18}
19
20export function isOn(state: ModsState, name: string) {
21  return state.enabled[name] === true
22}
23
24export function withToggle(state: ModsState, name: string, on: boolean): ModsState {
25  return { enabled: { ...state.enabled, [name]: on } }
26}
27
28export function serializeState(state: ModsState) {
29  return `${JSON.stringify(state, null, 2)}\n`
30}
31
src/shared/chip.ts 28 lines
1import { DRACULA } from './theme'
2
3// The mod-manager draws every mod's chip in one bar; each mod publishes its chip as data
4export type ChipTone = 'text' | 'muted' | 'ok' | 'warn' | 'bad' | 'info' | 'accent'
5export type ChipPart = { text: string; tone: ChipTone; bold?: boolean; action?: string }
6export type Chip = { icon: string; label: string; tone: ChipTone; parts: ChipPart[] }
7export type ChipPress = { plugin: string; action: string; at: number }
8
9export const TONE_COLOR: Record<ChipTone, string> = {
10  text: DRACULA.foreground,
11  muted: DRACULA.comment,
12  ok: DRACULA.green,
13  warn: DRACULA.orange,
14  bad: DRACULA.red,
15  info: DRACULA.cyan,
16  accent: DRACULA.purple,
17}
18
19export function sameChip(a: Chip | null, b: Chip | null) {
20  return JSON.stringify(a) === JSON.stringify(b)
21}
22
23export const BAR_STALE_MS = 30_000
24
25export function barIsLive(beat: number | undefined, now: number) {
26  return typeof beat === 'number' && now - beat < BAR_STALE_MS
27}
28
src/shared/theme.ts 15 lines
1// Dracula palette: https://draculatheme.com/contribute#color-palette
2export const DRACULA = {
3  background: '#282a36',
4  currentLine: '#44475a',
5  foreground: '#f8f8f2',
6  comment: '#6272a4',
7  cyan: '#8be9fd',
8  green: '#50fa7b',
9  orange: '#ffb86c',
10  pink: '#ff79c6',
11  purple: '#bd93f9',
12  red: '#ff5555',
13  yellow: '#f1fa8c',
14} as const
15
ui/chip.tsx 21 lines
1import type { Chip } from '../src/shared/chip'
2import type { Goal, Profile, RoundStatus } from '../types'
3import { byStatus, moodOf, unreadGoals } from '../src/dot'
4
5// Its tile in the mods bar: what it needs from you first, then whether it is working or has news
6export function dotChip(profile: Profile, goals: Goal[], round: RoundStatus): Chip {
7  const mood = moodOf(profile, goals, round)
8  const waiting = byStatus(goals).waiting.length
9  const unread = unreadGoals(goals, profile.seenAt).length
10  const part = mood === 'paused'
11    ? { text: 'paused', tone: 'muted' as const }
12    : waiting > 0
13      ? { text: `⚠ needs you (${waiting})`, tone: 'warn' as const }
14      : mood === 'working'
15        ? { text: '● working…', tone: 'ok' as const }
16        : unread > 0
17          ? { text: `✓ ${unread} new ${unread === 1 ? 'reply' : 'replies'}`, tone: 'info' as const }
18          : { text: 'idle', tone: 'muted' as const }
19  return { icon: profile.emoji, label: profile.name.toLowerCase(), tone: part.tone, parts: [{ ...part, bold: part.tone !== 'muted', action: 'open' }] }
20}
21
ui/pane.tsx 341 lines
1import type { Elements, RenderSurface } from 'claude-code'
2
3import type { Goal, Profile, RoundStatus } from '../types'
4import { avatarSvg } from '../src/avatar'
5import { BRIEFING_CHOICES, MEMORY_LIMIT, byStatus, clock, moodOf, nextRoundAt, ROUND_CHOICES, splitLinks, unreadGoals } from '../src/dot'
6import { DRACULA } from '../src/shared/theme'
7
8type Ui = Elements[RenderSurface]
9
10const BANNER_AVATAR_PX = 72
11const THREADS_SHOWN = 8
12const STUCK_MS = 10 * 60_000
13const BUBBLE_WIDTH = '82%'
14
15// Surfaces a step off the pane background, so groups read without borders
16const SURFACE = '#21222c'
17const MINE = '#44475a'
18const QUESTION = '#3b3326'
19
20export const SUGGESTIONS = [
21  { label: "Today's agenda", text: 'What is on my calendar today, and what should I prepare?' },
22  { label: 'Unanswered Slack', text: 'Who is waiting on a reply from me on Slack?' },
23  { label: 'Important emails', text: 'Any important email that needs my answer?' },
24]
25
26export type Notice = { tone: 'ok' | 'error' | 'info'; text: string }
27
28export type DotPaneProps = {
29  ui: Ui
30  profile: Profile
31  goals: Goal[]
32  round: RoundStatus
33  now: number
34  notice: Notice | null
35  dotDir: string
36  showSettings: boolean
37  memory: { bullets: number; chars: number }
38  onAdd: (title: string) => unknown
39  onAnswer: (id: string, answer: string) => unknown
40  onDone: (id: string) => unknown
41  onRemove: (id: string) => unknown
42  onPause: () => unknown
43  onRunNow: () => unknown
44  onSchedule: () => unknown
45  onEvery: (minutes: number) => unknown
46  onBriefing: (time: string) => unknown
47  onToggleSettings: () => unknown
48  confirmClear: boolean
49  onClear: () => unknown
50  onWatch: (enabled: boolean) => unknown
51  onSeen: () => unknown
52}
53
54const NOTICE_COLOR = { ok: DRACULA.green, error: DRACULA.orange, info: DRACULA.cyan } as const
55
56function statusLine(profile: Profile, round: RoundStatus, now: number): { text: string; color: string } {
57  if (!profile.scheduled) return { text: '○ Off. Turn it on to let it work on its own.', color: DRACULA.orange }
58  if (profile.paused) return { text: '○ Paused', color: DRACULA.comment }
59  if (round.state === 'running') {
60    const since = round.at > 0 ? ` · since ${clock(round.at)}` : ''
61    if (round.at > 0 && now - round.at > STUCK_MS) {
62      return { text: `● Stuck${since}, waiting for an approval. It closes on its own shortly.`, color: DRACULA.orange }
63    }
64    return { text: `● Working${round.goal ? ` on “${round.goal}”` : ''}${since}`, color: DRACULA.green }
65  }
66  const last = round.at > 0 ? ` · last ${clock(round.at)}` : ''
67  return { text: `● Online · next round ${clock(nextRoundAt(profile.everyMinutes, now))}${last}`, color: DRACULA.purple }
68}
69
70// Conversation on top; the live status (avatar, banner) docks at the bottom next to the field you type in
71export function DotPane(props: DotPaneProps) {
72  const { ui, profile, goals, round, now, notice } = props
73  const { Box, Text, Button } = ui
74  const threads = [...goals].sort((a, b) => a.createdAt - b.createdAt).slice(-THREADS_SHOWN)
75  const canRun = profile.scheduled && !profile.paused && round.state !== 'running'
76  const unread = new Set(unreadGoals(goals, profile.seenAt).map(goal => goal.id))
77
78  return (
79    <Box flexDirection="column" backgroundColor={DRACULA.background} paddingX={2} paddingY={1} rowGap={1}>
80      <Box flexDirection="row" gap={2} alignItems="center">
81        <Box flexGrow={1}><Text color={DRACULA.comment} bold>{`${profile.emoji} ${profile.name}`}</Text></Box>
82        {!profile.scheduled && <Button key="schedule" label="Turn on" onPress={props.onSchedule} />}
83        {canRun && <Button key="run-now" label="Run now" plain dimColor onPress={props.onRunNow} />}
84        {goals.length > 0 && <Button key="clear" label={props.confirmClear ? 'Confirm clear?' : 'Clear'} plain dimColor={!props.confirmClear} onPress={props.onClear} />}
85        <Button key="settings" label={props.showSettings ? 'Close' : 'Settings'} plain dimColor onPress={props.onToggleSettings} />
86      </Box>
87      {props.showSettings && <Settings {...props} />}
88
89      <Box flexDirection="column" rowGap={2} paddingY={1}>
90        {threads.length === 0 && <Empty ui={ui} name={profile.name} />}
91        {threads.map(goal => (
92          <Thread ui={ui} goal={goal} name={profile.name} unread={unread.has(goal.id)} emoji={profile.emoji} nextAt={clock(nextRoundAt(profile.everyMinutes, now))}
93            running={round.state === 'running' && round.goal === goal.title}
94            busy={round.state === 'running'}
95            onAnswer={props.onAnswer} onDone={props.onDone} onRemove={props.onRemove} />
96        ))}
97      </Box>
98
99      {notice && <Text color={NOTICE_COLOR[notice.tone]} wrap="wrap">{notice.text}</Text>}
100      <Banner {...props} />
101      <Composer ui={ui} name={profile.name} count={goals.reduce((n, goal) => n + 1 + goal.notes.length, 0)} answering={goals.some(goal => goal.status === 'waiting')} onAdd={props.onAdd} />
102    </Box>
103  )
104}
105
106const EXCERPT = 280
107
108// The newest reply you haven't seen, cut short, so the card answers without scrolling
109function latestReply(unread: Goal[]) {
110  const goal = [...unread].sort((a, b) => b.updatedAt - a.updatedAt)[0]
111  const note = [...(goal?.notes ?? [])].reverse().find(n => !n.startsWith('You: ')) ?? ''
112  const { body } = splitLinks(note)
113  const flat = body.replace(/\s+/g, ' ').trim()
114  return `${clock(goal?.updatedAt ?? 0)} · ${flat.length > EXCERPT ? `${flat.slice(0, EXCERPT)}… (full reply above)` : flat}`
115}
116
117const BANNER = {
118  waiting: { background: '#3b3326', color: DRACULA.orange },
119  working: { background: '#1f3a2a', color: DRACULA.green },
120  done: { background: '#2f2a45', color: DRACULA.purple },
121  idle: { background: SURFACE, color: DRACULA.comment },
122} as const
123
124// The live card above the field: the animated avatar and what matters now (it needs you, it is working, it has news)
125function Banner({ ui, profile, goals, round, now, onSeen }: DotPaneProps) {
126  const { Box, Text, Button } = ui
127  const asking = byStatus(goals).waiting[0]
128  const unread = unreadGoals(goals, profile.seenAt)
129  const running = round.state === 'running' && !profile.paused
130  const kind = asking ? 'waiting' : running ? 'working' : unread.length > 0 ? 'done' : 'idle'
131  const minutes = round.at > 0 ? Math.max(0, Math.round((now - round.at) / 60_000)) : 0
132  const idle = statusLine(profile, round, now)
133  const title = kind === 'waiting'
134    ? `⚠  ${profile.name} needs your answer`
135    : kind === 'working'
136      ? `●  ${profile.name} is working${round.goal ? ` on “${round.goal}”` : ''}`
137      : kind === 'done'
138        ? `✓  ${profile.name} replied${unread.length > 1 ? ` to ${unread.length} messages` : ` to “${unread[0]?.title ?? ''}”`}`
139        : `${profile.name} is all caught up`
140  const detail = kind === 'waiting'
141    ? `${asking?.question || asking?.title || ''} Reply in the conversation above.`
142    : kind === 'working'
143      ? `Started ${clock(round.at)}${minutes > 0 ? ` · ${minutes} min so far` : ''}. Replies show up above as it finishes.`
144      : kind === 'done'
145        ? latestReply(unread)
146        : idle.text.replace(/^[●○]\s*/, '')
147  const style = BANNER[kind]
148  return (
149    <Box flexDirection="row" backgroundColor={style.background} paddingX={2} paddingY={1} gap={2} alignItems="center">
150      {'Svg' in ui
151        ? <ui.Svg source={avatarSvg(moodOf(profile, goals, round), BANNER_AVATAR_PX)} alt={profile.name} width={BANNER_AVATAR_PX} height={BANNER_AVATAR_PX} />
152        : <Text>{profile.emoji}</Text>}
153      <Box flexDirection="column" flexGrow={1} flexShrink={1} rowGap={0}>
154        <Text color={style.color} bold wrap="wrap">{title}</Text>
155        <Text color={kind === 'idle' ? DRACULA.comment : DRACULA.foreground} wrap="wrap">{detail}</Text>
156      </Box>
157      {kind === 'done' && <Button key="seen" label="Got it" onPress={onSeen} />}
158    </Box>
159  )
160}
161
162function Empty({ ui, name }: { ui: Ui; name: string }) {
163  const { Box, Text } = ui
164  return (
165    <Box flexDirection="column" rowGap={0} paddingY={1}>
166      <Text color={DRACULA.foreground} bold>{`Hi, I'm ${name}.`}</Text>
167      <Text color={DRACULA.comment} wrap="wrap">Ask me anything. I keep working on it in the background, read your Slack, email and calendar, and ask before doing anything risky.</Text>
168    </Box>
169  )
170}
171
172function Settings({ ui, profile, dotDir, memory, onEvery, onBriefing, onPause, onWatch }: DotPaneProps) {
173  const { Box, Text, Button } = ui
174  return (
175    <Box flexDirection="column" rowGap={1} backgroundColor={SURFACE} paddingX={2} paddingY={1}>
176      {'Select' in ui ? (
177        <Box flexDirection="row" gap={3} flexWrap="wrap">
178          <ui.Select key="every" label="Rounds" value={String(profile.everyMinutes)}
179            options={ROUND_CHOICES.map(m => ({ value: String(m), label: m < 60 ? `every ${m} min` : `every ${m / 60} h` }))}
180            onSelect={(v: string) => void onEvery(Number(v))} />
181          <ui.Select key="briefing" label="Weekday briefing" value={profile.briefing || 'off'}
182            options={BRIEFING_CHOICES.map(t => ({ value: t, label: t === 'off' ? 'off' : `at ${t}` }))}
183            onSelect={(v: string) => void onBriefing(v)} />
184        </Box>
185      ) : (
186        <Box flexDirection="row" gap={1} flexWrap="wrap">
187          <Text color={DRACULA.comment}>Rounds:</Text>
188          {ROUND_CHOICES.map(m => m === profile.everyMinutes
189            ? <Text color={DRACULA.purple} bold>{m < 60 ? `${m}m` : `${m / 60}h`}</Text>
190            : <Button key={`every-${m}`} label={m < 60 ? `${m}m` : `${m / 60}h`} dimColor plain onPress={() => onEvery(m)} />)}
191        </Box>
192      )}
193      <Box flexDirection="row" gap={2} alignItems="center" flexWrap="wrap">
194        <Text color={profile.watch ? DRACULA.green : DRACULA.comment}>
195          {profile.watch ? '● Watching Slack and calendar every 30 min' : '○ Not watching Slack and calendar'}
196        </Text>
197        <Button key="watch" label={profile.watch ? 'Stop watching' : 'Watch every 30 min'} plain={profile.watch ? true : undefined} dimColor={profile.watch} onPress={() => onWatch(!profile.watch)} />
198      </Box>
199      <Box flexDirection="row" gap={2} alignItems="center" flexWrap="wrap">
200        <Text color={memory.bullets > MEMORY_LIMIT ? DRACULA.orange : DRACULA.comment}>
201          {`Memory: ${memory.bullets}/${MEMORY_LIMIT} facts · ${(memory.chars / 1000).toFixed(1)}k chars`}
202        </Text>
203        {'Link' in ui && <ui.Link key="open-memory" href={`file://${dotDir}/memory.md`} label="Open memory ↗" />}
204        {'Link' in ui && <ui.Link key="open-sessions" href={`file://${dotDir}/sessions.md`} label="Sessions map ↗" />}
205        {'Link' in ui && <ui.Link key="open-rules" href={`file://${dotDir}/rules.md`} label="Rules ↗" />}
206      </Box>
207      <Box flexDirection="row" gap={2} alignItems="center">
208        {profile.scheduled && <Button key="pause" label={profile.paused ? 'Resume rounds' : 'Pause rounds'} plain dimColor onPress={onPause} />}
209        <Box flexGrow={1} flexShrink={1}><Text color={DRACULA.comment} wrap="truncate-start">{`Files: ${dotDir}`}</Text></Box>
210      </Box>
211    </Box>
212  )
213}
214
215type ThreadProps = {
216  ui: Ui
217  goal: Goal
218  name: string
219  emoji: string
220  nextAt: string
221  running: boolean
222  busy: boolean
223  unread: boolean
224  onAnswer: (id: string, answer: string) => unknown
225  onDone: (id: string) => unknown
226  onRemove: (id: string) => unknown
227}
228
229function Mine({ ui, id, text, meta }: { ui: Ui; id: string; text: string; meta?: string }) {
230  const { Box, Text } = ui
231  return (
232    <Box key={id} flexDirection="column" alignItems="flex-end" rowGap={0}>
233      <Box width={BUBBLE_WIDTH} flexDirection="row" justifyContent="flex-end">
234        <Box flexShrink={1} backgroundColor={MINE} paddingX={2}>
235          <Text color={DRACULA.foreground} wrap="wrap">{text}</Text>
236        </Box>
237      </Box>
238      {meta && <Text color={DRACULA.comment}>{meta}</Text>}
239    </Box>
240  )
241}
242
243function Reply({ ui, id, name, emoji, text, tone, background }: { ui: Ui; id: string; name: string; emoji: string; text: string; tone?: string; background?: string }) {
244  const { Box, Text, Link } = ui
245  if ('Markdown' in ui && !tone) {
246    return (
247      <Box key={id} flexDirection="row" gap={1} alignItems="flex-start">
248        <Box flexShrink={0} width={3}><Text>{emoji}</Text></Box>
249        <Box width={BUBBLE_WIDTH} flexDirection="column" rowGap={0}>
250          <Text color={DRACULA.purple} bold>{name}</Text>
251          <ui.Markdown text={text} />
252        </Box>
253      </Box>
254    )
255  }
256  const { body, links } = splitLinks(text)
257  const lines = body.split('\n').filter(line => line.trim() !== '')
258  return (
259    <Box key={id} flexDirection="row" gap={1} alignItems="flex-start">
260      <Box flexShrink={0} width={3}><Text>{emoji}</Text></Box>
261      <Box width={BUBBLE_WIDTH} flexDirection="column" rowGap={0} backgroundColor={background} paddingX={background ? 2 : 0} paddingY={background ? 1 : 0}>
262        <Text color={DRACULA.purple} bold>{name}</Text>
263        {lines.map((line, index) => <Text key={`${id}-l${index}`} color={tone ?? DRACULA.foreground} wrap="wrap">{line}</Text>)}
264        {links.length > 0 && (
265          <Box flexDirection="row" gap={2} flexWrap="wrap" marginTop={1}>
266            {links.map((link, index) => <Link key={`${id}-k${index}`} href={link.href} label={`${link.label} ↗`} />)}
267          </Box>
268        )}
269      </Box>
270    </Box>
271  )
272}
273
274// One goal as a short conversation; its actions show only while you hover it
275function Thread({ ui, goal, name, emoji, nextAt, running, busy, unread, onAnswer, onDone, onRemove }: ThreadProps) {
276  const { Box, Text, Button } = ui
277  const replies = goal.notes.filter(note => !note.startsWith('You: ')).length
278  const state = goal.status === 'done'
279    ? (replies === 0 ? { text: `Done, but ${name} left no reply`, color: DRACULA.orange } : { text: `✓ Done · ${clock(goal.updatedAt)}`, color: DRACULA.comment })
280    : unread && goal.status === 'working'
281      ? { text: `✓ New reply · ${clock(goal.updatedAt)} · ${name} continues next round`, color: DRACULA.purple }
282    : {
283        queued: { text: busy ? `Next in line: ${name} answers this right after the current round` : `${name} starts on this in the next round · ${nextAt}`, color: busy ? DRACULA.cyan : DRACULA.comment },
284        working: { text: running ? `${name} is working on this…` : `${name} continues in the next round · ${nextAt}`, color: DRACULA.green },
285        waiting: { text: `${name} needs your answer`, color: DRACULA.orange },
286      }[goal.status]
287
288  return (
289    <Box key={`thread-${goal.id}`} flexDirection="column" rowGap={1}>
290      <Mine ui={ui} id={`ask-${goal.id}`} text={goal.title} meta={clock(goal.createdAt)} />
291      {goal.notes.map((note, index) => note.startsWith('You: ')
292        ? <Mine ui={ui} id={`note-${goal.id}-${index}`} text={note.slice(5)} />
293        : <Reply ui={ui} id={`note-${goal.id}-${index}`} name={name} emoji={emoji} text={note} />)}
294      {goal.status === 'waiting' && goal.question !== '' && (
295        <Reply ui={ui} id={`question-${goal.id}`} name={name} emoji={emoji} text={goal.question} tone={DRACULA.orange} background={QUESTION} />
296      )}
297      {goal.status === 'waiting' && 'Input' in ui && (
298        <Box flexDirection="row" paddingLeft={4}>
299          <Box width={BUBBLE_WIDTH} backgroundColor={MINE} paddingX={2}>
300            <ui.Input key={`answer-${goal.id}-${goal.notes.length}`} placeholder={`Reply to ${name}…`} submitLabel="send" value=""
301              onSubmit={(text: string) => void onAnswer(goal.id, text)} />
302          </Box>
303        </Box>
304      )}
305      <Box key={`actions-${goal.id}`} flexDirection="row" gap={2} paddingLeft={4} alignItems="center">
306        <Box flexGrow={1} flexShrink={1}>
307          <Text color={unread ? DRACULA.purple : state.color} bold={unread} wrap="wrap">{unread && goal.status === 'done' ? `✓ New reply · ${clock(goal.updatedAt)}` : state.text}</Text>
308        </Box>
309        <Box display="none" hover={{ display: 'flex' }} flexDirection="row" gap={2} flexShrink={0}>
310          {goal.status !== 'done' && <Button key={`done-${goal.id}`} label="Mark done" dimColor plain onPress={() => onDone(goal.id)} />}
311          <Button key={`remove-${goal.id}`} label="Delete" dimColor plain onPress={() => onRemove(goal.id)} />
312        </Box>
313      </Box>
314    </Box>
315  )
316}
317
318// Keyed by the goal count so the field comes back empty once a message lands
319function Composer({ ui, name, count, answering, onAdd }: { ui: Ui; name: string; count: number; answering: boolean; onAdd: (title: string) => unknown }) {
320  const { Box, Text, Button } = ui
321  return (
322    <Box flexDirection="column" rowGap={1}>
323      <Box flexDirection="row" gap={2} flexWrap="wrap">
324        {SUGGESTIONS.map(s => <Button key={`suggest-${s.label}`} label={s.label} plain dimColor onPress={() => onAdd(s.text)} />)}
325      </Box>
326      {'Input' in ui && (
327        <Box backgroundColor={MINE} paddingX={2} paddingY={1}>
328          <ui.Input key={`new-goal-${count}-${answering ? 'a' : 'n'}`} placeholder={answering ? `Answer ${name}…` : `Ask ${name}…`} submitLabel="send" autoFocus value=""
329            onSubmit={(text: string) => void onAdd(text)} />
330        </Box>
331      )}
332      <Text color={DRACULA.comment} wrap="wrap">{`Long message? Type /dot <message> in the main prompt. ${name} starts right away.`}</Text>
333    </Box>
334  )
335}
336
337export function PaneError({ ui, message }: { ui: Ui; message: string }) {
338  const { Box, Text } = ui
339  return <Box padding={1}><Text color={DRACULA.red}>{`The pane couldn't draw: ${message}`}</Text></Box>
340}
341
src/avatar.ts 142 lines
1export type Mood = 'working' | 'waiting' | 'done' | 'idle' | 'paused'
2
3// A chibi vampire drawn in the Dracula palette; each mood swaps the face and the effects around it
4const PALETTE = {
5  ink: '#282a36',
6  hair: '#2b2540',
7  hairShine: '#6a5a9c',
8  skin: '#fdf0f5',
9  skinShade: '#f1d9e6',
10  blush: '#ff79c6',
11  iris: '#ff5555',
12  capeOut: '#6c4fb8',
13  capeIn: '#ff5555',
14  collar: '#4b3a86',
15  gold: '#f1fa8c',
16  green: '#50fa7b',
17  orange: '#ffb86c',
18  purple: '#bd93f9',
19} as const
20
21const STYLE = `
22.bob{animation:bob 2.6s ease-in-out infinite;transform-origin:50% 60%}
23.busy .bob{animation:busy .9s ease-in-out infinite}
24.spin{animation:spin 2.4s linear infinite;transform-box:fill-box;transform-origin:center}
25.glow{animation:glow 1.4s ease-in-out infinite}
26.pop{animation:pop 1.6s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
27.tilt{animation:tilt 1.2s ease-in-out infinite;transform-box:fill-box;transform-origin:50% 100%}
28.cape{animation:cape 3.2s ease-in-out infinite;transform-box:fill-box;transform-origin:50% 0}
29.eye{animation:blink 4.2s infinite;transform-box:fill-box;transform-origin:center}
30.blush{animation:blush 2.6s ease-in-out infinite}
31.ring{animation:ring 2.2s ease-out infinite;transform-box:fill-box;transform-origin:center}
32.spark{animation:spark 1.8s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
33.s2{animation-delay:.6s}.s3{animation-delay:1.2s}
34.bang{animation:bang 1s ease-in-out infinite;transform-box:fill-box;transform-origin:50% 100%}
35.zz{animation:zz 3s ease-in-out infinite}.z2{animation-delay:1s}
36.bat{animation:bat .35s ease-in-out infinite alternate;transform-box:fill-box;transform-origin:center}
37.fly{animation:fly 6s ease-in-out infinite}
38@keyframes bob{0%,100%{transform:translateY(0)}50%{transform:translateY(-3px)}}
39@keyframes busy{0%,100%{transform:translateY(0) rotate(0)}25%{transform:translateY(-6px) rotate(-3deg)}75%{transform:translateY(-6px) rotate(3deg)}}
40@keyframes spin{to{transform:rotate(360deg)}}
41@keyframes glow{0%,100%{opacity:.35}50%{opacity:1}}
42@keyframes pop{0%,100%{transform:scale(1)}50%{transform:scale(1.18)}}
43@keyframes tilt{0%,100%{transform:rotate(-4deg)}50%{transform:rotate(4deg)}}
44@keyframes cape{0%,100%{transform:skewX(0) scaleX(1)}50%{transform:skewX(-3deg) scaleX(1.03)}}
45@keyframes blink{0%,93%,100%{transform:scaleY(1)}96%{transform:scaleY(.08)}}
46@keyframes blush{0%,100%{opacity:.35}50%{opacity:.6}}
47@keyframes ring{0%{transform:scale(.85);opacity:.55}100%{transform:scale(1.25);opacity:0}}
48@keyframes spark{0%,100%{transform:scale(.4);opacity:0}50%{transform:scale(1);opacity:1}}
49@keyframes bang{0%,100%{transform:rotate(-14deg) scale(1)}50%{transform:rotate(14deg) scale(1.2)}}
50@keyframes zz{0%{opacity:0;transform:translate(0,0)}30%{opacity:1}100%{opacity:0;transform:translate(6px,-12px)}}
51@keyframes bat{from{transform:scaleY(1)}to{transform:scaleY(.55)}}
52@keyframes fly{0%,100%{transform:translate(0,0)}50%{transform:translate(-6px,-4px)}}
53`
54
55function eyes(mood: Mood, blink = false) {
56  const p = PALETTE
57  if (mood === 'paused' || blink) {
58    return `<path d="M38 55 q5 4 10 0 M62 55 q5 4 10 0" stroke="${p.ink}" stroke-width="2.4" fill="none" stroke-linecap="round"/>`
59  }
60  const eye = (cx: number) => `<g class="eye">
61    <ellipse cx="${cx}" cy="55" rx="5.6" ry="6.6" fill="${p.ink}"/>
62    <ellipse cx="${cx}" cy="56.6" rx="3.6" ry="4.2" fill="${p.iris}"/>
63    <circle cx="${cx - 1.8}" cy="52.6" r="1.9" fill="#fff"/>
64    <circle cx="${cx + 1.9}" cy="58.2" r=".9" fill="#fff" opacity=".8"/>
65  </g>`
66  return eye(43) + eye(67)
67}
68
69function mouth(mood: Mood) {
70  const p = PALETTE
71  if (mood === 'waiting') return `<ellipse cx="55" cy="68.5" rx="2.6" ry="3" fill="${p.ink}"/>`
72  if (mood === 'paused') return `<path d="M51 68 q4 2 8 0" stroke="${p.ink}" stroke-width="1.8" fill="none" stroke-linecap="round"/>`
73  return `<path d="M49 66.5 q6 5 12 0" stroke="${p.ink}" stroke-width="1.8" fill="none" stroke-linecap="round"/>
74    <path d="M51.2 67.6 l1.3 3.4 1.3-3 z" fill="#fff" stroke="${p.ink}" stroke-width=".5" stroke-linejoin="round"/>`
75}
76
77const GLOW: Record<Mood, string> = { working: PALETTE.green, waiting: PALETTE.orange, done: PALETTE.purple, idle: '', paused: '' }
78
79// A pulsing border in the mood's colour, so the state reads at a glance even when the avatar is small
80function frameGlow(mood: Mood) {
81  const color = GLOW[mood]
82  return color ? `<rect class="glow" x="2" y="2" width="106" height="106" rx="20" fill="none" stroke="${color}" stroke-width="4"/>` : ''
83}
84
85function effects(mood: Mood, frame: number) {
86  const twinkle = (i: number) => ((frame + i) % 4 === 0 ? 0.25 : 1)
87  const p = PALETTE
88  if (mood === 'working') {
89    return `<g class="spin"><circle cx="55" cy="58" r="44" fill="none" stroke="${p.green}" stroke-width="3" stroke-dasharray="10 14" stroke-linecap="round" opacity=".85"/></g>
90      <path class="spark" opacity="${twinkle(0)}" d="M14 28 l2.2 6 6 2.2 -6 2.2 -2.2 6 -2.2-6 -6-2.2 6-2.2z" fill="${p.gold}"/>
91      <path class="spark s2" opacity="${twinkle(1)}" d="M95 20 l1.8 4.6 4.6 1.8 -4.6 1.8 -1.8 4.6 -1.8-4.6 -4.6-1.8 4.6-1.8z" fill="${p.purple}"/>
92      <path class="spark s3" opacity="${twinkle(2)}" d="M98 74 l1.6 4 4 1.6 -4 1.6 -1.6 4 -1.6-4 -4-1.6 4-1.6z" fill="${p.green}"/>`
93  }
94  if (mood === 'waiting') {
95    return `<g class="bang"><circle cx="90" cy="22" r="15" fill="${p.orange}"/>
96      <rect x="88" y="12" width="4" height="12" rx="2" fill="${p.ink}"/><circle cx="90" cy="29" r="2.4" fill="${p.ink}"/></g>`
97  }
98  if (mood === 'done') {
99    return `<g class="pop"><circle cx="90" cy="22" r="14" fill="${p.green}"/>
100      <path d="M83 22 l5 5 9-10" stroke="${p.ink}" stroke-width="3.4" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>`
101  }
102  if (mood === 'paused') {
103    return `<text class="zz" x="84" y="30" font-family="system-ui,sans-serif" font-size="13" font-weight="700" fill="${p.purple}">z</text>
104      <text class="zz z2" x="92" y="20" font-family="system-ui,sans-serif" font-size="10" font-weight="700" fill="${p.purple}">z</text>`
105  }
106  return `<g class="fly"><g class="bat" transform="translate(90 26)">
107    <path d="M0 0 q-6-6-12-2 q4 1 4 5 q3-3 8-3z M0 0 q6-6 12-2 q-4 1-4 5 q-3-3-8-3z" fill="#6272a4"/>
108    <circle cx="0" cy="1" r="2.6" fill="#6272a4"/></g></g>`
109}
110
111export const FRAMES = 4
112
113// frame drives a static pose (bob, blink, pulse) so a surface that draws SVG as a still image can animate by redrawing
114export function avatarSvg(mood: Mood, size = 96, frame = 0) {
115  const p = PALETTE
116  const lift = [0, -1.5, -3, -1.5][frame % FRAMES] ?? 0
117  const blink = mood !== 'paused' && frame % FRAMES === 3 && Math.floor(frame / FRAMES) % 3 === 0
118  return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 110 110">
119<style>${STYLE}</style>
120<rect width="110" height="110" rx="22" fill="${p.ink}"/>
121${frameGlow(mood)}
122${effects(mood, frame)}
123<g transform="translate(0 ${lift})" class="${mood === 'working' ? 'busy' : ''}"><g class="bob">
124  <path class="cape" d="M22 76 Q55 64 88 76 L98 110 L12 110 Z" fill="${p.capeOut}"/>
125  <path d="M27 52 Q22 70 34 80 L46 74 Z M83 52 Q88 70 76 80 L64 74 Z" fill="${p.collar}"/>
126  <path d="M40 76 Q55 70 70 76 L74 110 L36 110 Z" fill="${p.ink}"/>
127  <path d="M46 75 L55 92 L64 75 Q55 79 46 75 Z" fill="#fff"/>
128  <path d="M49.5 82 L55 85 L60.5 82 L60.5 88 L55 85 L49.5 88 Z" fill="${p.capeIn}"/>
129  <circle cx="55" cy="85" r="1.6" fill="${p.capeIn}"/>
130  <path d="M30 54 L22 46 L32 50 Z M80 54 L88 46 L78 50 Z" fill="${p.skin}" stroke="${p.skinShade}" stroke-width="1" stroke-linejoin="round"/>
131  <ellipse cx="55" cy="56" rx="25" ry="23" fill="${p.skin}"/>
132  <ellipse cx="55" cy="66" rx="21" ry="10" fill="${p.skinShade}" opacity=".4"/>
133  <path d="M30 52 Q29 29 55 28 Q81 29 80 52 Q78 42 70 39 Q63 40 55 46 Q47 40 40 39 Q32 42 30 52 Z" fill="${p.hair}"/>
134  <path d="M41 33.5 Q52 29.5 63 32" stroke="${p.hairShine}" stroke-width="2.2" fill="none" stroke-linecap="round" opacity=".85"/>
135  <ellipse class="blush" cx="37" cy="63" rx="5" ry="3" fill="${p.blush}"/>
136  <ellipse class="blush" cx="73" cy="63" rx="5" ry="3" fill="${p.blush}"/>
137  ${eyes(mood, blink)}
138  ${mouth(mood)}
139</g></g>
140</svg>`
141}
142
types/index.d.ts 37 lines
1export type ChipTone = 'text' | 'muted' | 'ok' | 'warn' | 'bad' | 'info' | 'accent'
2export type ChipPart = { text: string; tone: ChipTone; bold?: boolean; action?: string }
3export type Chip = { icon: string; label: string; tone: ChipTone; parts: ChipPart[] }
4export type ChipPress = { plugin: string; action: string; at: number }
5
6export type GoalStatus = 'queued' | 'working' | 'waiting' | 'done'
7export type Goal = {
8  id: string
9  title: string
10  status: GoalStatus
11  notes: string[]
12  question: string
13  createdAt: number
14  updatedAt: number
15}
16export type Profile = { name: string; emoji: string; paused: boolean; scheduled: boolean; everyMinutes: number; briefing: string; seenAt: number; watch: boolean }
17export type RoundStatus = { state: 'idle' | 'running'; goal: string; summary: string; at: number }
18
19declare module 'claude-code' {
20  interface PluginState {
21    'mod-manager': { bar: number; press: ChipPress | null }
22    dot: {
23      active: boolean
24      chip: Chip | null
25      profile: Profile
26      goals: Goal[]
27      round: RoundStatus
28      isOpen: boolean
29      notice: { tone: 'ok' | 'error' | 'info'; text: string } | null
30      showSettings: boolean
31      chained: number
32      memory: { bullets: number; chars: number }
33      confirmClear: number
34    }
35  }
36}
37