sisyphi 1.1.13 → 1.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli/index.ts","../src/cli/commands/start.ts","../src/cli/install.ts","../src/cli/tmux-setup.ts","../src/cli/client.ts","../src/cli/tmux.ts","../src/cli/commands/dashboard.ts","../src/cli/commands/spawn.ts","../src/cli/stdin.ts","../src/cli/commands/submit.ts","../src/cli/commands/yield.ts","../src/cli/commands/complete.ts","../src/cli/commands/continue.ts","../src/cli/commands/status.ts","../src/cli/commands/list.ts","../src/cli/commands/report.ts","../src/cli/commands/resume.ts","../src/cli/commands/kill.ts","../src/cli/commands/uninstall.ts","../src/cli/commands/notify.ts","../src/cli/commands/message.ts","../src/cli/commands/update-task.ts","../src/cli/commands/rollback.ts","../src/cli/commands/restart-agent.ts","../src/cli/commands/setup-keybind.ts","../src/cli/commands/doctor.ts","../src/cli/onboard.ts","../src/cli/commands/companion-context.ts","../src/cli/commands/getting-started.ts","../src/cli/commands/init.ts","../src/cli/commands/setup.ts"],"sourcesContent":["const nodeVersion = parseInt(process.versions.node.split('.')[0]!, 10);\nif (nodeVersion < 22) {\n console.error(`Sisyphus requires Node.js v22+ (current: v${process.versions.node})`);\n process.exit(1);\n}\n\nimport { Command } from 'commander';\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { registerStart } from './commands/start.js';\nimport { registerSpawn } from './commands/spawn.js';\nimport { registerSubmit } from './commands/submit.js';\nimport { registerYield } from './commands/yield.js';\nimport { registerComplete } from './commands/complete.js';\nimport { registerContinue } from './commands/continue.js';\nimport { registerStatus } from './commands/status.js';\nimport { registerList } from './commands/list.js';\nimport { registerReport } from './commands/report.js';\nimport { registerResume } from './commands/resume.js';\nimport { registerKill } from './commands/kill.js';\nimport { registerUninstall } from './commands/uninstall.js';\nimport { registerNotify } from './commands/notify.js';\nimport { registerMessage } from './commands/message.js';\nimport { registerUpdateTask } from './commands/update-task.js';\nimport { registerDashboard } from './commands/dashboard.js';\nimport { registerRollback } from './commands/rollback.js';\nimport { registerRestartAgent } from './commands/restart-agent.js';\nimport { registerSetupKeybind } from './commands/setup-keybind.js';\nimport { registerDoctor } from './commands/doctor.js';\nimport { registerCompanionContext } from './commands/companion-context.js';\nimport { registerGettingStarted } from './commands/getting-started.js';\nimport { registerInit } from './commands/init.js';\nimport { registerSetup } from './commands/setup.js';\nimport { globalDir } from '../shared/paths.js';\n\nconst program = new Command();\n\nprogram\n .name('sisyphus')\n .description('tmux-integrated orchestration daemon for Claude Code')\n .version(\n JSON.parse(\n readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf-8'),\n ).version,\n );\n\nprogram.configureHelp({\n sortSubcommands: false,\n});\n\nregisterStart(program);\nregisterSpawn(program);\nregisterSubmit(program);\nregisterReport(program);\nregisterYield(program);\nregisterComplete(program);\nregisterContinue(program);\nregisterStatus(program);\nregisterList(program);\nregisterResume(program);\nregisterKill(program);\nregisterUninstall(program);\nregisterNotify(program);\nregisterMessage(program);\nregisterUpdateTask(program);\nregisterDashboard(program);\nregisterRollback(program);\nregisterRestartAgent(program);\nregisterSetupKeybind(program);\nregisterDoctor(program);\nregisterCompanionContext(program);\nregisterGettingStarted(program);\nregisterInit(program);\nregisterSetup(program);\n\nprogram.addHelpText('after', `\nExamples:\n $ sisyphus start \"Implement auth system\" Start a new session\n $ sisyphus start \"Build @requirements.md\" -n auth Start with a name and requirements reference\n $ sisyphus status Check current sessions\n $ sisyphus dashboard Open the TUI\n $ sisyphus doctor Verify installation\n\nRun 'sisyphus getting-started' for a complete usage guide.\n`);\n\n// Show welcome on first run (before ~/.sisyphus exists)\nconst args = process.argv.slice(2);\nconst firstArg = args[0];\nconst skipWelcome = ['doctor', 'getting-started', 'help', '--help', '-h', 'init', 'setup', 'uninstall', '--version', '-V'];\nif (!existsSync(globalDir()) && firstArg && !skipWelcome.includes(firstArg)) {\n mkdirSync(globalDir(), { recursive: true });\n console.log('');\n console.log(\" Welcome to Sisyphus. Run 'sisyphus setup' to get started.\");\n console.log('');\n}\n\nprogram.parseAsync(process.argv).catch((err: Error) => {\n console.error(err.message);\n process.exit(1);\n});\n","import type { Command } from 'commander';\nimport { execSync } from 'node:child_process';\nimport { sendRequest } from '../client.js';\nimport { getTmuxSession, isTmuxInstalled } from '../tmux.js';\nimport { shellQuote } from '../../shared/shell.js';\nimport { openDashboardWindow } from './dashboard.js';\nimport type { Request } from '../../shared/protocol.js';\n\n\nexport function registerStart(program: Command): void {\n program\n .command('start')\n .description('Start a new sisyphus session')\n .argument('<task>', 'Task description for the orchestrator')\n .option('-c, --context <context>', 'Background context for the orchestrator')\n .option('-n, --name <name>', 'Human-readable name for the session')\n .option('--no-tmux-check', 'Skip the tmux session check')\n .action(async (task: string, opts: { context?: string; name?: string; tmuxCheck?: boolean }) => {\n const cwd = process.env['SISYPHUS_CWD'] ?? process.cwd();\n\n if (!process.env['TMUX'] && opts.tmuxCheck !== false) {\n if (!isTmuxInstalled()) {\n console.error('Error: tmux is not installed. Sisyphus requires tmux for agent panes.');\n console.error(' Install: brew install tmux (macOS) or apt install tmux (Linux)');\n console.error(' Then: tmux new-session');\n process.exit(1);\n }\n console.error('Error: Not running inside a tmux session.');\n console.error(' Sisyphus uses tmux to manage agent panes.');\n console.error(' Start a tmux session first: tmux new-session');\n console.error('');\n console.error(' To skip this check: sisyphus start --no-tmux-check \"task\"');\n process.exit(1);\n }\n const request: Request = { type: 'start', task, context: opts.context, cwd, name: opts.name };\n const response = await sendRequest(request);\n if (response.ok) {\n const sessionId = response.data?.sessionId as string;\n const tmuxSessionName = response.data?.tmuxSessionName as string | undefined;\n // Tag the user's current tmux session so it's part of the same cycle group\n if (process.env['TMUX']) {\n try {\n execSync(`tmux set-option @sisyphus_cwd ${shellQuote(cwd)}`, { stdio: 'ignore' });\n } catch { /* not in tmux or tmux error — ignore */ }\n\n try {\n const tmuxSession = getTmuxSession();\n if (openDashboardWindow(tmuxSession, cwd)) {\n console.log(`Dashboard opened in tmux window \"sisyphus-dashboard\"`);\n }\n } catch { /* dashboard launch failed — non-fatal */ }\n }\n\n console.log(`Task handed off to sisyphus orchestrator (session ${sessionId})`);\n console.log(`The orchestrator and its agents will handle this task autonomously — no further action needed from you.`);\n\n if (tmuxSessionName) {\n console.log(`\\nTmux session: ${tmuxSessionName}`);\n console.log(` tmux attach -t ${tmuxSessionName}`);\n }\n\n console.log(`\\nMonitor:`);\n console.log(` sisyphus status ${sessionId} # agents, cycles, reports`);\n console.log(` tail -f ~/.sisyphus/daemon.log # daemon activity`);\n console.log(`\\nControl:`);\n console.log(` sisyphus resume ${sessionId} \"new instructions\" # respawn with follow-up`);\n console.log(` sisyphus kill ${sessionId} # stop all agents and orchestrator`);\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { connect } from 'node:net';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { daemonLogPath, daemonUpdatingPath, globalDir, socketPath } from '../shared/paths.js';\nimport { type SetupResult, removeTmuxKeybind, setupTmuxKeybind } from './tmux-setup.js';\n\nconst PLIST_LABEL = 'com.sisyphus.daemon';\nconst PLIST_FILENAME = `${PLIST_LABEL}.plist`;\n\nfunction launchAgentDir(): string {\n return join(homedir(), 'Library', 'LaunchAgents');\n}\n\nfunction plistPath(): string {\n return join(launchAgentDir(), PLIST_FILENAME);\n}\n\nfunction daemonBinPath(): string {\n // In bundled output, cli.js and daemon.js are siblings in dist/\n const installDir = dirname(fileURLToPath(import.meta.url));\n return resolve(installDir, 'daemon.js');\n}\n\nfunction generatePlist(nodePath: string, daemonPath: string, logPath: string): string {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${PLIST_LABEL}</string>\n <key>ProgramArguments</key>\n <array>\n <string>${nodePath}</string>\n <string>${daemonPath}</string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>StandardOutPath</key>\n <string>${logPath}</string>\n <key>StandardErrorPath</key>\n <string>${logPath}</string>\n</dict>\n</plist>\n`;\n}\n\nexport function isInstalled(): boolean {\n return existsSync(plistPath());\n}\n\nexport async function ensureDaemonInstalled(): Promise<void> {\n if (process.platform !== 'darwin') return;\n\n if (!isInstalled()) {\n const nodePath = process.execPath;\n const daemonPath = daemonBinPath();\n const logPath = daemonLogPath();\n\n mkdirSync(globalDir(), { recursive: true });\n mkdirSync(launchAgentDir(), { recursive: true });\n\n const plist = generatePlist(nodePath, daemonPath, logPath);\n writeFileSync(plistPath(), plist, 'utf8');\n\n execSync(`launchctl load -w ${plistPath()}`);\n\n const keybindResult = setupTmuxKeybind();\n\n printGettingStarted(keybindResult);\n }\n\n await waitForDaemon();\n}\n\nexport async function uninstallDaemon(purge: boolean): Promise<void> {\n if (process.platform !== 'darwin') {\n console.log('Auto-install is only supported on macOS.');\n return;\n }\n\n const plist = plistPath();\n if (existsSync(plist)) {\n try {\n execSync(`launchctl unload -w ${plist}`, { stdio: 'pipe' });\n } catch {\n // already unloaded or not registered — ignore\n }\n unlinkSync(plist);\n console.log('Daemon unloaded and plist removed.');\n } else {\n console.log('Daemon is not installed (plist not found).');\n }\n\n removeTmuxKeybind();\n\n if (purge) {\n const dir = globalDir();\n if (existsSync(dir)) {\n rmSync(dir, { recursive: true, force: true });\n console.log(`Removed ${dir}`);\n }\n }\n}\n\nfunction printGettingStarted(keybindResult: SetupResult): void {\n const lines = [\n '',\n 'Sisyphus installed — daemon running via launchd.',\n '',\n ];\n\n if (keybindResult.status === 'installed') {\n lines.push(`Tmux keybind: ${keybindResult.message}`, '');\n } else if (keybindResult.status === 'conflict') {\n lines.push(`Keybind: ${keybindResult.message}`, '');\n }\n\n lines.push(\n 'Run `sisyphus getting-started` for a complete usage guide.',\n '',\n );\n\n console.log(lines.join('\\n'));\n}\n\nfunction testConnection(): Promise<void> {\n return new Promise((resolve, reject) => {\n const sock = connect(socketPath());\n sock.on('connect', () => { sock.destroy(); resolve(); });\n sock.on('error', (err) => { sock.destroy(); reject(err); });\n });\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function waitForDaemon(maxWaitMs = 6000): Promise<void> {\n const start = Date.now();\n let updatingLogged = false;\n\n while (Date.now() - start < maxWaitMs) {\n // Extend timeout if daemon is updating\n const updatingPath = daemonUpdatingPath();\n if (existsSync(updatingPath)) {\n if (!updatingLogged) {\n try {\n const version = readFileSync(updatingPath, 'utf-8').trim();\n console.log(`Updating sisyphus to ${version}...`);\n } catch {\n console.log('Updating sisyphus...');\n }\n updatingLogged = true;\n }\n maxWaitMs = Math.max(maxWaitMs, 30000);\n }\n\n if (existsSync(socketPath())) {\n try {\n await testConnection();\n return;\n } catch {\n // not ready yet\n }\n }\n await sleep(300);\n }\n throw new Error(`Daemon did not start within ${maxWaitMs}ms. Check ${daemonLogPath()}`);\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, unlinkSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { globalDir } from '../shared/paths.js';\n\nexport const DEFAULT_KEY = 'M-s';\nexport const DEFAULT_HOME_KEY = 'M-S';\n\nconst SISYPHUS_CONF_MARKER = '# sisyphus-managed — do not edit';\n\nexport function cycleScriptPath(): string {\n return join(globalDir(), 'bin', 'sisyphus-cycle');\n}\n\nexport function homeScriptPath(): string {\n return join(globalDir(), 'bin', 'sisyphus-home');\n}\n\nexport function killPaneScriptPath(): string {\n return join(globalDir(), 'bin', 'sisyphus-kill-pane');\n}\n\nexport function sisyphusTmuxConfPath(): string {\n return join(globalDir(), 'tmux.conf');\n}\n\nfunction userTmuxConfPath(): string | null {\n // Check both standard locations, preferring whichever exists\n const dotfile = join(homedir(), '.tmux.conf');\n const xdg = join(homedir(), '.config', 'tmux', 'tmux.conf');\n if (existsSync(xdg)) return xdg;\n if (existsSync(dotfile)) return dotfile;\n return null;\n}\n\nconst CYCLE_SCRIPT = `#!/bin/bash\ncwd=$(tmux show-option -v @sisyphus_cwd 2>/dev/null)\n[ -z \"$cwd\" ] && exit 0\ncurrent=$(tmux display-message -p '#{session_name}')\nsessions=()\nwhile IFS= read -r name; do\n scwd=$(tmux show-option -t \"$name\" -v @sisyphus_cwd 2>/dev/null)\n [ \"$scwd\" = \"$cwd\" ] && sessions+=(\"$name\")\ndone < <(tmux list-sessions -F '#{session_name}')\n(( \\${#sessions[@]} <= 1 )) && exit 0\nfor (( i=0; i<\\${#sessions[@]}; i++ )); do\n if [ \"\\${sessions[$i]}\" = \"$current\" ]; then\n next=$(( (i + 1) % \\${#sessions[@]} ))\n tmux switch-client -t \"\\${sessions[$next]}\"\n exit 0\n fi\ndone\ntmux switch-client -t \"\\${sessions[0]}\"\n`;\n\nconst HOME_SCRIPT = `#!/bin/bash\n# Jump to the home (non-sisyphus) session that has the dashboard window\ncwd=$(tmux show-option -v @sisyphus_cwd 2>/dev/null)\n[ -z \"$cwd\" ] && exit 0\nwhile IFS= read -r name; do\n # Skip sisyphus agent/orchestrator sessions\n case \"$name\" in sisyphus-*) continue ;; esac\n scwd=$(tmux show-option -t \"$name\" -v @sisyphus_cwd 2>/dev/null)\n if [ \"$scwd\" = \"$cwd\" ]; then\n tmux switch-client -t \"$name\"\n # Focus the dashboard window by stored ID (not name)\n dwid=$(tmux show-option -t \"$name\" -v @sisyphus_dashboard 2>/dev/null)\n [ -n \"$dwid\" ] && tmux select-window -t \"$dwid\" 2>/dev/null\n exit 0\n fi\ndone < <(tmux list-sessions -F '#{session_name}')\n`;\n\nconst KILL_PANE_SCRIPT = `#!/bin/bash\n# prefix-x override for sisyphus sessions.\n# If this is the last pane, switch to the home session before killing.\nsession=$(tmux display-message -p '#{session_name}')\npane_count=$(tmux list-panes -t \"$session\" -F '#{pane_id}' | wc -l | tr -d ' ')\n\nif [ \"$pane_count\" -le 1 ]; then\n # Last pane — find home session, switch there, then kill sisyphus session\n cwd=$(tmux show-option -t \"$session\" -v @sisyphus_cwd 2>/dev/null)\n if [ -n \"$cwd\" ]; then\n while IFS= read -r name; do\n case \"$name\" in sisyphus-*) continue ;; esac\n scwd=$(tmux show-option -t \"$name\" -v @sisyphus_cwd 2>/dev/null)\n if [ \"$scwd\" = \"$cwd\" ]; then\n tmux switch-client -t \"$name\"\n dwid=$(tmux show-option -t \"$name\" -v @sisyphus_dashboard 2>/dev/null)\n [ -n \"$dwid\" ] && tmux select-window -t \"$dwid\" 2>/dev/null\n tmux kill-session -t \"$session\"\n exit 0\n fi\n done < <(tmux list-sessions -F '#{session_name}')\n fi\n # No home session found — just kill the pane\n tmux kill-pane\nelse\n # Multiple panes — kill this one and rebalance\n tmux kill-pane\n tmux select-layout even-horizontal\nfi\n`;\n\nexport function installCycleScript(): void {\n mkdirSync(join(globalDir(), 'bin'), { recursive: true });\n const scriptPath = cycleScriptPath();\n writeFileSync(scriptPath, CYCLE_SCRIPT, 'utf8');\n chmodSync(scriptPath, 0o755);\n}\n\nexport function installHomeScript(): void {\n mkdirSync(join(globalDir(), 'bin'), { recursive: true });\n const scriptPath = homeScriptPath();\n writeFileSync(scriptPath, HOME_SCRIPT, 'utf8');\n chmodSync(scriptPath, 0o755);\n}\n\nexport function installKillPaneScript(): void {\n mkdirSync(join(globalDir(), 'bin'), { recursive: true });\n const scriptPath = killPaneScriptPath();\n writeFileSync(scriptPath, KILL_PANE_SCRIPT, 'utf8');\n chmodSync(scriptPath, 0o755);\n}\n\nexport function getExistingBinding(key: string): string | null {\n try {\n const output = execSync('tmux list-keys', { stdio: ['pipe', 'pipe', 'pipe'] }).toString();\n for (const line of output.split('\\n')) {\n // lines look like: bind-key -T root M-s run-shell ...\n // or: bind-key -T root M-s run-shell ...\n if (line.includes(key)) {\n const parts = line.trim().split(/\\s+/);\n // Find the key in parts and check it matches exactly (not as substring of another key)\n const keyIdx = parts.indexOf(key);\n if (keyIdx !== -1) {\n return line.trim();\n }\n }\n }\n return null;\n } catch {\n // tmux not running or not available\n return null;\n }\n}\n\nexport function isSisyphusBinding(binding: string): boolean {\n return binding.includes('sisyphus');\n}\n\nexport type SetupResult =\n | { status: 'installed'; message: string }\n | { status: 'already-installed'; message: string }\n | { status: 'conflict'; message: string; existingBinding: string };\n\nexport function setupTmuxKeybind(key: string = DEFAULT_KEY, homeKey: string = DEFAULT_HOME_KEY): SetupResult {\n installCycleScript();\n installHomeScript();\n installKillPaneScript();\n\n // Check for existing binding before writing anything\n const existing = getExistingBinding(key);\n if (existing !== null && !isSisyphusBinding(existing)) {\n return {\n status: 'conflict',\n message: `Tmux key ${key} is already bound to something else. Run \"sisyphus setup-keybind <key>\" to use a different key.`,\n existingBinding: existing,\n };\n }\n\n // Check home key for conflicts too (only if different from cycle key)\n if (homeKey !== key) {\n const existingHome = getExistingBinding(homeKey);\n if (existingHome !== null && !isSisyphusBinding(existingHome)) {\n return {\n status: 'conflict',\n message: `Tmux key ${homeKey} is already bound to something else.`,\n existingBinding: existingHome,\n };\n }\n }\n\n // Write ~/.sisyphus/tmux.conf with keybindings + prefix-x override\n const confPath = sisyphusTmuxConfPath();\n const cycleBinding = `bind-key -T root ${key} run-shell ${cycleScriptPath()}`;\n const homeBinding = `bind-key -T root ${homeKey} run-shell ${homeScriptPath()}`;\n const killPaneOverride = `bind-key -T prefix x if-shell \"tmux display-message -p '#{session_name}' | grep -q '^sisyphus-'\" \"run-shell ${killPaneScriptPath()}\" \"kill-pane \\\\; select-layout even-horizontal\"`;\n writeFileSync(confPath, `${SISYPHUS_CONF_MARKER}\\n${cycleBinding}\\n${homeBinding}\\n${killPaneOverride}\\n`, 'utf8');\n\n // Append source line to tmux.conf if not already there\n const userConf = userTmuxConfPath();\n const sourceLine = `source-file ${confPath}`;\n const markedSourceLine = `${sourceLine} ${SISYPHUS_CONF_MARKER}`;\n let persistedToConf = false;\n\n if (userConf !== null) {\n const contents = readFileSync(userConf, 'utf8');\n if (!contents.includes(confPath)) {\n const separator = contents.endsWith('\\n') ? '' : '\\n';\n writeFileSync(userConf, `${contents}${separator}${markedSourceLine}\\n`, 'utf8');\n }\n persistedToConf = true;\n }\n\n // Apply bindings live if tmux is running\n try {\n execSync(`tmux bind-key -T root ${key} run-shell ${cycleScriptPath()}`, { stdio: 'pipe' });\n execSync(`tmux bind-key -T root ${homeKey} run-shell ${homeScriptPath()}`, { stdio: 'pipe' });\n execSync(`tmux ${killPaneOverride}`, { stdio: 'pipe' });\n } catch {\n // tmux not running — bindings will take effect on next session start\n }\n\n if (existing !== null && isSisyphusBinding(existing)) {\n return {\n status: 'already-installed',\n message: `Tmux keybindings ${key} (cycle) and ${homeKey} (dashboard) already configured for sisyphus.`,\n };\n }\n\n const persistNote = persistedToConf\n ? ''\n : `\\nNote: No tmux.conf found. Add this to your tmux config for persistence:\\n source-file ${confPath}`;\n return {\n status: 'installed',\n message: `Tmux keybindings set: ${key} cycles sessions, ${homeKey} jumps to dashboard${persistNote}`,\n };\n}\n\nexport function removeTmuxKeybind(): void {\n // Remove source line from user's tmux.conf\n const confPath = sisyphusTmuxConfPath();\n // Check both possible tmux.conf locations\n for (const candidate of [join(homedir(), '.tmux.conf'), join(homedir(), '.config', 'tmux', 'tmux.conf')]) {\n if (existsSync(candidate)) {\n const contents = readFileSync(candidate, 'utf8');\n const filtered = contents\n .split('\\n')\n .filter((line) => !line.includes(confPath))\n .join('\\n');\n if (filtered !== contents) {\n writeFileSync(candidate, filtered, 'utf8');\n }\n }\n }\n\n // Remove ~/.sisyphus/tmux.conf\n if (existsSync(confPath)) {\n unlinkSync(confPath);\n }\n\n // Restore default prefix-x binding if tmux is running\n try {\n execSync('tmux bind-key -T prefix x kill-pane \\\\; select-layout even-horizontal', { stdio: 'pipe' });\n } catch {\n // tmux not running\n }\n\n // Remove scripts\n for (const scriptPath of [cycleScriptPath(), homeScriptPath(), killPaneScriptPath()]) {\n if (existsSync(scriptPath)) {\n unlinkSync(scriptPath);\n }\n }\n}\n","import type { Request, Response } from '../shared/protocol.js';\nimport { rawSend as sharedRawSend } from '../shared/client.js';\nimport { ensureDaemonInstalled, waitForDaemon } from './install.js';\n\nexport function rawSend(request: Request): Promise<Response> {\n return sharedRawSend(request, 10_000);\n}\n\nexport async function sendRequest(request: Request): Promise<Response> {\n const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n const MAX_ATTEMPTS = 5;\n const RETRY_DELAY_MS = 2000;\n let installedDaemon = false;\n let lastErr: unknown;\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n try {\n return await rawSend(request);\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT' && code !== 'ECONNREFUSED') {\n throw err;\n }\n\n if (attempt === MAX_ATTEMPTS) break;\n\n if (process.platform === 'darwin' && !installedDaemon) {\n installedDaemon = true;\n await ensureDaemonInstalled();\n await waitForDaemon(5000);\n } else {\n process.stderr.write(`Daemon not ready, retrying (${attempt}/${MAX_ATTEMPTS - 1})...\\n`);\n await sleep(RETRY_DELAY_MS);\n }\n }\n }\n\n if (process.platform !== 'darwin') {\n const lines = [`Sisyphus daemon is not running.`];\n if (process.platform === 'linux') {\n lines.push(\n '',\n ' Start options:',\n ' sisyphusd & # Run in background',\n ' nohup sisyphusd > ~/.sisyphus/daemon.log 2>&1 & # Persist after logout',\n '',\n ' For systemd (recommended):',\n ' # Create ~/.config/systemd/user/sisyphus.service with:',\n ' # [Unit]',\n ' # Description=Sisyphus Daemon',\n ' # [Service]',\n ' # ExecStart=/usr/bin/env node <path-to-sisyphusd>',\n ' # Restart=always',\n ' # [Install]',\n ' # WantedBy=default.target',\n ' systemctl --user enable --now sisyphus',\n );\n } else {\n lines.push(\n '',\n ' Start it manually: sisyphusd &',\n );\n }\n lines.push(\n '',\n ' Diagnose: sisyphus doctor',\n ' Logs: tail -f ~/.sisyphus/daemon.log',\n );\n throw new Error(lines.join('\\n'));\n }\n throw lastErr;\n}\n","import { execSync } from 'node:child_process';\n\nexport function isTmuxInstalled(): boolean {\n try {\n execSync('which tmux', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nexport function assertTmux(): void {\n if (!process.env.TMUX) {\n throw new Error('Not running inside a tmux pane. Sisyphus requires tmux.');\n }\n}\n\nexport function getTmuxSession(): string {\n assertTmux();\n return execSync('tmux display-message -p \"#{session_name}\"', { encoding: 'utf8' }).trim();\n}\n\n","import type { Command } from 'commander';\nimport { join } from 'node:path';\nimport { execSync } from 'node:child_process';\nimport { assertTmux, getTmuxSession } from '../tmux.js';\nimport { shellQuote } from '../../shared/shell.js';\n\n\n/**\n * Opens the dashboard in a new tmux window (for background use, e.g. from `start`).\n *\n * Tracks the window by its tmux window ID stored in the @sisyphus_dashboard\n * session option — not by window name, which is fragile (renames, collisions).\n * The \"; exit\" suffix closes the window when the TUI exits.\n *\n * Returns true if a new dashboard was created, false if an existing one was focused.\n */\nexport function openDashboardWindow(tmuxSession: string, cwd: string): boolean {\n // Check for existing dashboard by stored window ID\n try {\n const storedId = execSync(\n `tmux show-option -t ${shellQuote(tmuxSession)} -v @sisyphus_dashboard`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] },\n ).trim();\n\n if (storedId) {\n try {\n execSync(\n `tmux display-message -t ${shellQuote(storedId)} -p \"#{window_id}\"`,\n { stdio: 'pipe' },\n );\n execSync(`tmux select-window -t ${shellQuote(storedId)}`, { stdio: 'pipe' });\n return false;\n } catch {\n // Window is gone — fall through to create a new one\n }\n }\n } catch {\n // Option not set — fall through to create\n }\n\n const tuiPath = join(import.meta.dirname, 'tui.js');\n\n const windowId = execSync(\n `tmux new-window -n \"sisyphus-dashboard\" -c ${shellQuote(cwd)} -P -F \"#{window_id}\"`,\n { encoding: 'utf-8' },\n ).trim();\n\n const cmd = `node ${shellQuote(tuiPath)} --cwd ${shellQuote(cwd)}; exit`;\n execSync(\n `tmux send-keys -t ${shellQuote(windowId)} ${shellQuote(cmd)} Enter`,\n );\n\n execSync(\n `tmux set-option -t ${shellQuote(tmuxSession)} @sisyphus_dashboard ${shellQuote(windowId)}`,\n { stdio: 'pipe' },\n );\n\n return true;\n}\n\nexport function registerDashboard(program: Command): void {\n program\n .command('dashboard')\n .description('Launch the TUI dashboard for monitoring and managing sessions')\n .action(async () => {\n assertTmux();\n const tuiPath = join(import.meta.dirname, 'tui.js');\n execSync(`node ${shellQuote(tuiPath)} --cwd ${shellQuote(process.cwd())}`, {\n stdio: 'inherit',\n });\n });\n}\n","import type { Command } from 'commander';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { readStdin } from '../stdin.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerSpawn(program: Command): void {\n program\n .command('spawn')\n .description('Spawn a new agent (orchestrator only)')\n .argument('[instruction]', 'Task instruction for the agent')\n .option('--agent-type <type>', 'Agent role label (default: worker)', 'worker')\n .requiredOption('--name <name>', 'Agent name')\n .option('--instruction <instruction>', 'Task instruction for the agent (or pipe via stdin)')\n .option('--repo <name>', 'Repo subdirectory to use for this agent')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (positionalInstruction: string | undefined, opts: { agentType: string; name: string; instruction?: string; repo?: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const instruction = opts.instruction ?? positionalInstruction ?? await readStdin();\n if (!instruction) {\n console.error('Error: --instruction is required (or pipe via stdin)');\n process.exit(1);\n }\n\n const sisyphusCwd = process.env['SISYPHUS_CWD'] ?? process.cwd();\n\n if (opts.repo && (opts.repo.includes('/') || opts.repo.includes('..') || opts.repo.includes('\\\\'))) {\n console.error('Error: --repo must be a directory name, not a path');\n process.exit(1);\n }\n\n if (opts.repo && opts.repo !== '.') {\n const repoPath = join(sisyphusCwd, opts.repo);\n if (!existsSync(repoPath)) {\n console.error(`Error: repo directory does not exist: ${repoPath}`);\n process.exit(1);\n }\n }\n\n const request: Request = {\n type: 'spawn',\n sessionId,\n agentType: opts.agentType,\n name: opts.name,\n instruction,\n ...(opts.repo ? { repo: opts.repo } : {}),\n };\n const response = await sendRequest(request);\n if (response.ok) {\n const agentId = response.data?.agentId as string;\n console.log(`Agent spawned: ${agentId}`);\n console.log(\"Run `sisyphus yield` when done spawning agents.\");\n } else {\n console.error(`Error: ${response.error}`);\n if (response.error?.includes(\"Unknown session\")) console.error(\"Hint: run `sisyphus list` to see active sessions.\");\n process.exit(1);\n }\n });\n}\n","export function readStdin(): Promise<string | null> {\n if (process.stdin.isTTY) return Promise.resolve(null);\n\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk: Buffer) => chunks.push(chunk));\n process.stdin.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf-8').trim();\n resolve(text || null);\n });\n process.stdin.on('error', reject);\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { readStdin } from '../stdin.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerSubmit(program: Command): void {\n program\n .command('submit')\n .description('Submit work report and exit (agent only)')\n .option('--report <report>', 'Work report (or pipe via stdin)')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { report?: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n const agentId = process.env.SISYPHUS_AGENT_ID;\n if (!sessionId || !agentId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID (and SISYPHUS_AGENT_ID) environment variables');\n process.exit(1);\n }\n\n const report = opts.report ?? await readStdin();\n if (!report) {\n console.error('Error: provide --report or pipe content via stdin');\n process.exit(1);\n }\n\n const request: Request = { type: 'submit', sessionId, agentId, report };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Report submitted successfully');\n console.log('Your pane will close. The orchestrator resumes when all agents finish.');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { readStdin } from '../stdin.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerYield(program: Command): void {\n program\n .command('yield')\n .description('Yield control back to daemon (orchestrator only)')\n .option('--prompt <text>', 'Instructions for the next orchestrator cycle (or pipe via stdin)')\n .option('--mode <mode>', 'System prompt mode for next cycle (planning, implementation, validation)')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { prompt?: string; mode?: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const nextPrompt = opts.prompt ?? await readStdin() ?? undefined;\n\n const request: Request = { type: 'yield', sessionId, agentId: 'orchestrator', nextPrompt, mode: opts.mode };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Yielded. Waiting for agents to complete.');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerComplete(program: Command): void {\n program\n .command('complete')\n .description('Mark session as completed (orchestrator only)')\n .requiredOption('--report <report>', 'Final completion report')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { report: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const request: Request = { type: 'complete', sessionId, report: opts.report };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Session completed.');\n console.log(`\\nTo keep working in this session:`);\n console.log(` sisyphus continue # reactivate session and clear roadmap for new work`);\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerContinue(program: Command): void {\n program\n .command('continue')\n .description('Clear roadmap and continue working on a completed session (stays in current cycle)')\n .addHelpText('after', '\\n Use `continue` when a session completed but you want to add more work.\\n Use `resume` when you want to restart with specific new instructions.\\n')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const request: Request = { type: 'continue', sessionId };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Session reactivated. Roadmap cleared.');\n console.log('\\nThe previous roadmap has been wiped — you are starting fresh.');\n console.log('Consider writing a new roadmap before spawning agents.');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport type { Session, Agent, OrchestratorCycle } from '../../shared/types.js';\nimport { computeActiveTimeMs } from '../../shared/utils.js';\nimport { roadmapPath, cycleLogPath } from '../../shared/paths.js';\nimport { formatDuration, statusColor } from '../../shared/format.js';\n\nconst COLOR_CODES: Record<string, string> = {\n green: '\\x1b[32m', yellow: '\\x1b[33m', cyan: '\\x1b[36m',\n red: '\\x1b[31m', gray: '\\x1b[90m', white: '\\x1b[37m',\n};\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\n\nfunction colorize(text: string, status: string): string {\n const colorName = statusColor(status);\n const code = COLOR_CODES[colorName];\n if (!code) return `${text}\\x1b[0m`;\n return `${code}${text}\\x1b[0m`;\n}\n\nfunction inferOrchestratorPhase(session: Session): string {\n const cycles = session.orchestratorCycles;\n if (cycles.length === 0) return 'planning';\n const lastCycle = cycles[cycles.length - 1];\n\n if (!lastCycle.completedAt) {\n // Orchestrator pane is alive\n const elapsed = Date.now() - new Date(lastCycle.timestamp).getTime();\n if (elapsed < 5000 || lastCycle.agentsSpawned.length === 0) return 'planning';\n return 'spawning';\n } else {\n // Orchestrator yielded\n const runningAgents = session.agents.filter(\n a => lastCycle.agentsSpawned.includes(a.id) && a.status === 'running'\n );\n if (runningAgents.length > 0) {\n return `waiting on ${runningAgents.map(a => a.id).join(', ')}`;\n }\n return 'starting';\n }\n}\n\nfunction formatAgent(agent: Agent, verbose: boolean): string {\n const status = colorize(agent.status, agent.status);\n const name = `${BOLD}${agent.name}${RESET}`;\n const type = `${DIM}(${agent.agentType})${RESET}`;\n const duration = formatDuration(agent.activeMs);\n let line = ` ${agent.id} ${name} ${type} — ${status} ${DIM}(${duration})${RESET}`;\n if (verbose && agent.instruction) {\n const truncated = agent.instruction.length > 200 ? agent.instruction.slice(0, 200) + '...' : agent.instruction;\n line += `\\n ${DIM}Instruction: ${truncated}${RESET}`;\n }\n if (agent.reports.length > 0) {\n for (const r of agent.reports) {\n const label = r.type === 'final' ? 'Final' : 'Update';\n line += `\\n ${label}: ${r.summary}`;\n }\n }\n if (agent.killedReason) {\n line += `\\n Reason: ${agent.killedReason}`;\n }\n return line;\n}\n\nfunction formatCycle(cycle: OrchestratorCycle, phase?: string): string {\n let duration: string;\n if (cycle.completedAt) {\n duration = ` ${DIM}(${formatDuration(cycle.activeMs)})${RESET}`;\n } else {\n const elapsed = formatDuration(cycle.activeMs);\n duration = ` ${DIM}(running, ${elapsed})${RESET}`;\n }\n const agents = cycle.agentsSpawned.length > 0\n ? ` — agents: ${cycle.agentsSpawned.join(', ')}`\n : '';\n const phaseStr = phase ? ` — orchestrator: ${phase}` : '';\n return ` Cycle ${cycle.cycle}${duration}${agents}${phaseStr}`;\n}\n\nfunction computeLastActivity(session: Session): Date | null {\n const timestamps: number[] = [];\n\n for (const cycle of session.orchestratorCycles) {\n timestamps.push(new Date(cycle.timestamp).getTime());\n if (cycle.completedAt) timestamps.push(new Date(cycle.completedAt).getTime());\n }\n\n for (const agent of session.agents) {\n timestamps.push(new Date(agent.spawnedAt).getTime());\n if (agent.completedAt) timestamps.push(new Date(agent.completedAt).getTime());\n for (const r of agent.reports) {\n timestamps.push(new Date(r.timestamp).getTime());\n }\n }\n\n if (timestamps.length === 0) return null;\n return new Date(Math.max(...timestamps));\n}\n\nfunction readRoadmap(cwd: string, sessionId: string): string | null {\n try {\n return readFileSync(roadmapPath(cwd, sessionId), 'utf8');\n } catch {\n return null;\n }\n}\n\nfunction readCycleLog(cwd: string, sessionId: string, cycle: number): string | null {\n try {\n const path = cycleLogPath(cwd, sessionId, cycle);\n if (!existsSync(path)) return null;\n return readFileSync(path, 'utf8');\n } catch {\n return null;\n }\n}\n\nfunction capturePaneOutput(paneId: string, lines: number = 50): string | null {\n try {\n return execSync(\n `tmux capture-pane -t \"${paneId}\" -p -S -${lines}`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] },\n ).trimEnd();\n } catch {\n return null;\n }\n}\n\nfunction printSession(session: Session, verbose: boolean): void {\n const status = colorize(session.status, session.status);\n const sessionDuration = formatDuration(session.createdAt, session.completedAt);\n console.log(`\\n${BOLD}Session: ${session.id}${RESET}`);\n console.log(` Status: ${status}`);\n console.log(` Task: ${session.task}`);\n if (session.context) {\n const truncated = !verbose && session.context.length > 120 ? session.context.slice(0, 120) + '...' : session.context;\n console.log(` Context: ${truncated}`);\n }\n console.log(` CWD: ${session.cwd}`);\n console.log(` Created: ${session.createdAt}`);\n const activeTime = formatDuration(computeActiveTimeMs(session));\n console.log(` Duration: ${sessionDuration}${session.completedAt ? '' : ' (ongoing)'} (${activeTime} active)`);\n\n const lastActivity = computeLastActivity(session);\n if (lastActivity) {\n console.log(` Last activity: ${formatDuration(Date.now() - lastActivity.getTime())} ago`);\n }\n\n console.log(` Orchestrator cycles: ${session.orchestratorCycles.length}`);\n\n // Active agents block\n const runningAgents = session.agents.filter(a => a.status === 'running');\n if (runningAgents.length > 0) {\n console.log(`\\n${BOLD}Active agents (${runningAgents.length}):${RESET}`);\n for (const agent of runningAgents) {\n const name = `${BOLD}${agent.name}${RESET}`;\n const type = `${DIM}(${agent.agentType})${RESET}`;\n const duration = formatDuration(agent.activeMs);\n console.log(` ${agent.id} ${name} ${type} running ${duration}`);\n if (verbose && agent.instruction) {\n const truncated = agent.instruction.length > 200 ? agent.instruction.slice(0, 200) + '...' : agent.instruction;\n console.log(` ${DIM}Instruction: ${truncated}${RESET}`);\n }\n }\n }\n\n // Roadmap\n const roadmap = readRoadmap(session.cwd, session.id);\n if (roadmap) {\n console.log(`\\n${BOLD}Roadmap:${RESET}`);\n console.log(roadmap);\n }\n\n if (session.orchestratorCycles.length > 0) {\n console.log(`\\n ${BOLD}Cycles:${RESET}`);\n const cycles = session.orchestratorCycles;\n for (let i = 0; i < cycles.length; i++) {\n const isLast = i === cycles.length - 1;\n const phase = isLast && session.status === 'active' ? inferOrchestratorPhase(session) : undefined;\n console.log(formatCycle(cycles[i], phase));\n\n // Verbose: show cycle log\n if (verbose) {\n const log = readCycleLog(session.cwd, session.id, cycles[i].cycle);\n if (log) {\n const lines = log.split('\\n');\n const preview = lines.slice(0, 20).join('\\n');\n console.log(` ${DIM}--- cycle log ---${RESET}`);\n for (const line of preview.split('\\n')) {\n console.log(` ${DIM}${line}${RESET}`);\n }\n if (lines.length > 20) {\n console.log(` ${DIM}... (${lines.length - 20} more lines)${RESET}`);\n }\n }\n }\n }\n }\n\n if (session.agents.length > 0) {\n console.log(`\\n ${BOLD}Agents:${RESET}`);\n for (const agent of session.agents) {\n console.log(formatAgent(agent, verbose));\n }\n }\n\n // Verbose: capture live pane output\n if (verbose) {\n // Orchestrator pane (from last running cycle)\n const lastCycle = session.orchestratorCycles[session.orchestratorCycles.length - 1];\n if (lastCycle && !lastCycle.completedAt && lastCycle.paneId) {\n const output = capturePaneOutput(lastCycle.paneId);\n if (output) {\n console.log(`\\n<orchestrator-pane-output lines=\"50\">`);\n console.log(output);\n console.log(`</orchestrator-pane-output>`);\n }\n }\n\n // Running agent panes\n for (const agent of runningAgents) {\n if (agent.paneId) {\n const output = capturePaneOutput(agent.paneId, 30);\n if (output) {\n console.log(`\\n<agent-pane-output agent=\"${agent.id}\" name=\"${agent.name}\" lines=\"30\">`);\n console.log(output);\n console.log(`</agent-pane-output>`);\n }\n }\n }\n }\n\n // Completion report\n if (verbose && session.completionReport) {\n console.log(`\\n${BOLD}Completion Report:${RESET}`);\n console.log(session.completionReport);\n }\n}\n\nexport function registerStatus(program: Command): void {\n program\n .command('status')\n .description('Show session status')\n .argument('[session-id]', 'Session ID (defaults to SISYPHUS_SESSION_ID env)')\n .option('-v, --verbose', 'Show detailed output (roadmap, pane output, agent instructions)')\n .action(async (sessionIdArg?: string, opts?: { verbose?: boolean }) => {\n const sessionId = sessionIdArg ?? process.env.SISYPHUS_SESSION_ID;\n const verbose = opts?.verbose ?? false;\n\n const request: Request = { type: 'status', sessionId };\n const response = await sendRequest(request);\n if (response.ok) {\n const session = response.data?.session as Session | undefined;\n if (session) {\n printSession(session, verbose);\n } else {\n console.log('No session found');\n }\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { basename } from 'node:path';\n\ninterface SessionSummary {\n id: string;\n name?: string;\n task: string;\n status: string;\n agentCount: number;\n createdAt: string;\n cwd?: string;\n}\n\nconst STATUS_COLORS: Record<string, string> = {\n active: '\\x1b[32m',\n paused: '\\x1b[33m',\n completed: '\\x1b[36m',\n};\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\n\nfunction truncateTask(task: string, max: number): string {\n if (task.length <= max) return task;\n return task.slice(0, max - 1) + '…';\n}\n\nexport function registerList(program: Command): void {\n program\n .command('list')\n .description('List sessions (defaults to current project)')\n .option('-a, --all', 'Show sessions from all projects')\n .option('--cwd <path>', 'Project directory to list sessions for (overrides SISYPHUS_CWD)')\n .action(async (opts: { all?: boolean; cwd?: string }) => {\n const cwd = opts.cwd ?? process.env['SISYPHUS_CWD'] ?? process.cwd();\n const request: Request = { type: 'list', cwd, all: opts.all };\n const response = await sendRequest(request);\n if (response.ok) {\n const sessions = (response.data?.sessions ?? []) as SessionSummary[];\n const totalCount = response.data?.totalCount as number | undefined;\n const filtered = response.data?.filtered as boolean | undefined;\n\n if (sessions.length === 0) {\n if (filtered && totalCount && totalCount > 0) {\n console.log(`No sessions in this project. ${totalCount} session(s) in other projects.`);\n console.log(`${DIM}Run ${RESET}sisyphus list --all${DIM} to show all.${RESET}`);\n } else {\n console.log('No sessions');\n }\n return;\n }\n\n for (const s of sessions) {\n const color = STATUS_COLORS[s.status] ?? '';\n const status = `${color}${s.status}${RESET}`;\n const agents = `${DIM}${s.agentCount} agent(s)${RESET}`;\n const task = truncateTask(s.task, 60);\n const label = s.name ? `${s.name} ${DIM}(${s.id.slice(0, 8)})${RESET}` : s.id;\n const cwdLabel = opts.all && s.cwd ? ` ${DIM}${basename(s.cwd)}${RESET}` : '';\n console.log(` ${BOLD}${label}${RESET} ${status} ${agents} ${task}${cwdLabel}`);\n }\n\n if (filtered && totalCount && totalCount > sessions.length) {\n const otherCount = totalCount - sessions.length;\n console.log(`\\n${DIM}${otherCount} more session(s) in other projects. Run ${RESET}sisyphus list --all${DIM} to show all.${RESET}`);\n }\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { readStdin } from '../stdin.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerReport(program: Command): void {\n program\n .command('report')\n .description('Send a progress report without exiting (agent only)')\n .option('--message <message>', 'Progress report content')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { message?: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n const agentId = process.env.SISYPHUS_AGENT_ID;\n if (!sessionId || !agentId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID (and SISYPHUS_AGENT_ID) environment variables');\n process.exit(1);\n }\n\n const content = opts.message ?? await readStdin();\n if (!content) {\n console.error('Error: provide --message or pipe content via stdin');\n process.exit(1);\n }\n\n const request: Request = { type: 'report', sessionId, agentId, content };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Progress report recorded');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerResume(program: Command): void {\n program\n .command('resume')\n .description('Respawn orchestrator with new instructions (for paused/completed sessions)')\n .addHelpText('after', '\\n Use `resume` to restart a paused or completed session with new instructions.\\n Use `continue` to keep working on a completed session without new instructions.\\n')\n .argument('<session-id>', 'Session ID to resume')\n .argument('[message]', 'Additional instructions for the orchestrator')\n .action(async (sessionId: string, message?: string) => {\n const cwd = process.env['SISYPHUS_CWD'] ?? process.cwd();\n const request: Request = { type: 'resume', sessionId, cwd, message };\n const response = await sendRequest(request);\n if (response.ok) {\n const tmuxSessionName = response.data?.tmuxSessionName as string | undefined;\n console.log(`Session ${sessionId} resumed`);\n if (tmuxSessionName) {\n console.log(`Tmux session: ${tmuxSessionName}`);\n console.log(` tmux attach -t ${tmuxSessionName}`);\n }\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerKill(program: Command): void {\n program\n .command('kill <sessionId>')\n .description('Kill a running session and all its agents')\n .action(async (sessionId: string) => {\n const request: Request = { type: 'kill', sessionId };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log(`Session ${sessionId} killed.`);\n if (response.data) {\n const { killedAgents } = response.data as { killedAgents: number };\n console.log(`Cleaned up: ${killedAgents} agent(s) killed, tmux window removed.`);\n }\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { createInterface } from 'node:readline';\nimport { uninstallDaemon } from '../install.js';\n\nasync function confirm(question: string): Promise<boolean> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim().toLowerCase() === 'y');\n });\n });\n}\n\nexport function registerUninstall(program: Command): void {\n program\n .command('uninstall')\n .description('Unload the sisyphus daemon from launchd and remove the plist')\n .option('--purge', 'Also remove all session data in ~/.sisyphus')\n .option('-y, --yes', 'Skip confirmation prompt for --purge')\n .action(async (opts: { purge?: boolean; yes?: boolean }) => {\n const purge = opts.purge ?? false;\n\n if (purge && !opts.yes) {\n const ok = await confirm('This will delete all session data in ~/.sisyphus. Continue? (y/N) ');\n if (!ok) {\n console.log('Aborted.');\n return;\n }\n }\n\n await uninstallDaemon(purge);\n });\n}\n","import type { Command } from 'commander';\nimport { rawSend } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerNotify(program: Command): void {\n const notify = program\n .command('notify')\n .description('Internal notifications (fire-and-forget)');\n\n notify\n .command('pane-exited')\n .description('Notify daemon that a tmux pane exited')\n .requiredOption('--pane-id <paneId>', 'Pane ID that exited')\n .action(async (opts: { paneId: string }) => {\n try {\n const request: Request = { type: 'pane-exited', paneId: opts.paneId };\n await rawSend(request);\n } catch {\n // Fire-and-forget: daemon may be stopped, socket gone, etc.\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport type { MessageSource } from '../../shared/types.js';\n\nexport function registerMessage(program: Command): void {\n program\n .command('message <content>')\n .description('Queue a message for the orchestrator to see on next cycle')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (content: string, opts: { session?: string }) => {\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const source: MessageSource | undefined = process.env.SISYPHUS_AGENT_ID\n ? { type: 'agent' as const, agentId: process.env.SISYPHUS_AGENT_ID }\n : undefined;\n\n const request: Request = { type: 'message', sessionId, content, source };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Message queued');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerUpdateTask(program: Command): void {\n program\n .command('update-task <task>')\n .description('Update the session task/goal')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (task: string, opts: { session?: string }) => {\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const request: Request = { type: 'update-task', sessionId, task };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Task updated');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerRollback(program: Command): void {\n program\n .command('rollback <sessionId> <cycle>')\n .description('Roll back a session to a previous cycle boundary')\n .action(async (sessionId: string, cycleStr: string) => {\n const toCycle = parseInt(cycleStr, 10);\n if (isNaN(toCycle) || toCycle < 1) {\n console.error('Error: cycle must be a positive integer');\n process.exit(1);\n }\n\n const cwd = process.env['SISYPHUS_CWD'] ?? process.cwd();\n const request: Request = { type: 'rollback', sessionId, cwd, toCycle };\n const response = await sendRequest(request);\n if (response.ok) {\n const data = response.data as { restoredToCycle: number };\n console.log(`Session ${sessionId} rolled back to cycle ${data.restoredToCycle}.`);\n console.log(`Session is now paused. Use 'sisyphus resume ${sessionId}' to respawn the orchestrator.`);\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerRestartAgent(program: Command): void {\n program\n .command('restart-agent <agentId>')\n .description('Restart a failed/killed/lost agent in a new tmux pane')\n .option('-s, --session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID)')\n .action(async (agentId: string, opts: { session?: string }) => {\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: No session ID. Use --session or set SISYPHUS_SESSION_ID.');\n process.exit(1);\n }\n\n const request: Request = { type: 'restart-agent', sessionId, agentId };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log(`Agent ${agentId} restarted.`);\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { DEFAULT_KEY, setupTmuxKeybind } from '../tmux-setup.js';\n\nexport function registerSetupKeybind(program: Command): void {\n program\n .command('setup-keybind [key]')\n .description('Install the sisyphus-cycle tmux keybinding (default: M-s)')\n .action(async (key: string | undefined) => {\n const resolvedKey = key ?? DEFAULT_KEY;\n const result = setupTmuxKeybind(resolvedKey);\n\n switch (result.status) {\n case 'installed':\n console.log(result.message);\n break;\n case 'already-installed':\n console.log(result.message);\n break;\n case 'conflict':\n console.log(`Key ${resolvedKey} is already bound:`);\n console.log(` ${result.existingBinding}`);\n console.log('');\n console.log('Use a different key, e.g.:');\n console.log(' sisyphus setup-keybind M-S');\n console.log(' sisyphus setup-keybind M-w');\n console.log(' sisyphus setup-keybind M-j');\n break;\n }\n });\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, statSync } from 'node:fs';\nimport type { Command } from 'commander';\nimport { daemonLogPath, daemonPidPath, globalDir, socketPath } from '../../shared/paths.js';\nimport { isInstalled } from '../install.js';\nimport { detectTerminal, checkItermOptionKey, isNvimAvailable, isBeginCommandInstalled } from '../onboard.js';\nimport { cycleScriptPath, DEFAULT_KEY, getExistingBinding, isSisyphusBinding, sisyphusTmuxConfPath } from '../tmux-setup.js';\n\ninterface Check {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n detail: string;\n fix?: string;\n}\n\nfunction checkNodeVersion(): Check {\n const major = parseInt(process.versions.node.split('.')[0]!, 10);\n if (major < 22) {\n return { name: 'Node.js', status: 'fail', detail: `v${process.versions.node} (v22+ required)`, fix: 'Install Node.js 22+: https://nodejs.org' };\n }\n return { name: 'Node.js', status: 'ok', detail: `v${process.versions.node}` };\n}\n\nfunction checkClaudeCli(): Check {\n try {\n execSync('which claude', { stdio: 'pipe' });\n return { name: 'Claude CLI', status: 'ok', detail: 'Found on PATH' };\n } catch {\n return {\n name: 'Claude CLI',\n status: 'fail',\n detail: 'Not found on PATH',\n fix: 'Install Claude Code: https://docs.anthropic.com/en/docs/claude-code/overview',\n };\n }\n}\n\nfunction checkGit(): Check {\n try {\n const version = execSync('git --version', { encoding: 'utf-8', stdio: 'pipe' }).trim();\n return { name: 'git', status: 'ok', detail: version };\n } catch {\n return { name: 'git', status: 'fail', detail: 'Not found on PATH', fix: 'Install git: https://git-scm.com/downloads' };\n }\n}\n\nfunction checkTmuxVersion(): Check {\n try {\n const version = execSync('tmux -V', { encoding: 'utf-8', stdio: 'pipe' }).trim();\n // Parse \"tmux X.Y\" or \"tmux next-X.Y\"\n const match = version.match(/(\\d+\\.\\d+)/);\n if (!match) return { name: 'tmux version', status: 'warn', detail: `Could not parse version: ${version}` };\n const ver = parseFloat(match[1]);\n if (ver < 3.2) {\n const upgradeHint = process.platform === 'darwin' ? 'brew install tmux (or upgrade)' : 'apt install tmux (Debian/Ubuntu) or your package manager';\n return { name: 'tmux version', status: 'warn', detail: `${version} (3.2+ recommended for popup support)`, fix: upgradeHint };\n }\n return { name: 'tmux version', status: 'ok', detail: version };\n } catch {\n return { name: 'tmux version', status: 'warn', detail: 'Could not determine version' };\n }\n}\n\nfunction checkDaemonInstalled(): Check {\n if (process.platform === 'darwin') {\n if (isInstalled()) {\n return { name: 'Daemon plist', status: 'ok', detail: 'Installed in LaunchAgents' };\n }\n return {\n name: 'Daemon plist',\n status: 'fail',\n detail: 'Not installed',\n fix: 'Run any sisyphus command to auto-install, or: sisyphus start \"test\"',\n };\n }\n // Linux: check if PID file exists (daemon started manually)\n const pid = daemonPidPath();\n if (existsSync(pid)) {\n return { name: 'Daemon setup', status: 'ok', detail: `PID file found at ${pid}` };\n }\n return {\n name: 'Daemon setup',\n status: 'fail',\n detail: 'Daemon not running (no PID file)',\n fix: 'Start manually: sisyphusd & — or configure via systemd',\n };\n}\n\nfunction checkDaemonRunning(): Check {\n const pid = daemonPidPath();\n if (!existsSync(pid)) {\n const fix = process.platform === 'darwin'\n ? 'launchctl load -w ~/Library/LaunchAgents/com.sisyphus.daemon.plist'\n : 'sisyphusd & — or check if the process is running';\n return {\n name: 'Daemon process',\n status: 'fail',\n detail: 'No PID file found',\n fix,\n };\n }\n try {\n const sock = socketPath();\n execSync(`test -S \"${sock}\"`, { stdio: 'pipe' });\n return { name: 'Daemon process', status: 'ok', detail: `Socket at ${sock}` };\n } catch {\n return {\n name: 'Daemon process',\n status: 'warn',\n detail: 'PID file exists but socket not found',\n fix: `Check logs: tail -20 ${daemonLogPath()}`,\n };\n }\n}\n\nfunction checkTmux(): Check {\n try {\n execSync('which tmux', { stdio: 'pipe' });\n } catch {\n const installHint = process.platform === 'darwin' ? 'brew install tmux' : 'apt install tmux (Debian/Ubuntu) or your package manager';\n return { name: 'tmux', status: 'fail', detail: 'Not found on PATH', fix: installHint };\n }\n try {\n execSync('tmux list-sessions', { stdio: 'pipe' });\n return { name: 'tmux', status: 'ok', detail: 'Running' };\n } catch {\n return { name: 'tmux', status: 'warn', detail: 'Installed but no server running' };\n }\n}\n\nfunction checkCycleScript(): Check {\n const path = cycleScriptPath();\n if (!existsSync(path)) {\n return {\n name: 'Cycle script',\n status: 'fail',\n detail: `Not found at ${path}`,\n fix: 'sisyphus setup-keybind',\n };\n }\n try {\n const mode = statSync(path).mode;\n if ((mode & 0o111) === 0) {\n return {\n name: 'Cycle script',\n status: 'fail',\n detail: 'Not executable',\n fix: `chmod +x ${path}`,\n };\n }\n } catch { /* ignore stat errors */ }\n return { name: 'Cycle script', status: 'ok', detail: path };\n}\n\nfunction checkTmuxKeybind(): Check {\n const existing = getExistingBinding(DEFAULT_KEY);\n if (existing === null) {\n // Also check if the sisyphus tmux.conf exists (binding might be configured but tmux not running)\n if (existsSync(sisyphusTmuxConfPath())) {\n return {\n name: `Tmux keybind (${DEFAULT_KEY})`,\n status: 'warn',\n detail: 'Configured in sisyphus tmux.conf but not active (tmux may not be running)',\n };\n }\n return {\n name: `Tmux keybind (${DEFAULT_KEY})`,\n status: 'fail',\n detail: 'Not bound',\n fix: 'sisyphus setup-keybind',\n };\n }\n if (isSisyphusBinding(existing)) {\n return { name: `Tmux keybind (${DEFAULT_KEY})`, status: 'ok', detail: 'Bound to sisyphus-cycle' };\n }\n return {\n name: `Tmux keybind (${DEFAULT_KEY})`,\n status: 'warn',\n detail: `Bound to something else: ${existing}`,\n fix: 'sisyphus setup-keybind M-S (or another free key)',\n };\n}\n\nfunction checkGlobalDir(): Check {\n const dir = globalDir();\n if (existsSync(dir)) {\n return { name: 'Data directory', status: 'ok', detail: dir };\n }\n return { name: 'Data directory', status: 'warn', detail: `${dir} does not exist (created on first use)` };\n}\n\nfunction checkTerminal(): Check {\n if (process.platform !== 'darwin') {\n return { name: 'Terminal', status: 'ok', detail: 'Non-macOS (skipped)' };\n }\n const terminal = detectTerminal();\n if (terminal.isIterm) {\n return { name: 'Terminal', status: 'ok', detail: terminal.name };\n }\n return {\n name: 'Terminal',\n status: 'warn',\n detail: terminal.name ? terminal.name : 'unknown',\n fix: 'iTerm2 recommended for best experience: https://iterm2.com',\n };\n}\n\nfunction checkItermRightOptionKey(): Check | null {\n if (process.platform !== 'darwin') return null;\n const terminal = detectTerminal();\n if (!terminal.isIterm) return null;\n const result = checkItermOptionKey();\n if (!result.checked) return null;\n if (result.allCorrect) {\n return { name: 'Right Option Key', status: 'ok', detail: 'Esc+' };\n }\n const profiles = result.incorrectProfiles.map((p) => `\"${p}\"`).join(', ');\n return {\n name: 'Right Option Key',\n status: 'warn',\n detail: `Not Esc+ for ${profiles}`,\n fix: 'iTerm2 \\u2192 Settings \\u2192 Profiles \\u2192 Keys \\u2192 Right Option Key \\u2192 Esc+',\n };\n}\n\nfunction checkBeginCommand(): Check {\n if (isBeginCommandInstalled()) {\n return { name: '/begin command', status: 'ok', detail: 'Installed' };\n }\n return {\n name: '/begin command',\n status: 'warn',\n detail: 'Not installed',\n fix: 'sisyphus setup',\n };\n}\n\nfunction checkNvim(): Check {\n if (!isNvimAvailable()) {\n const fix = process.platform === 'darwin' ? 'brew install neovim' : 'Install neovim from https://neovim.io';\n return { name: 'nvim', status: 'warn', detail: 'Not installed', fix };\n }\n try {\n const version = execSync('nvim --version', { encoding: 'utf-8', stdio: 'pipe' }).split('\\n')[0]?.replace('NVIM ', '');\n return { name: 'nvim', status: 'ok', detail: version ?? 'installed' };\n } catch {\n return { name: 'nvim', status: 'ok', detail: 'installed' };\n }\n}\n\nconst SYMBOLS = { ok: '\\u2713', warn: '!', fail: '\\u2717' } as const;\n\nexport function registerDoctor(program: Command): void {\n program\n .command('doctor')\n .description('Check sisyphus installation health')\n .action(async () => {\n const itermCheck = checkItermRightOptionKey();\n const checks: Check[] = [\n checkNodeVersion(),\n checkClaudeCli(),\n checkGit(),\n checkTmux(),\n checkTmuxVersion(),\n checkTerminal(),\n ...(itermCheck ? [itermCheck] : []),\n checkGlobalDir(),\n checkDaemonInstalled(),\n checkDaemonRunning(),\n checkCycleScript(),\n checkTmuxKeybind(),\n checkBeginCommand(),\n checkNvim(),\n ];\n\n let hasIssues = false;\n for (const c of checks) {\n const sym = SYMBOLS[c.status];\n console.log(` ${sym} ${c.name}: ${c.detail}`);\n if (c.status !== 'ok') hasIssues = true;\n }\n\n // Print fixes\n const fixable = checks.filter((c) => c.fix && c.status !== 'ok');\n if (fixable.length > 0) {\n console.log('\\nFixes:');\n for (const c of fixable) {\n console.log(` ${c.name}: ${c.fix}`);\n }\n }\n\n if (!hasIssues) {\n console.log('\\nAll checks passed.');\n }\n });\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport interface TerminalInfo {\n name: string;\n isIterm: boolean;\n}\n\nexport interface ItermOptionKeyResult {\n checked: boolean;\n allCorrect: boolean;\n incorrectProfiles: string[];\n}\n\nexport interface NvimInfo {\n installed: boolean;\n autoInstalled: boolean;\n version: string;\n lazyVimInstalled: boolean;\n}\n\nexport interface CommandInfo {\n installed: boolean;\n autoInstalled: boolean;\n path: string;\n}\n\nexport interface OnboardResult {\n tmuxInstalled: boolean;\n tmuxAutoInstalled: boolean;\n terminal: TerminalInfo;\n itermOptionKey: ItermOptionKeyResult;\n tmuxDefaultsWritten: boolean;\n nvim: NvimInfo;\n command: CommandInfo;\n}\n\nexport function detectTerminal(): TerminalInfo {\n const termProgram = process.env['TERM_PROGRAM'] || '';\n const isIterm = termProgram === 'iTerm.app' || !!process.env['ITERM_SESSION_ID'];\n return { name: termProgram || 'unknown', isIterm };\n}\n\nfunction isTmuxAvailable(): boolean {\n try {\n execSync('which tmux', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isBrewAvailable(): boolean {\n try {\n execSync('which brew', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction tryAutoInstallTmux(): boolean {\n if (!isBrewAvailable()) return false;\n try {\n console.log(' Installing tmux via Homebrew...');\n execSync('brew install tmux', { stdio: 'inherit' });\n return isTmuxAvailable();\n } catch {\n return false;\n }\n}\n\nexport function checkItermOptionKey(): ItermOptionKeyResult {\n if (process.platform !== 'darwin') {\n return { checked: false, allCorrect: true, incorrectProfiles: [] };\n }\n\n const plistPath = join(homedir(), 'Library', 'Preferences', 'com.googlecode.iterm2.plist');\n if (!existsSync(plistPath)) {\n return { checked: false, allCorrect: false, incorrectProfiles: [] };\n }\n\n try {\n const json = execSync(\n `plutil -extract \"New Bookmarks\" json -o - \"${plistPath}\"`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] },\n );\n const profiles = JSON.parse(json) as Array<Record<string, unknown>>;\n const currentProfile = process.env['ITERM_PROFILE'];\n const incorrect: string[] = [];\n for (const profile of profiles) {\n const name = (profile['Name'] as string) || 'Unnamed';\n // Only check the current profile (or all if we can't detect which)\n if (currentProfile && name !== currentProfile) continue;\n // 0 = Normal, 1 = Meta, 2 = Esc+\n if (profile['Right Option Key Sends'] !== 2) {\n incorrect.push(name);\n }\n }\n return { checked: true, allCorrect: incorrect.length === 0, incorrectProfiles: incorrect };\n } catch {\n return { checked: false, allCorrect: false, incorrectProfiles: [] };\n }\n}\n\nfunction hasExistingTmuxConf(): boolean {\n return (\n existsSync(join(homedir(), '.tmux.conf')) ||\n existsSync(join(homedir(), '.config', 'tmux', 'tmux.conf'))\n );\n}\n\nconst TMUX_DEFAULTS = `# Sensible tmux defaults (installed by sisyphus)\n# Customize freely — sisyphus won't overwrite this file.\n\n# Enable mouse (click panes, scroll, resize)\nset -g mouse on\n\n# Scrollback history\nset -g history-limit 50000\n\n# 256 color + true color support\nset -g default-terminal \"tmux-256color\"\nset -as terminal-overrides \",*:Tc\"\n\n# Low escape delay (keeps Option/Meta keybindings responsive)\nset -sg escape-time 10\n\n# Window numbering from 1\nset -g base-index 1\nsetw -g pane-base-index 1\n\n# Renumber windows when one closes\nset -g renumber-windows on\n\n# Clipboard integration\nset -g set-clipboard on\n\n# Focus events (for editors)\nset -g focus-events on\n\n# --- Pane navigation (no prefix needed) ---\nbind -n C-h select-pane -L\nbind -n C-j select-pane -D\nbind -n C-k select-pane -U\nbind -n C-l select-pane -R\n\n# --- Window navigation (no prefix needed) ---\nbind -n C-n next-window\nbind -n C-p previous-window\n\n# --- New window / splits preserve cwd ---\nbind c new-window -c \"#{pane_current_path}\"\nbind '\"' split-window -v -c \"#{pane_current_path}\"\nbind % split-window -h -c \"#{pane_current_path}\"\n\n# --- Kill pane + rebalance ---\nbind x kill-pane \\\\; select-layout even-horizontal\n\n# --- Auto-rebalance on pane close ---\nset-hook -g after-kill-pane \"select-layout even-horizontal\"\nset-hook -g pane-exited \"select-layout even-horizontal\"\n\n# --- Manual re-tile ---\nbind = select-layout even-horizontal\n\n# --- Scroll (no prefix needed) ---\nbind -n C-u copy-mode \\\\; send-keys -X halfpage-up\nbind -n C-d copy-mode \\\\; send-keys -X halfpage-down\n\n# --- Vi copy mode ---\nsetw -g mode-keys vi\nbind -T copy-mode-vi v send-keys -X begin-selection\nbind -T copy-mode-vi y send-keys -X copy-selection-and-cancel\n`;\n\nfunction writeTmuxDefaults(): void {\n const confPath = join(homedir(), '.tmux.conf');\n writeFileSync(confPath, TMUX_DEFAULTS, 'utf8');\n}\n\nexport function isNvimAvailable(): boolean {\n try {\n execSync('which nvim', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction getNvimVersion(): string {\n try {\n return execSync('nvim --version', { encoding: 'utf-8', stdio: 'pipe' }).split('\\n')[0]?.replace('NVIM ', '') || 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\nfunction hasLazyVimConfig(): boolean {\n return existsSync(join(homedir(), '.config', 'nvim', 'lazy-lock.json'));\n}\n\nexport function tryAutoInstallNvim(): NvimInfo {\n if (isNvimAvailable()) {\n return { installed: true, autoInstalled: false, version: getNvimVersion(), lazyVimInstalled: hasLazyVimConfig() };\n }\n if (!isBrewAvailable()) {\n return { installed: false, autoInstalled: false, version: '', lazyVimInstalled: false };\n }\n try {\n console.log(' Installing neovim via Homebrew...');\n execSync('brew install neovim', { stdio: 'inherit' });\n } catch {\n return { installed: false, autoInstalled: false, version: '', lazyVimInstalled: false };\n }\n if (!isNvimAvailable()) {\n return { installed: false, autoInstalled: false, version: '', lazyVimInstalled: false };\n }\n // Clone LazyVim starter config if no nvim config exists\n const nvimConfigDir = join(homedir(), '.config', 'nvim');\n let lazyVimInstalled = false;\n if (!existsSync(nvimConfigDir)) {\n try {\n console.log(' Cloning LazyVim starter config...');\n execSync(`git clone https://github.com/LazyVim/starter ${nvimConfigDir}`, { stdio: 'inherit' });\n // Remove .git so user owns the config\n const gitDir = join(nvimConfigDir, '.git');\n if (existsSync(gitDir)) {\n execSync(`rm -rf \"${gitDir}\"`, { stdio: 'pipe' });\n }\n lazyVimInstalled = true;\n } catch {\n // Non-fatal — nvim is installed, just no starter config\n }\n }\n return { installed: true, autoInstalled: true, version: getNvimVersion(), lazyVimInstalled };\n}\n\nfunction beginCommandPath(): string {\n return join(homedir(), '.claude', 'commands', 'sisyphus', 'begin.md');\n}\n\nfunction bundledBeginCommandPath(): string {\n const distDir = dirname(fileURLToPath(import.meta.url));\n return join(distDir, 'templates', 'begin.md');\n}\n\nexport function isBeginCommandInstalled(): boolean {\n return existsSync(beginCommandPath());\n}\n\nexport function installBeginCommand(): CommandInfo {\n const dest = beginCommandPath();\n if (existsSync(dest)) {\n return { installed: true, autoInstalled: false, path: dest };\n }\n const src = bundledBeginCommandPath();\n if (!existsSync(src)) {\n return { installed: false, autoInstalled: false, path: dest };\n }\n try {\n mkdirSync(dirname(dest), { recursive: true });\n writeFileSync(dest, readFileSync(src, 'utf-8'), 'utf8');\n return { installed: true, autoInstalled: true, path: dest };\n } catch {\n return { installed: false, autoInstalled: false, path: dest };\n }\n}\n\nexport function runOnboarding(): OnboardResult {\n const terminal = detectTerminal();\n const tmuxAlreadyInstalled = isTmuxAvailable();\n\n let tmuxInstalled = tmuxAlreadyInstalled;\n let tmuxAutoInstalled = false;\n let tmuxDefaultsWritten = false;\n\n // Auto-install tmux if missing\n if (!tmuxAlreadyInstalled && process.platform === 'darwin') {\n tmuxAutoInstalled = tryAutoInstallTmux();\n tmuxInstalled = tmuxAutoInstalled;\n\n // Write sensible defaults only for fresh tmux installs (don't touch existing configs)\n if (tmuxAutoInstalled && !hasExistingTmuxConf()) {\n writeTmuxDefaults();\n tmuxDefaultsWritten = true;\n }\n }\n\n // Check iTerm2 right option key\n let itermOptionKey: ItermOptionKeyResult = { checked: false, allCorrect: true, incorrectProfiles: [] };\n if (terminal.isIterm) {\n itermOptionKey = checkItermOptionKey();\n }\n\n // Nvim\n const nvim = tryAutoInstallNvim();\n\n // /begin command\n const command = installBeginCommand();\n\n return { tmuxInstalled, tmuxAutoInstalled, terminal, itermOptionKey, tmuxDefaultsWritten, nvim, command };\n}\n\nexport function formatOnboardingMessages(result: OnboardResult): string[] {\n const lines: string[] = [];\n\n // Terminal recommendation (macOS only)\n if (process.platform === 'darwin' && !result.terminal.isIterm) {\n lines.push(\n ` Terminal: ${result.terminal.name || 'unknown'}`,\n ' Tip: iTerm2 is recommended for the best experience with sisyphus.',\n ' Download: https://iterm2.com',\n '',\n );\n }\n\n // tmux status\n if (result.tmuxAutoInstalled) {\n lines.push(' \\u2713 tmux installed via Homebrew.');\n if (result.tmuxDefaultsWritten) {\n lines.push(' \\u2713 Default tmux config written to ~/.tmux.conf');\n }\n lines.push('');\n } else if (!result.tmuxInstalled) {\n const installHint = process.platform === 'darwin'\n ? ' Install Homebrew (https://brew.sh) then run: brew install tmux'\n : ' Install: apt install tmux (Debian/Ubuntu) or your package manager';\n lines.push(\n ' \\u2717 tmux is required but could not be installed automatically.',\n installHint,\n '',\n );\n }\n\n // iTerm2 right option key\n if (result.itermOptionKey.checked && !result.itermOptionKey.allCorrect) {\n const profiles = result.itermOptionKey.incorrectProfiles;\n lines.push(\n ' \\u26a0 Right Option Key is not sending Esc+ in iTerm2:',\n ...profiles.map((p) => ` \\u2022 Profile \"${p}\"`),\n '',\n ' Sisyphus uses Option keybindings (e.g., Option-s to cycle sessions).',\n ' Fix: iTerm2 \\u2192 Settings \\u2192 Profiles \\u2192 Keys \\u2192 Right Option Key \\u2192 Esc+',\n '',\n );\n }\n\n return lines;\n}\n","import type { Command } from 'commander';\nimport { buildCompanionContext } from '../../tui/lib/context.js';\n\nexport function registerCompanionContext(program: Command): void {\n program\n .command('companion-context')\n .description('Output session context JSON for companion hook')\n .option('--cwd <path>', 'Project directory', process.cwd())\n .action((opts: { cwd: string }) => {\n const context = buildCompanionContext(opts.cwd);\n process.stdout.write(JSON.stringify({ additionalContext: context }));\n });\n}\n","import { execSync } from 'node:child_process';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Command } from 'commander';\nimport { isTmuxInstalled } from '../tmux.js';\nimport { isNvimAvailable, detectTerminal, checkItermOptionKey } from '../onboard.js';\n\nfunction templatePath(name: string): string {\n return join(dirname(fileURLToPath(import.meta.url)), 'templates', name);\n}\n\nfunction isClaudeCode(): boolean {\n return !!process.env['CLAUDECODE'];\n}\n\nfunction printNonClaudeMessage(): void {\n console.log(`\n ╔══════════════════════════════════════════════════╗\n ║ sisyphus getting-started — Interactive Tutorial ║\n ╚══════════════════════════════════════════════════╝\n\n This command provides an interactive tutorial best experienced\n inside Claude Code. Claude will walk you through setup step by step.\n\n To start:\n 1. Open Claude Code: claude\n 2. Run: sisyphus getting-started\n\n If you just want the quick reference, run:\n sisyphus --help\n sisyphus doctor\n`);\n}\n\nfunction printStep0(): void {\n const tmuxInstalled = isTmuxInstalled();\n const inTmux = !!process.env['TMUX'];\n let tmuxSession: string | null = null;\n if (process.env['TMUX']) {\n const segments = process.env['TMUX'].split(',');\n const pathPart = segments[0];\n if (pathPart) {\n const parts = pathPart.split('/');\n tmuxSession = parts[parts.length - 1] || null;\n }\n }\n\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 0: Entry & Tmux Gate\n\n## Environment Data\n- tmuxInstalled: ${tmuxInstalled}\n- inTmux: ${inTmux}\n- tmuxSession: ${tmuxSession ?? 'none'}\n\n## Tutorial Overview\n\nThis tutorial has 6 steps. Share this overview so the user knows what's coming and can skip ahead:\n\n| Step | Topic | Command |\n|------|-------|---------|\n| 0 | Entry & tmux gate (you are here) | \\`sisyphus getting-started\\` |\n| 1 | Tmux basics — sessions, panes, navigation | \\`--tutorial 1\\` |\n| 2 | Nvim basics — open, save, quit (optional) | \\`--tutorial 2\\` |\n| 3 | Sisyphus concepts — session model & keybinds | \\`--tutorial 3\\` |\n| 4 | Live demo — launch and observe a real session | \\`--tutorial 4\\` |\n| 5 | What's next — real usage guidance & suggestions | \\`--tutorial 5\\` |\n\nTell the user they can skip to any step with \\`sisyphus getting-started --tutorial <N>\\`.\n\n## Instructions for Claude\n\nYou are guiding a user through the Sisyphus interactive tutorial.\n\n### First: Ask if they want the tutorial\n\nAsk the user if they'd like the interactive walkthrough. If they decline, give this quick summary and stop:\n\n> Sisyphus is a multi-agent orchestrator for Claude Code. Start a session with \\`sisyphus start \"task\"\\`,\n> monitor with \\`sisyphus dashboard\\`, and check health with \\`sisyphus doctor\\`.\n\n### If they want the tutorial:\n\n**Case 1: tmux is NOT installed (tmuxInstalled: false)**\n- Explain what tmux is in 2-3 sentences: \"tmux is a terminal multiplexer — it lets you split your terminal into multiple panes and keep sessions running in the background. Sisyphus uses it to give each agent its own workspace.\"\n- Show this ASCII diagram:\n\n\\`\\`\\`\n Regular terminal: With tmux:\n ┌──────────────┐ ┌──────┬──────┐\n │ │ │ Agent│ Agent│\n │ one view │ │ 001 │ 002 │\n │ │ ├──────┼──────┤\n │ │ │ Agent│ Orch │\n └──────────────┘ │ 003 │ │\n └──────┴──────┘\n\\`\\`\\`\n\n- Tell them to install tmux:\n - macOS: \\`brew install tmux\\`\n - Linux: \\`apt install tmux\\` or their package manager\n- After install, re-run: \\`sisyphus getting-started --tutorial 0\\` to verify\n\n**Case 2: tmux installed but NOT in a tmux session (inTmux: false)**\n- Tell the user they need to be inside a tmux session for the tutorial\n- Have them run: \\`tmux new-session\\`\n- Then resume the conversation with Claude in the new tmux session: \\`claude\\`\n- Then re-run: \\`sisyphus getting-started --tutorial 0\\` to verify\n\n**Case 3: In tmux (inTmux: true)**\n- Tell the user they're all set — tmux is running\n- Proceed by running: \\`sisyphus getting-started --tutorial 1\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep1(): void {\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 1: Tmux Basics\n\n## Instructions for Claude\n\nTeach the user tmux fundamentals. Be conversational and encouraging.\n\n### 1. Explain the concepts with diagrams\n\n**Sessions, Windows, and Panes:**\n\n\\`\\`\\`\ntmux session \"work\"\n├── window 1: \"code\"\n│ ┌──────────┬──────────┐\n│ │ pane 1 │ pane 2 │\n│ │ (editor)│ (tests) │\n│ └──────────┴──────────┘\n└── window 2: \"servers\"\n ┌──────────────────────┐\n │ pane 1 │\n │ (dev server) │\n └──────────────────────┘\n\\`\\`\\`\n\n- **Session**: A collection of windows. Persists even if you close the terminal.\n- **Window**: Like a tab. Each window fills the screen.\n- **Pane**: A split within a window. Sisyphus puts each agent in its own pane.\n\n### 2. Hands-on: Create a test split\n\nRun this command for the user:\n\\`\\`\\`\ntmux split-window -h\n\\`\\`\\`\n\nTell them: \"I just split your terminal. You should see two panes side by side.\"\n\nExplain navigation:\n- \\`Ctrl+l\\`: move to the right pane\n- \\`Ctrl+h\\`: move to the left pane\n- \\`Ctrl+j\\`: move to the pane below\n- \\`Ctrl+k\\`: move to the pane above\n- No prefix key needed — just hold Ctrl and press the direction letter\n- For windows: \\`Ctrl+n\\` next window, \\`Ctrl+p\\` previous window\n\nAsk them to try navigating between panes.\n\n### 3. Clean up the test pane\n\nOnce they confirm they can navigate, close the extra pane:\n\\`\\`\\`\ntmux kill-pane -t {the other pane}\n\\`\\`\\`\n\nOr tell them they can type \\`exit\\` in the extra pane to close it.\n\n### 4. Teach essential commands\n\n- **Detach**: \\`Ctrl-b d\\` — leaves tmux running in background, returns to normal terminal\n- **Reattach**: \\`tmux attach\\` (or \\`tmux a\\`) — reconnects to the running session\n- **Scroll up/down**: \\`Ctrl+u\\` / \\`Ctrl+d\\` — scroll half-page up/down (no prefix needed). Press \\`q\\` to exit scroll mode.\n- **New window**: \\`Ctrl-b n\\` — opens a new window in the current directory\n- **Kill pane**: \\`Ctrl-b x\\` — closes the current pane and rebalances layout\n- **Re-tile**: \\`Ctrl-b =\\` — rebalance all panes to equal widths\n\n### 5. Verification\n\nAsk the user to confirm: \"Can you navigate between panes with Ctrl+h and Ctrl+l?\"\n\nOnce confirmed, proceed:\n\\`\\`\\`\nsisyphus getting-started --tutorial 2\n\\`\\`\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep2(): void {\n const nvimInstalled = isNvimAvailable();\n\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 2: Nvim Basics\n\n## Environment Data\n- nvimInstalled: ${nvimInstalled}\n\n## Instructions for Claude\n\nThis step is OPTIONAL. Nvim is useful for reviewing and editing files when you jump into agent panes, but not required.\n\nNote: The sisyphus dashboard has keys that auto-open files in nvim — users don't need to know how to open files from the command line. Focus on what they'll need once they're INSIDE nvim.\n\n### If nvim is NOT installed (nvimInstalled: false)\n\nAsk the user: \"Neovim is handy for reviewing and editing files in tmux panes. Want me to install it, or skip this step?\"\n\n- **Install**: Run \\`brew install neovim\\` (macOS) or suggest their package manager\n- **Skip**: That's fine — they can use \\`cat\\`, \\`less\\`, or any editor they prefer. Proceed to step 3.\n\n### If nvim IS installed (nvimInstalled: true)\n\nBriefly explain the key concept — nvim has two modes:\n\n- **Normal mode** (default): Keys are commands, not text. This is where you navigate.\n- **Insert mode**: Press \\`i\\` to enter. Now you type normally. \\`Esc\\` goes back to normal.\n\nThen tell the user: \"I'm going to open an interactive tutorial file in a pane to your right. It walks you through everything — navigation, editing, saving. Follow the instructions inside the file.\"\n\nOpen the bundled tutorial file in a split pane:\n\\`\\`\\`\ncp ${templatePath('nvim-tutorial.txt')} /tmp/sisyphus-nvim-tutorial.txt\ntmux split-window -h \"nvim /tmp/sisyphus-nvim-tutorial.txt\"\n\\`\\`\\`\n\nTell them to click on the right pane (or \\`Ctrl+l\\`) and follow the instructions in the file. When they \\`:wq\\` or \\`ZZ\\`, the pane closes and they're back in Claude.\n\nTell them: \"When you jump into an agent's pane and the dashboard opens a file, you'll land in normal mode. Now you know how to look around, make edits, and get out.\"\n\n### Verification\n\nAsk if they were able to edit and save the file (or if they skipped).\n\nProceed:\n\\`\\`\\`\nsisyphus getting-started --tutorial 3\n\\`\\`\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep3(): void {\n // Detect iTerm Right Option Key status for environment data\n let rightOptionKeyStatus = 'unknown';\n const terminal = detectTerminal();\n if (!terminal.isIterm) {\n rightOptionKeyStatus = 'not-iterm';\n } else {\n const result = checkItermOptionKey();\n if (!result.checked) {\n rightOptionKeyStatus = 'could-not-check';\n } else if (result.allCorrect) {\n rightOptionKeyStatus = 'ok';\n } else {\n rightOptionKeyStatus = `incorrect:${result.incorrectProfiles.join(',')}`;\n }\n }\n\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 3: Sisyphus Concepts & Keybinds\n\n## Environment Data\n- rightOptionKeyStatus: ${rightOptionKeyStatus}\n\n## Instructions for Claude\n\n### 1. CRITICAL FIRST: Right Option Key Setup\n\n**This must be done before anything else.** Sisyphus keybinds use the Option key as \"Meta\". By default, macOS terminals send special characters when you press Option (e.g., Option+s types \\`ß\\`). We need the RIGHT Option key to send escape sequences instead.\n\n**Check the environment data above:**\n\n- **rightOptionKeyStatus: ok** — They're all set, briefly confirm and move on.\n\n- **rightOptionKeyStatus: incorrect:ProfileName** — Walk them through the fix:\n\n > Your Right Option key isn't configured correctly yet. Here's how to fix it:\n >\n > 1. Open **iTerm2 Settings** (Cmd+,)\n > 2. Go to **Profiles** → select your profile (shown above)\n > 3. Click the **Keys** tab\n > 4. At the bottom, find **Right Option Key**\n > 5. Change it from **Normal** to **Esc+**\n >\n > \\`\\`\\`\n > ┌─ iTerm2 Settings ──────────────────────────┐\n > │ Profiles > Keys │\n > │ │\n > │ Right Option Key: │\n > │ ○ Normal (sends special chars like ß) │\n > │ ● Esc+ (sends escape sequences) ← ✓ │\n > └─────────────────────────────────────────────┘\n > \\`\\`\\`\n >\n > **Why right and not left?** You'll still want the left Option key for\n > typing special characters (accents, symbols). The right Option key\n > becomes your \"Meta\" key for tmux/sisyphus keybinds.\n\n After they change it, have them verify by re-running \\`sisyphus doctor\\` — look for \"Right Option Key: Esc+\".\n\n- **rightOptionKeyStatus: not-iterm** — They're not using iTerm2. Explain:\n > Sisyphus keybinds use Option as Meta. In iTerm2 this is configured via\n > \"Right Option Key → Esc+\". For your terminal, look for a similar setting\n > like \"Option sends Meta\" or \"Option sends Esc+\". Without this, pressing\n > Option+s will type a special character instead of triggering the keybind.\n\n- **rightOptionKeyStatus: could-not-check** or **unknown** — Ask them to manually check:\n > Press Option+s in your terminal. If you see \\`ß\\` (or another special character),\n > your Option key needs to be reconfigured. In iTerm2: Settings → Profiles → Keys →\n > Right Option Key → Esc+.\n\n### 2. Explain the session model\n\nThis is the KEY concept. Use the diagram and be clear:\n\n\\`\\`\\`\n YOUR tmux session (\"work\") Sisyphus tmux session (\"sisyphus-abc123\")\n ┌─────────────────────┐ ┌──────────┬──────────┬──────────┐\n │ │ │ Orch │ Agent │ Agent │\n │ Your normal work │ ←──→ │ (yellow)│ (blue) │ (green) │\n │ + dashboard │ │ │ │ │\n │ │ │ Plans & │ Writes │ Writes │\n │ │ │ assigns │ code │ tests │\n └─────────────────────┘ └──────────┴──────────┴──────────┘\n\\`\\`\\`\n\nKey points:\n- Sisyphus creates its OWN tmux session — it doesn't clutter yours\n- The **orchestrator** (yellow pane) plans work and spawns agents\n- **Agents** (colored panes) work in parallel on subtasks\n- Your session stays clean — you get a **dashboard** for monitoring\n- You can jump between your session and the sisyphus session to observe\n\n### 3. Teach keybinds\n\nTwo keybinds to remember (both use the RIGHT Option key):\n\n| Keybind | Action |\n|---------|--------|\n| Right Option + s | Cycle through sisyphus sessions |\n| Right Option + Shift + s | Jump back to dashboard |\n\n### 4. Verify keybinds are installed\n\nRun \\`sisyphus doctor\\` and check the output. Look for:\n- \"Cycle script\" — should be ✓\n- \"Tmux keybind\" — should be ✓\n- \"Right Option Key\" — should be \"Esc+\"\n\nIf cycle script or keybind is missing, run: \\`sisyphus setup-keybind\\`\n\n### 5. Test the keybind\n\nHave the user try pressing Right Option + s. Nothing should happen yet (no sisyphus session running) — and that's fine. The important thing is no special character appears.\n\nIf they see \\`ß\\` or similar, circle back to the Right Option Key setup above.\n\n### 6. Verification\n\nConfirm:\n- They understand the two-session model (their session vs sisyphus session)\n- \\`sisyphus doctor\\` shows keybinds installed AND Right Option Key: Esc+\n- Right Option + s doesn't produce a special character\n\nProceed:\n\\`\\`\\`\nsisyphus getting-started --tutorial 4\n\\`\\`\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep4(): void {\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 4: Demo Session\n\n## Instructions for Claude\n\nThis is the grand finale — a live demo session.\n\n### 1. Health check\n\nRun \\`sisyphus doctor\\` first. If any checks are failing, help the user fix them before proceeding.\nAll core checks (tmux, daemon, keybinds) should be ✓.\n\n### 2. BEFORE launching: Teach navigation\n\n**This is critical.** When \\`sisyphus start\\` runs, it auto-opens the dashboard in a new tmux window. The user will suddenly be looking at the dashboard and may feel \"stuck\". Teach them how to navigate BEFORE launching:\n\nExplain clearly:\n\n> Before we launch, you need to know how to move between tmux windows. Right now you're in a window with Claude. When sisyphus starts, it'll open a dashboard in a new window. Think of windows like tabs:\n>\n> \\`\\`\\`\n> Window 1 (you are here) Window 2 (dashboard)\n> ┌──────────────────┐ ┌──────────────────┐\n> │ Claude Code │ │ Sisyphus │\n> │ (this session) │ → │ Dashboard │\n> └──────────────────┘ └──────────────────┘\n> Ctrl+n → ← Ctrl+p\n> \\`\\`\\`\n>\n> - **\\`Ctrl+n\\`** — next window (go to dashboard)\n> - **\\`Ctrl+p\\`** — previous window (come back here)\n>\n> And remember from step 3:\n> - **Right Option + s** — jump to the sisyphus agent session (where you can watch agents work live)\n> - **Right Option + Shift + s** — jump back to dashboard\n\nHave the user confirm they understand these keybinds before proceeding.\n\n### 3. Set expectations, copy demo app, and launch\n\nFirst, copy the demo todo app to a temp directory and init a git repo (sisyphus needs git):\n\\`\\`\\`\nrm -rf /tmp/sisyphus-tutorial-demo\ncp -r ${templatePath('tutorial-demo')} /tmp/sisyphus-tutorial-demo\ngit -C /tmp/sisyphus-tutorial-demo init\ngit -C /tmp/sisyphus-tutorial-demo add -A\ngit -C /tmp/sisyphus-tutorial-demo commit -m \"Initial todo app\"\n\\`\\`\\`\n\nTell the user:\n\n> I've set up a small todo app in /tmp/sisyphus-tutorial-demo — a Node.js API\n> with a few files. I'm going to launch sisyphus on it. Here's what will happen:\n> 1. The dashboard opens automatically (you'll be switched to it)\n> 2. Press **Ctrl+p** to come back here to Claude — I'll guide you through what to watch\n> 3. The session takes a few minutes. You can watch agents work live!\n\nThen launch from the demo directory:\n\\`\\`\\`\ncd /tmp/sisyphus-tutorial-demo && sisyphus start \"Add three improvements to this todo app: (1) add a priority field (high/medium/low) to todos, (2) add a GET /todos/stats endpoint that returns counts of total/done/pending todos, (3) add tests for the new features. Explain your thinking at each step.\" -c \"TUTORIAL DEMO: A user is watching this session to learn how sisyphus works. Be EXTRA VERBOSE — explain your reasoning, narrate what you're doing, and make your planning visible. When spawning agents, give each agent context that this is a tutorial demo and they should explain their work clearly. Keep scope small: 2-3 agents, 1-2 cycles.\"\n\\`\\`\\`\n\nAfter launching, tell them:\n\n> The dashboard just opened. Press **Ctrl+p** to come back here — I'll provide live commentary as the session runs so you know what's happening.\n\nWait for them to confirm they're back, then start live commentary.\n\n### 4. Live commentary loop\n\n**This is the most important part of the demo.** Don't just launch and wait — actively narrate.\n\nOnce the user is back, start a polling loop. Every ~45 seconds, run \\`sisyphus status --verbose <session-id>\\` and provide SHORT, contextual commentary about what's happening. The \\`--verbose\\` flag shows agent instructions, full roadmap, cycle logs, and live pane output from the orchestrator and running agents — use this rich data to narrate what's actually happening, not just phase names.\n\n**How to narrate each phase:**\n\n- **Cycle 1, no agents yet**: \"The orchestrator is reading the codebase and planning. It's figuring out how to split the work. Check the dashboard (\\`Ctrl+n\\`) — you'll see the roadmap updating.\"\n\n- **Agents spawning**: \"Agents just spawned! You should see new panes appearing. Try \\`Right Option + s\\` to jump to the sisyphus session and watch them work. Each colored pane is an independent Claude instance.\"\n\n- **Agents working**: \"Agent-001 is working on [X], Agent-002 is on [Y]. They're working in parallel — this is the key advantage of sisyphus. Jump over and watch if you like (\\`Right Option + s\\`).\"\n\n- **Agents submitting**: \"Agent-001 just submitted its report! [N] more to go. When all agents finish, the orchestrator will respawn to review.\"\n\n- **Between cycles**: \"All agents done. The orchestrator is respawning with fresh context to review the reports and decide what's next. This is the cycle boundary — the orchestrator never runs out of context because it starts fresh each time.\"\n\n- **Completion**: \"The session is complete! Let me show you the results.\"\n\n**Important:**\n- Keep commentary to 1-3 sentences per check — don't wall-of-text\n- Remind them of navigation keys when relevant (\"jump over with Right Option + s to see this live\")\n- If agents are still working with no change, say so briefly (\"Still working... Agent-001 is the furthest along\")\n- Reference specific agent names and tasks from the status output\n- Stop polling when status shows \"completed\"\n\nBetween polls, encourage the user to explore:\n> \"While we wait, try jumping around: \\`Ctrl+n\\` for dashboard, \\`Right Option + s\\` for the agent session, \\`Right Option + Shift + s\\` to jump back. I'll keep narrating here.\"\n\n### 5. After completion\n\nOnce the session shows \"completed\":\n\n- Show them what the agents built: \\`cd /tmp/sisyphus-tutorial-demo && git log --oneline\\`\n- Run the tests to prove the work: \\`cd /tmp/sisyphus-tutorial-demo && node --test test.js\\`\n- Show the session artifacts: find the session dir in \\`.sisyphus/sessions/\\` and show \\`roadmap.md\\`\n- Explain: \"Every session creates a roadmap, agent reports, and logs — all stored in .sisyphus/sessions/\"\n\n### 6. Proceed to wrap-up\n\nTell the user the demo is done. Then run:\n\\`\\`\\`\nsisyphus getting-started --tutorial 5\n\\`\\`\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep5(): void {\n // Gather codebase context for suggestions\n let recentCommits = '';\n let topLevelFiles = '';\n try {\n recentCommits = execSync('git log --oneline -15 2>/dev/null', { encoding: 'utf-8' }).trim();\n } catch { /* not in a git repo */ }\n try {\n topLevelFiles = execSync('ls -1 2>/dev/null', { encoding: 'utf-8' }).trim();\n } catch { /* ignore */ }\n\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 5: What's Next\n\n## Codebase Context\n<recent-commits>\n${recentCommits || '(no git repo detected)'}\n</recent-commits>\n\n<top-level-files>\n${topLevelFiles || '(could not list)'}\n</top-level-files>\n\n## Instructions for Claude\n\n### 1. Congratulate them\n\nTell them they've completed the tutorial and recap what they learned:\n- tmux basics (sessions, panes, navigation)\n- nvim basics for reviewing files\n- The sisyphus session model (separate tmux session for orchestrator + agents)\n- Monitoring with dashboard and keybinds\n- A live session lifecycle\n\n### 2. Navigation cheat sheet\n\n| Key | Action |\n|-----|--------|\n| \\`Ctrl+n\\` / \\`Ctrl+p\\` | Next/previous tmux window |\n| \\`Ctrl+h/j/k/l\\` | Navigate between panes |\n| \\`Right Option + s\\` | Jump to sisyphus agent session |\n| \\`Right Option + Shift + s\\` | Jump to dashboard |\n\n### 3. How to use sisyphus for REAL work\n\nThis is the most important part. Explain clearly:\n\n> **Sisyphus is for big, end-to-end features — the kind that need exploration,\n> planning, and parallel implementation across multiple systems.**\n>\n> You don't need to define the task precisely. Broad is fine — the orchestrator\n> will explore the codebase, write specs, plan phases, and break it down itself.\n\n**Real sisyphus sessions (from production use):**\n- \"Design and implement a human-in-the-loop agent inbox system\" — exploration, spec writing, DB schema, API endpoints, UI components, webhook integration, e2e validation\n- \"Build multi-user organization features — invites, privilege gating, org switcher, workspace sharing, credit tracking\" — touched auth, DB, API, UI, billing, permissions\n- \"Rework all 5 worker onboarding templates to match production pipeline patterns\" — mapped existing patterns, designed new architecture, implemented across templates, validated with e2e tests\n- \"Autonomous failure detection system across 8 sequential phases\" — monitoring, alerting, recovery, dashboard, with each phase building on the last\n- \"Comprehensive code quality audit — find and fix dead code, null handling, useless fallbacks\" — systematic codebase-wide analysis and cleanup\n- \"Implement @requirements.md\" — point it at a spec and let it go\n\n**NOT good for sisyphus:**\n- Five unrelated small tasks bundled together (\"fix the login bug, update the README, add a loading spinner\") — these aren't one feature, they're a todo list\n- Something Claude Code in plan mode would handle — plan mode already handles substantial single-engineer work. If it fits in one Claude session, just do it directly.\n- Quick fixes, bug fixes, small refactors — use regular Claude Code\n\n**How to start:**\nThe easiest way is the \\`/sisyphus:begin\\` slash command inside Claude Code. Just tell Claude\nwhat you want to build and it'll hand it off to sisyphus with the right context.\n\nOr directly: \\`sisyphus start \"your task\" -c \"any background context\"\\`\n\n### 4. Suggest real tasks for THEIR codebase\n\nLook at the recent commits and top-level files above. Based on what you can see of their project, suggest 2-3 concrete sisyphus-scale tasks they could try. Be specific to their codebase — reference actual directories, patterns, or areas you can see.\n\nIf there are no commits or files (e.g., they ran this from /tmp), skip this section.\n\nFormat as:\n> Based on your codebase, here are some tasks sisyphus would be great for:\n> - \"...\"\n> - \"...\"\n\n### 5. There's more to learn\n\nTell them:\n\n> There's actually a lot of depth to how sisyphus works — the design is intentional\n> and there's real reasoning behind why it does things the way it does. If you want\n> to understand the philosophy, or you want a deeper rundown on the dashboard,\n> monitoring, configuration, or how to steer sessions — just ask and I'll explain.\n\nIf the user says yes or asks to learn more, run \\`sisyphus getting-started --explain\\`\nand use its output to explain the system to them conversationally. Don't dump the whole\nthing — answer what they're curious about, using the reference as your source material.\n</claude-instructions>\n`);\n}\n\nfunction printExplain(): void {\n console.log(`\n<claude-instructions>\n# Sisyphus — Comprehensive Reference\n\nThis is a detailed reference for how sisyphus works. The user asked to understand\nsisyphus more deeply. Use this to answer their questions conversationally — don't dump\nthe whole thing. Read through it, then respond to what they're curious about.\n\n## Design Philosophy\n\nSisyphus is built on specific insights about how to get the best work out of LLM agents.\nThese aren't arbitrary — each design decision solves a real failure mode.\n\n### 1. The Orchestrator as \"Human-in-the-Loop\"\n\nWhen you use Claude Code effectively, YOU are the orchestrator — you review work,\nsteer direction, break problems down, and assign the next piece. Sisyphus automates\nthat human role. The orchestrator does what a skilled developer does when prompting\nClaude: explore the codebase, understand the problem, write specs, plan phases,\nassign focused work, review results, and iterate.\n\nThe strategy layer mirrors how developers actually work on end-to-end features:\nexplore, understand, spec, plan, implement, review, validate. The orchestrator\nfollows this same workflow, but runs it with parallel agents.\n\n### 2. Fresh Context Kills Shortcuts\n\nThe orchestrator is KILLED after every cycle and respawned fresh. This is the most\nimportant design decision.\n\nWhen an LLM accumulates context over a long session, it starts taking shortcuts.\nIt \"knows\" what it did earlier, so it skips re-reading, assumes things still hold,\nand builds on stale understanding. A fresh start forces honest reassessment every\ncycle — the orchestrator reads the actual state, not its memory of it.\n\nThis is inspired by adversarial training (think GANs) — better results come from\nadversarial pressure. Each fresh orchestrator effectively audits the previous cycle's\nwork because it has no stake in defending prior decisions. It sees the roadmap, the\nreports, the code — and judges them with fresh eyes.\n\n### 3. Single-Focus Agents\n\nEach agent gets ONE task with a fully self-contained instruction. No context switching,\nno juggling multiple concerns, no \"also while you're there could you...\"\n\nLLMs perform dramatically better when focused. An agent implementing a priority field\ndoesn't think about the stats endpoint. It reads the relevant context, does its one\nthing well, and reports back. The orchestrator handles decomposition — agents handle\nexecution.\n\n### 4. Shared Context Directory (Saved Research)\n\nEvery session has a context/ directory where agents save research, specs, plans, and\ndesign docs. These files persist across ALL cycles and are visible to the orchestrator\nand subsequent agents.\n\nThis means research is never repeated. Cycle 1 agents explore and write findings to\ncontext/explore-auth-system.md. Cycle 3 agents read those findings and build on them.\nKnowledge accumulates even though the orchestrator itself is stateless.\n\n### 5. Two-Layer Planning (Strategy + Roadmap)\n\nThe system maintains two documents at different abstraction levels:\n\n**strategy.md** — The high-level problem-solving map. What phases exist, what gates\nbetween them, what backtrack paths exist. Updated every few cycles when the shape of\nwork changes. Helps the orchestrator see the forest.\n\n**roadmap.md** — Working memory. Updated every cycle. Current Stage, Exit Criteria,\nActive Context, Next Steps. The orchestrator reads this first each cycle to understand\nwhere things stand. Helps the orchestrator see the trees.\n\nThis prevents the failure mode where a single document becomes either too abstract\nto act on or too detailed to show the big picture.\n\n### 6. Adversarial Review Is Built In\n\nThe orchestrator doesn't just implement — it runs mandatory critique cycles. After\nimplementation, review agents attack different dimensions: code reuse, quality,\nefficiency, correctness. Fix agents address the findings. Re-review until only nits\nremain. Multiple agents auditing each other produces better results than any single\nagent reviewing its own work.\n\nThe rule: never let 2+ stages complete without critique. Small issues compound into\narchitectural problems if unchecked.\n\n### 7. Evidence Over Assumptions\n\nValidation requires PROOF — command output, test results, HTTP responses. \"The code\nlooks correct\" is not evidence. \"All 14 tests pass\" is. This catches the gap between\ncode that looks right and code that works.\n\n## Architecture Overview\n\n\\`\\`\\`\n┌─────────────────────────────────────────────────────────────────────┐\n│ USER'S TMUX SESSION │\n│ │\n│ ┌─────────────────────────┐ ┌──────────────────────────────────┐ │\n│ │ Window 1: Claude Code │ │ Window 2: Dashboard (TUI) │ │\n│ │ │ │ │ │\n│ │ User's normal work │ │ Real-time session monitor │ │\n│ │ + this conversation │ │ Roadmap, agents, reports │ │\n│ │ │ │ Interactive controls │ │\n│ └─────────────────────────┘ └──────────────────────────────────┘ │\n└──────────────────────────────────┬──────────────────────────────────┘\n │ Right Option+s / Right Option+Shift+s\n ▼\n┌─────────────────────────────────────────────────────────────────────┐\n│ SISYPHUS TMUX SESSION │\n│ (created per sisyphus session) │\n│ │\n│ ┌──────────┬──────────┬──────────┬──────────┐ │\n│ │ Orch │ Agent │ Agent │ Agent │ ← panes │\n│ │ (yellow) │ (blue) │ (green) │ (magenta)│ │\n│ │ │ │ │ │ │\n│ │ Plans, │ Impl │ Tests │ Docs │ ← each is a │\n│ │ assigns, │ feature │ │ │ Claude Code │\n│ │ reviews │ │ │ │ instance │\n│ └──────────┴──────────┴──────────┴──────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n │\n ▼\n┌─────────────────────────────────────────────────────────────────────┐\n│ DAEMON (sisyphusd) │\n│ Background process via launchd │\n│ │\n│ Listens on ~/.sisyphus/daemon.sock │\n│ Manages session lifecycle, pane monitoring, state persistence │\n│ Polls panes to detect when agents/orchestrator finish │\n└─────────────────────────────────────────────────────────────────────┘\n\\`\\`\\`\n\n## The Session Lifecycle (in detail)\n\n\\`\\`\\`\n ┌──────────────────────────────────────────────────────────────────┐\n │ SESSION LIFECYCLE │\n │ │\n │ sisyphus start \"task\" │\n │ │ │\n │ ▼ │\n │ ┌─────────┐ spawn agents ┌──────────────┐ │\n │ │ Orch │ ──────────────────→ │ Agents work │ │\n │ │ plans │ then yields │ in parallel │ │\n │ └────┬────┘ └──────┬───────┘ │\n │ │ │ each calls │\n │ │ orchestrator │ sisyphus submit │\n │ │ is KILLED │ when done │\n │ │ ▼ │\n │ │ ┌──────────────┐ │\n │ │ │ All agents │ │\n │ │ │ finished? │ │\n │ │ └──────┬───────┘ │\n │ │ │ yes │\n │ │ ┌──────────────────────┘ │\n │ │ ▼ │\n │ │ ┌─────────┐ │\n │ └──── │ Respawn │ Fresh orchestrator with full state │\n │ next cycle │ Orch │ Reviews reports, plans next cycle │\n │ └────┬────┘ │\n │ │ │\n │ ▼ │\n │ ┌───────────────┐ ┌───────────┐ │\n │ │ More work │──yes──→ │ Spawn │ → (loop) │\n │ │ needed? │ │ agents │ │\n │ └───────┬───────┘ └───────────┘ │\n │ │ no │\n │ ▼ │\n │ ┌───────────────┐ │\n │ │ sisyphus │ │\n │ │ complete │ │\n │ └───────────────┘ │\n └──────────────────────────────────────────────────────────────────┘\n\\`\\`\\`\n\n**Key insight**: The orchestrator is STATELESS. It gets killed after each yield and\nrespawned fresh with the complete session state (roadmap, agent reports, cycle history).\nThis means it never runs out of context, no matter how many cycles a session takes.\n\n## The Dashboard\n\nThe dashboard is a real-time TUI that shows session state. Launch with \\`sisyphus dashboard\\`\nor it auto-opens when a session starts.\n\n**Dashboard sections:**\n- **Header**: Session ID, status, task description\n- **Roadmap**: Current strategic plan with checked/unchecked items\n- **Agents**: List of all agents with status, duration, and report summaries\n- **Cycles**: Orchestrator cycle history\n- **Messages**: Recent session messages\n\n**Dashboard keys:**\n| Key | Action |\n|-----|--------|\n| \\`m\\` | Message the orchestrator (steer direction mid-session) |\n| \\`w\\` | Jump to the sisyphus tmux session (watch agents work) |\n| \\`k\\` | Kill the session |\n| \\`r\\` | Resume a paused/completed session |\n| \\`q\\` | Quit the dashboard |\n| \\`↑/↓\\` | Scroll through content |\n| \\`Tab\\` | Cycle through sections |\n\n**The \\`m\\` key is the most powerful feature.** You can message the orchestrator at any time\nto course-correct: \"Focus on the API layer first\", \"Skip the tests for now\",\n\"The approach for auth is wrong, use JWT instead\". The orchestrator reads these\nmessages when it respawns each cycle.\n\n## Monitoring Strategy\n\nSisyphus sessions should be actively monitored. Here's what to watch for:\n\n**Things that go wrong:**\n- Agents stuck waiting for user input (they're autonomous — they shouldn't need input)\n- Agents going down rabbit holes or working on the wrong thing\n- Merge conflicts between agents touching the same files\n- Orchestrator spawning too many agents or too few\n- Agents crashing or getting killed unexpectedly\n\n**When to intervene:**\n- Use \\`m\\` in the dashboard to message the orchestrator with corrections\n- Use \\`sisyphus kill <id>\\` to stop a runaway session\n- Use \\`sisyphus resume <id> \"new instructions\"\\` to restart with different direction\n\n**Useful monitoring commands:**\n\\`\\`\\`\nsisyphus status <id> # Quick status check\nsisyphus status --verbose <id> # Full detail: roadmap, pane output, agent instructions\nsisyphus dashboard # Interactive TUI\ntail -f ~/.sisyphus/daemon.log # Daemon activity log\n\\`\\`\\`\n\n## The .sisyphus/ Directory\n\nEverything sisyphus does lives in a \\`.sisyphus/\\` directory at the root of your project.\nThis is project-local — each project gets its own. It contains:\n\n\\`\\`\\`\n.sisyphus/\n├── config.json # Project-specific config (model, poll interval, etc.)\n├── orchestrator.md # Optional custom orchestrator prompt override\n└── sessions/\n ├── <session-id-1>/ # Each session gets its own directory\n ├── <session-id-2>/\n └── ...\n\\`\\`\\`\n\nThere's also a global directory at \\`~/.sisyphus/\\` for the daemon socket, PID file,\nlogs, keybind scripts, and global config. But the session state — the roadmaps,\nreports, context files, cycle logs — all lives in your project's \\`.sisyphus/sessions/\\`.\n\n## Session Files\n\nEvery session creates a directory at \\`.sisyphus/sessions/<id>/\\` with:\n\n\\`\\`\\`\n.sisyphus/sessions/<id>/\n├── state.json # Session state (agents, cycles, status)\n├── roadmap.md # Strategic plan (updated by orchestrator each cycle)\n├── goal.md # Original task description\n├── strategy.md # High-level strategy notes\n├── logs/\n│ ├── cycle-000.md # What the orchestrator did in cycle 0\n│ ├── cycle-001.md # What it did in cycle 1, etc.\n│ └── ...\n├── reports/\n│ ├── agent-001-final.md # Agent's final report\n│ ├── agent-002-update.md # Agent's progress update\n│ └── ...\n├── prompts/ # System/user prompts sent to orchestrator and agents\n└── context/ # Shared context files for agents\n\\`\\`\\`\n\n## Configuration\n\n**Global config**: \\`~/.sisyphus/config.json\\`\n**Project config**: \\`.sisyphus/config.json\\` (overrides global)\n\nOptions:\n- \\`model\\` — Claude model for orchestrator and agents\n- \\`orchestratorPrompt\\` — Path to custom orchestrator prompt\n- \\`pollIntervalMs\\` — How often daemon checks pane status (default: 2000)\n\n## Starting Sessions — Best Practices\n\n**The /sisyphus:begin slash command** is the recommended way to start. Inside Claude Code:\n\\`\\`\\`\n/sisyphus:begin\n\\`\\`\\`\nThen describe your task. Claude will hand it off with the right context.\n\n**Direct CLI:**\n\\`\\`\\`\nsisyphus start \"task description\" -c \"background context\"\nsisyphus start \"Implement @requirements.md\" -n my-feature\n\\`\\`\\`\n\n**Reference files with @**: \\`sisyphus start \"Build @docs/spec.md\"\\` — the orchestrator\nwill read the referenced file as part of its planning.\n\n**The -c flag** adds background context the orchestrator sees but doesn't act on directly.\nUse it for constraints: \\`-c \"Don't modify the auth module, use the existing API\"\\`\n\n**The -n flag** gives the session a human-readable name for easier tracking.\n\n## CLI Command Reference\n\n| Command | Purpose |\n|---------|---------|\n| \\`sisyphus start \"task\"\\` | Start a new session |\n| \\`sisyphus status [id]\\` | Check session status |\n| \\`sisyphus status -v [id]\\` | Detailed status with pane output |\n| \\`sisyphus list\\` | List all sessions |\n| \\`sisyphus dashboard\\` | Open the TUI dashboard |\n| \\`sisyphus resume <id> \"msg\"\\` | Resume with new instructions |\n| \\`sisyphus kill <id>\\` | Stop a session |\n| \\`sisyphus doctor\\` | Check installation health |\n| \\`sisyphus setup\\` | Run setup/onboarding |\n| \\`sisyphus setup-keybind\\` | Install tmux keybinds |\n\n## Troubleshooting\n\n**Daemon not running:**\n\\`\\`\\`\nsisyphusd restart\n\\`\\`\\`\n\n**Keybinds not working (special characters appear):**\niTerm2 → Settings → Profiles → Keys → Right Option Key → Esc+\n\n**Agents stuck:** Check \\`sisyphus status --verbose <id>\\` to see pane output. If an\nagent is waiting for input, kill the session and restart with clearer instructions.\n\n**Dashboard not opening:** Run \\`sisyphus dashboard\\` manually. Must be inside tmux.\n\n**Session seems hung:** Check \\`tail -20 ~/.sisyphus/daemon.log\\` for errors.\nThe daemon polls panes every 2s — if a pane dies unexpectedly, it'll be detected.\n</claude-instructions>\n`);\n}\n\nconst STEPS: Array<() => void> = [printStep0, printStep1, printStep2, printStep3, printStep4, printStep5];\n\nexport function registerGettingStarted(program: Command): void {\n program\n .command('getting-started')\n .description('Interactive tutorial (best with Claude Code)')\n .option('--tutorial <step>', 'Tutorial step (0-5)', parseInt)\n .option('--explain', 'Comprehensive reference for how sisyphus works')\n .action((opts) => {\n if (opts.explain) {\n printExplain();\n return;\n }\n if (opts.tutorial !== undefined) {\n const step = opts.tutorial as number;\n if (step < 0 || step > 5 || Number.isNaN(step)) {\n console.error(`Invalid tutorial step: ${opts.tutorial}. Must be 0-5.`);\n process.exit(1);\n }\n STEPS[step]!();\n return;\n }\n if (!isClaudeCode()) {\n printNonClaudeMessage();\n return;\n }\n printStep0();\n });\n}\n","import type { Command } from 'commander';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nconst DEFAULT_CONFIG = {};\n\nconst ORCHESTRATOR_TEMPLATE = `# Custom Orchestrator Prompt\n\n<!-- This file overrides the default orchestrator system prompt. -->\n<!-- Delete this file to use the built-in prompt. -->\n<!-- See: https://github.com/silasrhyneer/sisyphi for details. -->\n`;\n\nexport function registerInit(program: Command): void {\n program\n .command('init')\n .description('Initialize sisyphus configuration for this project')\n .option('--orchestrator', 'Also create a custom orchestrator prompt template')\n .action((opts: { orchestrator?: boolean }) => {\n const cwd = process.cwd();\n const sisDir = join(cwd, '.sisyphus');\n const configPath = join(sisDir, 'config.json');\n\n if (existsSync(configPath)) {\n console.log(`Already initialized: ${configPath}`);\n return;\n }\n\n mkdirSync(sisDir, { recursive: true });\n writeFileSync(configPath, JSON.stringify(DEFAULT_CONFIG, null, 2) + '\\n', 'utf-8');\n console.log(`Created ${configPath}`);\n\n if (opts.orchestrator) {\n const orchPath = join(sisDir, 'orchestrator.md');\n if (!existsSync(orchPath)) {\n writeFileSync(orchPath, ORCHESTRATOR_TEMPLATE, 'utf-8');\n console.log(`Created ${orchPath}`);\n }\n }\n\n console.log('');\n console.log('Configuration options (add to .sisyphus/config.json):');\n console.log(' orchestratorEffort — \"low\" | \"medium\" | \"high\" | \"max\" (default: \"high\")');\n console.log(' agentEffort — \"low\" | \"medium\" | \"high\" | \"max\" (default: \"medium\")');\n console.log(' pollIntervalMs — Daemon poll interval in ms (default: 5000)');\n console.log(' autoUpdate — Auto-update daemon on restart (default: true)');\n console.log(' notifications — { enabled: boolean, sound: string } (default: enabled, Hero.aiff)');\n });\n}\n","import { execSync } from 'node:child_process';\nimport type { Command } from 'commander';\nimport { runOnboarding, type OnboardResult } from '../onboard.js';\nimport { ensureDaemonInstalled, isInstalled } from '../install.js';\nimport { setupTmuxKeybind, DEFAULT_KEY, DEFAULT_HOME_KEY } from '../tmux-setup.js';\n\nfunction getTmuxVersion(): string {\n try {\n return execSync('tmux -V', { encoding: 'utf-8', stdio: 'pipe' }).trim();\n } catch {\n return 'installed';\n }\n}\n\nfunction printResults(result: OnboardResult, daemonOk: boolean, keybindMsg: string): void {\n console.log('');\n console.log('Setting up Sisyphus...');\n console.log('');\n\n // tmux\n if (result.tmuxInstalled) {\n const detail = getTmuxVersion();\n console.log(` \\u2713 tmux: ${detail}${result.tmuxAutoInstalled ? ' (just installed)' : ''}`);\n } else {\n const hint = process.platform === 'darwin'\n ? 'Install Homebrew (https://brew.sh) then: brew install tmux'\n : 'apt install tmux (Debian/Ubuntu) or your package manager';\n console.log(` \\u2717 tmux: Not installed \\u2014 ${hint}`);\n }\n\n // tmux config\n if (result.tmuxDefaultsWritten) {\n console.log(' \\u2713 tmux config: Sensible defaults written to ~/.tmux.conf');\n }\n\n // Terminal\n if (process.platform === 'darwin') {\n if (result.terminal.isIterm) {\n console.log(` \\u2713 Terminal: ${result.terminal.name}`);\n } else {\n const name = result.terminal.name ? result.terminal.name : 'unknown';\n console.log(` \\u26a0 Terminal: ${name} \\u2014 iTerm2 recommended (https://iterm2.com)`);\n }\n }\n\n // iTerm option key\n if (result.itermOptionKey.checked) {\n if (result.itermOptionKey.allCorrect) {\n console.log(' \\u2713 Right Option Key: Esc+');\n } else {\n const profiles = result.itermOptionKey.incorrectProfiles.map((p) => `\"${p}\"`).join(', ');\n console.log(` \\u26a0 Right Option Key: Not set to Esc+ for ${profiles}`);\n console.log(' Fix: iTerm2 \\u2192 Settings \\u2192 Profiles \\u2192 Keys \\u2192 Right Option Key \\u2192 Esc+');\n }\n }\n\n // Daemon\n if (daemonOk) {\n console.log(' \\u2713 Daemon: Running');\n } else {\n console.log(' \\u2717 Daemon: Failed to start');\n }\n\n // Keybindings\n console.log(` \\u2713 Keybindings: ${keybindMsg}`);\n\n // /begin command\n if (result.command.installed) {\n console.log(` \\u2713 /begin command: ${result.command.path}${result.command.autoInstalled ? ' (just installed)' : ''}`);\n } else {\n console.log(' \\u2717 /begin command: Failed to install');\n }\n\n // Nvim\n if (result.nvim.installed) {\n const extra = result.nvim.autoInstalled ? ' (just installed)' : '';\n console.log(` \\u2713 Editor: nvim ${result.nvim.version}${extra}`);\n if (result.nvim.lazyVimInstalled) {\n console.log(' \\u2713 LazyVim: Starter config installed to ~/.config/nvim/');\n }\n } else {\n console.log(' \\u26a0 Editor: nvim not installed');\n if (process.platform === 'darwin') {\n console.log(' Install: brew install neovim');\n }\n }\n\n console.log('');\n console.log(\"Run 'sisyphus getting-started' for a usage guide.\");\n console.log('');\n}\n\nexport function registerSetup(program: Command): void {\n program\n .command('setup')\n .description('One-time setup: install dependencies, daemon, keybindings, and commands')\n .action(async () => {\n // 1. Onboarding (tmux, terminal, iterm, nvim, plugin)\n const result = runOnboarding();\n\n // 2. Daemon\n let daemonOk = false;\n try {\n await ensureDaemonInstalled();\n daemonOk = true;\n } catch {\n daemonOk = isInstalled();\n }\n\n // 3. Keybindings\n const keybindResult = setupTmuxKeybind();\n let keybindMsg: string;\n if (keybindResult.status === 'installed' || keybindResult.status === 'already-installed') {\n keybindMsg = `${DEFAULT_KEY} (cycle), ${DEFAULT_HOME_KEY} (dashboard)`;\n } else {\n keybindMsg = keybindResult.message;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,SAAS,QAAQ,GAAG;AAC3E,EAAAC,WAAU,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;AAC1C,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,6DAA6D;AACzE,UAAQ,IAAI,EAAE;AAChB;AAEA,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAe;AACrD,UAAQ,MAAM,IAAI,OAAO;AACzB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","mkdirSync","readFileSync","dirname","join","fileURLToPath","execSync","execSync","existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","homedir","join","join","homedir","existsSync","mkdirSync","writeFileSync","execSync","unlinkSync","resolve","readFileSync","rawSend","sleep","resolve","execSync","join","execSync","execSync","join","program","program","execSync","existsSync","join","resolve","program","join","existsSync","program","program","program","program","execSync","existsSync","readFileSync","readFileSync","existsSync","execSync","program","RESET","BOLD","DIM","program","program","program","program","resolve","program","program","rawSend","program","program","program","program","program","execSync","existsSync","execSync","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","join","fileURLToPath","plistPath","execSync","existsSync","program","program","execSync","dirname","join","fileURLToPath","join","dirname","fileURLToPath","execSync","program","existsSync","mkdirSync","writeFileSync","join","program","execSync","execSync","program","readFileSync","join","dirname","fileURLToPath","existsSync","mkdirSync"]}
1
+ {"version":3,"sources":["../src/cli/index.ts","../src/cli/commands/start.ts","../src/cli/install.ts","../src/cli/tmux-setup.ts","../src/cli/plugins.ts","../src/cli/client.ts","../src/cli/tmux.ts","../src/cli/commands/dashboard.ts","../src/cli/commands/spawn.ts","../src/cli/stdin.ts","../src/cli/commands/submit.ts","../src/cli/commands/yield.ts","../src/cli/commands/complete.ts","../src/cli/commands/continue.ts","../src/cli/commands/status.ts","../src/cli/commands/list.ts","../src/cli/commands/report.ts","../src/cli/commands/resume.ts","../src/cli/commands/kill.ts","../src/cli/commands/uninstall.ts","../src/cli/commands/notify.ts","../src/cli/commands/message.ts","../src/cli/commands/update-task.ts","../src/cli/commands/rollback.ts","../src/cli/commands/restart-agent.ts","../src/cli/commands/setup-keybind.ts","../src/cli/commands/doctor.ts","../src/cli/onboard.ts","../src/cli/commands/companion-context.ts","../src/cli/commands/getting-started.ts","../src/cli/commands/init.ts","../src/cli/commands/setup.ts"],"sourcesContent":["const nodeVersion = parseInt(process.versions.node.split('.')[0]!, 10);\nif (nodeVersion < 22) {\n console.error(`Sisyphus requires Node.js v22+ (current: v${process.versions.node})`);\n process.exit(1);\n}\n\nimport { Command } from 'commander';\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { registerStart } from './commands/start.js';\nimport { registerSpawn } from './commands/spawn.js';\nimport { registerSubmit } from './commands/submit.js';\nimport { registerYield } from './commands/yield.js';\nimport { registerComplete } from './commands/complete.js';\nimport { registerContinue } from './commands/continue.js';\nimport { registerStatus } from './commands/status.js';\nimport { registerList } from './commands/list.js';\nimport { registerReport } from './commands/report.js';\nimport { registerResume } from './commands/resume.js';\nimport { registerKill } from './commands/kill.js';\nimport { registerUninstall } from './commands/uninstall.js';\nimport { registerNotify } from './commands/notify.js';\nimport { registerMessage } from './commands/message.js';\nimport { registerUpdateTask } from './commands/update-task.js';\nimport { registerDashboard } from './commands/dashboard.js';\nimport { registerRollback } from './commands/rollback.js';\nimport { registerRestartAgent } from './commands/restart-agent.js';\nimport { registerSetupKeybind } from './commands/setup-keybind.js';\nimport { registerDoctor } from './commands/doctor.js';\nimport { registerCompanionContext } from './commands/companion-context.js';\nimport { registerGettingStarted } from './commands/getting-started.js';\nimport { registerInit } from './commands/init.js';\nimport { registerSetup } from './commands/setup.js';\nimport { globalDir } from '../shared/paths.js';\n\nconst program = new Command();\n\nprogram\n .name('sisyphus')\n .description('tmux-integrated orchestration daemon for Claude Code')\n .version(\n JSON.parse(\n readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf-8'),\n ).version,\n );\n\nprogram.configureHelp({\n sortSubcommands: false,\n});\n\nregisterStart(program);\nregisterSpawn(program);\nregisterSubmit(program);\nregisterReport(program);\nregisterYield(program);\nregisterComplete(program);\nregisterContinue(program);\nregisterStatus(program);\nregisterList(program);\nregisterResume(program);\nregisterKill(program);\nregisterUninstall(program);\nregisterNotify(program);\nregisterMessage(program);\nregisterUpdateTask(program);\nregisterDashboard(program);\nregisterRollback(program);\nregisterRestartAgent(program);\nregisterSetupKeybind(program);\nregisterDoctor(program);\nregisterCompanionContext(program);\nregisterGettingStarted(program);\nregisterInit(program);\nregisterSetup(program);\n\nprogram.addHelpText('after', `\nExamples:\n $ sisyphus start \"Implement auth system\" Start a new session\n $ sisyphus start \"Build @requirements.md\" -n auth Start with a name and requirements reference\n $ sisyphus status Check current sessions\n $ sisyphus dashboard Open the TUI\n $ sisyphus doctor Verify installation\n\nRun 'sisyphus getting-started' for a complete usage guide.\n`);\n\n// Show welcome on first run (before ~/.sisyphus exists)\nconst args = process.argv.slice(2);\nconst firstArg = args[0];\nconst skipWelcome = ['doctor', 'getting-started', 'help', '--help', '-h', 'init', 'setup', 'uninstall', '--version', '-V'];\nif (!existsSync(globalDir()) && firstArg && !skipWelcome.includes(firstArg)) {\n mkdirSync(globalDir(), { recursive: true });\n console.log('');\n console.log(\" Welcome to Sisyphus. Run 'sisyphus setup' to get started.\");\n console.log('');\n}\n\nprogram.parseAsync(process.argv).catch((err: Error) => {\n console.error(err.message);\n process.exit(1);\n});\n","import type { Command } from 'commander';\nimport { execSync } from 'node:child_process';\nimport { sendRequest } from '../client.js';\nimport { getTmuxSession, isTmuxInstalled } from '../tmux.js';\nimport { shellQuote } from '../../shared/shell.js';\nimport { openDashboardWindow } from './dashboard.js';\nimport type { Request } from '../../shared/protocol.js';\n\n\nexport function registerStart(program: Command): void {\n program\n .command('start')\n .description('Start a new sisyphus session')\n .argument('<task>', 'Task description for the orchestrator')\n .option('-c, --context <context>', 'Background context for the orchestrator')\n .option('-n, --name <name>', 'Human-readable name for the session')\n .option('--no-tmux-check', 'Skip the tmux session check')\n .action(async (task: string, opts: { context?: string; name?: string; tmuxCheck?: boolean }) => {\n const cwd = process.env['SISYPHUS_CWD'] ?? process.cwd();\n\n if (!process.env['TMUX'] && opts.tmuxCheck !== false) {\n if (!isTmuxInstalled()) {\n console.error('Error: tmux is not installed. Sisyphus requires tmux for agent panes.');\n console.error(' Install: brew install tmux (macOS) or apt install tmux (Linux)');\n console.error(' Then: tmux new-session');\n process.exit(1);\n }\n console.error('Error: Not running inside a tmux session.');\n console.error(' Sisyphus uses tmux to manage agent panes.');\n console.error(' Start a tmux session first: tmux new-session');\n console.error('');\n console.error(' To skip this check: sisyphus start --no-tmux-check \"task\"');\n process.exit(1);\n }\n const request: Request = { type: 'start', task, context: opts.context, cwd, name: opts.name };\n const response = await sendRequest(request);\n if (response.ok) {\n const sessionId = response.data?.sessionId as string;\n const tmuxSessionName = response.data?.tmuxSessionName as string | undefined;\n // Tag the user's current tmux session so it's part of the same cycle group\n if (process.env['TMUX']) {\n try {\n execSync(`tmux set-option @sisyphus_cwd ${shellQuote(cwd)}`, { stdio: 'ignore' });\n } catch { /* not in tmux or tmux error — ignore */ }\n\n try {\n const tmuxSession = getTmuxSession();\n if (openDashboardWindow(tmuxSession, cwd)) {\n console.log(`Dashboard opened in tmux window \"sisyphus-dashboard\"`);\n }\n } catch { /* dashboard launch failed — non-fatal */ }\n }\n\n console.log(`Task handed off to sisyphus orchestrator (session ${sessionId})`);\n console.log(`The orchestrator and its agents will handle this task autonomously — no further action needed from you.`);\n\n if (tmuxSessionName) {\n console.log(`\\nTmux session: ${tmuxSessionName}`);\n console.log(` tmux attach -t ${tmuxSessionName}`);\n }\n\n console.log(`\\nMonitor:`);\n console.log(` sisyphus status ${sessionId} # agents, cycles, reports`);\n console.log(` tail -f ~/.sisyphus/daemon.log # daemon activity`);\n console.log(`\\nControl:`);\n console.log(` sisyphus resume ${sessionId} \"new instructions\" # respawn with follow-up`);\n console.log(` sisyphus kill ${sessionId} # stop all agents and orchestrator`);\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { connect } from 'node:net';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { daemonLogPath, daemonUpdatingPath, globalDir, socketPath } from '../shared/paths.js';\nimport { type SetupResult, removeTmuxKeybind, setupTmuxKeybind } from './tmux-setup.js';\nimport { ensureRequiredPlugins } from './plugins.js';\n\nconst PLIST_LABEL = 'com.sisyphus.daemon';\nconst PLIST_FILENAME = `${PLIST_LABEL}.plist`;\n\nfunction launchAgentDir(): string {\n return join(homedir(), 'Library', 'LaunchAgents');\n}\n\nfunction plistPath(): string {\n return join(launchAgentDir(), PLIST_FILENAME);\n}\n\nfunction daemonBinPath(): string {\n // In bundled output, cli.js and daemon.js are siblings in dist/\n const installDir = dirname(fileURLToPath(import.meta.url));\n return resolve(installDir, 'daemon.js');\n}\n\nfunction generatePlist(nodePath: string, daemonPath: string, logPath: string): string {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${PLIST_LABEL}</string>\n <key>ProgramArguments</key>\n <array>\n <string>${nodePath}</string>\n <string>${daemonPath}</string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>StandardOutPath</key>\n <string>${logPath}</string>\n <key>StandardErrorPath</key>\n <string>${logPath}</string>\n</dict>\n</plist>\n`;\n}\n\nexport function isInstalled(): boolean {\n return existsSync(plistPath());\n}\n\nexport async function ensureDaemonInstalled(): Promise<void> {\n if (process.platform !== 'darwin') return;\n\n if (!isInstalled()) {\n const nodePath = process.execPath;\n const daemonPath = daemonBinPath();\n const logPath = daemonLogPath();\n\n mkdirSync(globalDir(), { recursive: true });\n mkdirSync(launchAgentDir(), { recursive: true });\n\n const plist = generatePlist(nodePath, daemonPath, logPath);\n writeFileSync(plistPath(), plist, 'utf8');\n\n execSync(`launchctl load -w ${plistPath()}`);\n\n const keybindResult = setupTmuxKeybind();\n\n await ensureRequiredPlugins(process.cwd());\n\n printGettingStarted(keybindResult);\n }\n\n await waitForDaemon();\n}\n\nexport async function uninstallDaemon(purge: boolean): Promise<void> {\n if (process.platform !== 'darwin') {\n console.log('Auto-install is only supported on macOS.');\n return;\n }\n\n const plist = plistPath();\n if (existsSync(plist)) {\n try {\n execSync(`launchctl unload -w ${plist}`, { stdio: 'pipe' });\n } catch {\n // already unloaded or not registered — ignore\n }\n unlinkSync(plist);\n console.log('Daemon unloaded and plist removed.');\n } else {\n console.log('Daemon is not installed (plist not found).');\n }\n\n removeTmuxKeybind();\n\n if (purge) {\n const dir = globalDir();\n if (existsSync(dir)) {\n rmSync(dir, { recursive: true, force: true });\n console.log(`Removed ${dir}`);\n }\n }\n}\n\nfunction printGettingStarted(keybindResult: SetupResult): void {\n const lines = [\n '',\n 'Sisyphus installed — daemon running via launchd.',\n '',\n ];\n\n if (keybindResult.status === 'installed') {\n lines.push(`Tmux keybind: ${keybindResult.message}`, '');\n } else if (keybindResult.status === 'conflict') {\n lines.push(`Keybind: ${keybindResult.message}`, '');\n }\n\n lines.push(\n 'Run `sisyphus getting-started` for a complete usage guide.',\n '',\n );\n\n console.log(lines.join('\\n'));\n}\n\nfunction testConnection(): Promise<void> {\n return new Promise((resolve, reject) => {\n const sock = connect(socketPath());\n sock.on('connect', () => { sock.destroy(); resolve(); });\n sock.on('error', (err) => { sock.destroy(); reject(err); });\n });\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function waitForDaemon(maxWaitMs = 6000): Promise<void> {\n const start = Date.now();\n let updatingLogged = false;\n\n while (Date.now() - start < maxWaitMs) {\n // Extend timeout if daemon is updating\n const updatingPath = daemonUpdatingPath();\n if (existsSync(updatingPath)) {\n if (!updatingLogged) {\n try {\n const version = readFileSync(updatingPath, 'utf-8').trim();\n console.log(`Updating sisyphus to ${version}...`);\n } catch {\n console.log('Updating sisyphus...');\n }\n updatingLogged = true;\n }\n maxWaitMs = Math.max(maxWaitMs, 30000);\n }\n\n if (existsSync(socketPath())) {\n try {\n await testConnection();\n return;\n } catch {\n // not ready yet\n }\n }\n await sleep(300);\n }\n throw new Error(`Daemon did not start within ${maxWaitMs}ms. Check ${daemonLogPath()}`);\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, unlinkSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { globalDir } from '../shared/paths.js';\n\nexport const DEFAULT_KEY = 'M-s';\nexport const DEFAULT_HOME_KEY = 'M-S';\n\nconst SISYPHUS_CONF_MARKER = '# sisyphus-managed — do not edit';\n\nexport function cycleScriptPath(): string {\n return join(globalDir(), 'bin', 'sisyphus-cycle');\n}\n\nexport function homeScriptPath(): string {\n return join(globalDir(), 'bin', 'sisyphus-home');\n}\n\nexport function killPaneScriptPath(): string {\n return join(globalDir(), 'bin', 'sisyphus-kill-pane');\n}\n\nexport function sisyphusTmuxConfPath(): string {\n return join(globalDir(), 'tmux.conf');\n}\n\nfunction userTmuxConfPath(): string | null {\n // Check both standard locations, preferring whichever exists\n const dotfile = join(homedir(), '.tmux.conf');\n const xdg = join(homedir(), '.config', 'tmux', 'tmux.conf');\n if (existsSync(xdg)) return xdg;\n if (existsSync(dotfile)) return dotfile;\n return null;\n}\n\nconst CYCLE_SCRIPT = `#!/bin/bash\ncwd=$(tmux show-option -v @sisyphus_cwd 2>/dev/null)\n[ -z \"$cwd\" ] && exit 0\ncurrent=$(tmux display-message -p '#{session_name}')\nsessions=()\nwhile IFS= read -r name; do\n scwd=$(tmux show-option -t \"$name\" -v @sisyphus_cwd 2>/dev/null)\n [ \"$scwd\" = \"$cwd\" ] && sessions+=(\"$name\")\ndone < <(tmux list-sessions -F '#{session_name}')\n(( \\${#sessions[@]} <= 1 )) && exit 0\nfor (( i=0; i<\\${#sessions[@]}; i++ )); do\n if [ \"\\${sessions[$i]}\" = \"$current\" ]; then\n next=$(( (i + 1) % \\${#sessions[@]} ))\n tmux switch-client -t \"\\${sessions[$next]}\"\n exit 0\n fi\ndone\ntmux switch-client -t \"\\${sessions[0]}\"\n`;\n\nconst HOME_SCRIPT = `#!/bin/bash\n# Jump to the home (non-sisyphus) session that has the dashboard window\ncwd=$(tmux show-option -v @sisyphus_cwd 2>/dev/null)\n[ -z \"$cwd\" ] && exit 0\nwhile IFS= read -r name; do\n # Skip sisyphus agent/orchestrator sessions\n case \"$name\" in sisyphus-*) continue ;; esac\n scwd=$(tmux show-option -t \"$name\" -v @sisyphus_cwd 2>/dev/null)\n if [ \"$scwd\" = \"$cwd\" ]; then\n tmux switch-client -t \"$name\"\n # Focus the dashboard window by stored ID (not name)\n dwid=$(tmux show-option -t \"$name\" -v @sisyphus_dashboard 2>/dev/null)\n [ -n \"$dwid\" ] && tmux select-window -t \"$dwid\" 2>/dev/null\n exit 0\n fi\ndone < <(tmux list-sessions -F '#{session_name}')\n`;\n\nconst KILL_PANE_SCRIPT = `#!/bin/bash\n# prefix-x override for sisyphus sessions.\n# If this is the last pane, switch to the home session before killing.\nsession=$(tmux display-message -p '#{session_name}')\npane_count=$(tmux list-panes -t \"$session\" -F '#{pane_id}' | wc -l | tr -d ' ')\n\nif [ \"$pane_count\" -le 1 ]; then\n # Last pane — find home session, switch there, then kill sisyphus session\n cwd=$(tmux show-option -t \"$session\" -v @sisyphus_cwd 2>/dev/null)\n if [ -n \"$cwd\" ]; then\n while IFS= read -r name; do\n case \"$name\" in sisyphus-*) continue ;; esac\n scwd=$(tmux show-option -t \"$name\" -v @sisyphus_cwd 2>/dev/null)\n if [ \"$scwd\" = \"$cwd\" ]; then\n tmux switch-client -t \"$name\"\n dwid=$(tmux show-option -t \"$name\" -v @sisyphus_dashboard 2>/dev/null)\n [ -n \"$dwid\" ] && tmux select-window -t \"$dwid\" 2>/dev/null\n tmux kill-session -t \"$session\"\n exit 0\n fi\n done < <(tmux list-sessions -F '#{session_name}')\n fi\n # No home session found — just kill the pane\n tmux kill-pane\nelse\n # Multiple panes — kill this one and rebalance\n tmux kill-pane\n tmux select-layout even-horizontal\nfi\n`;\n\nexport function installCycleScript(): void {\n mkdirSync(join(globalDir(), 'bin'), { recursive: true });\n const scriptPath = cycleScriptPath();\n writeFileSync(scriptPath, CYCLE_SCRIPT, 'utf8');\n chmodSync(scriptPath, 0o755);\n}\n\nexport function installHomeScript(): void {\n mkdirSync(join(globalDir(), 'bin'), { recursive: true });\n const scriptPath = homeScriptPath();\n writeFileSync(scriptPath, HOME_SCRIPT, 'utf8');\n chmodSync(scriptPath, 0o755);\n}\n\nexport function installKillPaneScript(): void {\n mkdirSync(join(globalDir(), 'bin'), { recursive: true });\n const scriptPath = killPaneScriptPath();\n writeFileSync(scriptPath, KILL_PANE_SCRIPT, 'utf8');\n chmodSync(scriptPath, 0o755);\n}\n\nexport function getExistingBinding(key: string): string | null {\n try {\n const output = execSync('tmux list-keys', { stdio: ['pipe', 'pipe', 'pipe'] }).toString();\n for (const line of output.split('\\n')) {\n // lines look like: bind-key -T root M-s run-shell ...\n // or: bind-key -T root M-s run-shell ...\n if (line.includes(key)) {\n const parts = line.trim().split(/\\s+/);\n // Find the key in parts and check it matches exactly (not as substring of another key)\n const keyIdx = parts.indexOf(key);\n if (keyIdx !== -1) {\n return line.trim();\n }\n }\n }\n return null;\n } catch {\n // tmux not running or not available\n return null;\n }\n}\n\nexport function isSisyphusBinding(binding: string): boolean {\n return binding.includes('sisyphus');\n}\n\nexport type SetupResult =\n | { status: 'installed'; message: string }\n | { status: 'already-installed'; message: string }\n | { status: 'conflict'; message: string; existingBinding: string };\n\nexport function setupTmuxKeybind(key: string = DEFAULT_KEY, homeKey: string = DEFAULT_HOME_KEY): SetupResult {\n installCycleScript();\n installHomeScript();\n installKillPaneScript();\n\n // Check for existing binding before writing anything\n const existing = getExistingBinding(key);\n if (existing !== null && !isSisyphusBinding(existing)) {\n return {\n status: 'conflict',\n message: `Tmux key ${key} is already bound to something else. Run \"sisyphus setup-keybind <key>\" to use a different key.`,\n existingBinding: existing,\n };\n }\n\n // Check home key for conflicts too (only if different from cycle key)\n if (homeKey !== key) {\n const existingHome = getExistingBinding(homeKey);\n if (existingHome !== null && !isSisyphusBinding(existingHome)) {\n return {\n status: 'conflict',\n message: `Tmux key ${homeKey} is already bound to something else.`,\n existingBinding: existingHome,\n };\n }\n }\n\n // Write ~/.sisyphus/tmux.conf with keybindings + prefix-x override\n const confPath = sisyphusTmuxConfPath();\n const cycleBinding = `bind-key -T root ${key} run-shell ${cycleScriptPath()}`;\n const homeBinding = `bind-key -T root ${homeKey} run-shell ${homeScriptPath()}`;\n const killPaneOverride = `bind-key -T prefix x if-shell \"tmux display-message -p '#{session_name}' | grep -q '^sisyphus-'\" \"run-shell ${killPaneScriptPath()}\" \"kill-pane \\\\; select-layout even-horizontal\"`;\n writeFileSync(confPath, `${SISYPHUS_CONF_MARKER}\\n${cycleBinding}\\n${homeBinding}\\n${killPaneOverride}\\n`, 'utf8');\n\n // Append source line to tmux.conf if not already there\n const userConf = userTmuxConfPath();\n const sourceLine = `source-file ${confPath}`;\n const markedSourceLine = `${sourceLine} ${SISYPHUS_CONF_MARKER}`;\n let persistedToConf = false;\n\n if (userConf !== null) {\n const contents = readFileSync(userConf, 'utf8');\n if (!contents.includes(confPath)) {\n const separator = contents.endsWith('\\n') ? '' : '\\n';\n writeFileSync(userConf, `${contents}${separator}${markedSourceLine}\\n`, 'utf8');\n }\n persistedToConf = true;\n }\n\n // Apply bindings live if tmux is running\n try {\n execSync(`tmux bind-key -T root ${key} run-shell ${cycleScriptPath()}`, { stdio: 'pipe' });\n execSync(`tmux bind-key -T root ${homeKey} run-shell ${homeScriptPath()}`, { stdio: 'pipe' });\n execSync(`tmux ${killPaneOverride}`, { stdio: 'pipe' });\n } catch {\n // tmux not running — bindings will take effect on next session start\n }\n\n if (existing !== null && isSisyphusBinding(existing)) {\n return {\n status: 'already-installed',\n message: `Tmux keybindings ${key} (cycle) and ${homeKey} (dashboard) already configured for sisyphus.`,\n };\n }\n\n const persistNote = persistedToConf\n ? ''\n : `\\nNote: No tmux.conf found. Add this to your tmux config for persistence:\\n source-file ${confPath}`;\n return {\n status: 'installed',\n message: `Tmux keybindings set: ${key} cycles sessions, ${homeKey} jumps to dashboard${persistNote}`,\n };\n}\n\nexport function removeTmuxKeybind(): void {\n // Remove source line from user's tmux.conf\n const confPath = sisyphusTmuxConfPath();\n // Check both possible tmux.conf locations\n for (const candidate of [join(homedir(), '.tmux.conf'), join(homedir(), '.config', 'tmux', 'tmux.conf')]) {\n if (existsSync(candidate)) {\n const contents = readFileSync(candidate, 'utf8');\n const filtered = contents\n .split('\\n')\n .filter((line) => !line.includes(confPath))\n .join('\\n');\n if (filtered !== contents) {\n writeFileSync(candidate, filtered, 'utf8');\n }\n }\n }\n\n // Remove ~/.sisyphus/tmux.conf\n if (existsSync(confPath)) {\n unlinkSync(confPath);\n }\n\n // Restore default prefix-x binding if tmux is running\n try {\n execSync('tmux bind-key -T prefix x kill-pane \\\\; select-layout even-horizontal', { stdio: 'pipe' });\n } catch {\n // tmux not running\n }\n\n // Remove scripts\n for (const scriptPath of [cycleScriptPath(), homeScriptPath(), killPaneScriptPath()]) {\n if (existsSync(scriptPath)) {\n unlinkSync(scriptPath);\n }\n }\n}\n","import { execSync } from 'node:child_process';\nimport { loadConfig } from '../shared/config.js';\nimport { resolveInstalledPlugin } from '../daemon/plugins.js';\n\nfunction exec(cmd: string): string {\n try {\n return execSync(cmd, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();\n } catch {\n return '';\n }\n}\n\nfunction isMarketplaceInstalled(marketplace: string): boolean {\n const output = exec('claude plugins marketplace list');\n return output.includes(marketplace);\n}\n\nfunction installMarketplace(marketplace: string): void {\n console.log(`Adding marketplace: ${marketplace}`);\n execSync(`claude plugins marketplace add CaptainCrouton89/${marketplace}`, { stdio: 'inherit' });\n}\n\nfunction installPlugin(key: string): void {\n console.log(`Installing plugin: ${key}`);\n execSync(`claude plugins install ${key} --scope user`, { stdio: 'inherit' });\n}\n\nexport async function ensureRequiredPlugins(cwd: string): Promise<void> {\n const config = loadConfig(cwd);\n const required = config.requiredPlugins;\n if (!required || required.length === 0) return;\n\n for (const plugin of required) {\n const key = `${plugin.name}@${plugin.marketplace}`;\n const existing = resolveInstalledPlugin(key);\n if (existing) continue;\n\n console.log(`Required plugin ${key} not found — installing...`);\n\n if (!isMarketplaceInstalled(plugin.marketplace)) {\n installMarketplace(plugin.marketplace);\n }\n\n installPlugin(key);\n\n // Verify\n const verified = resolveInstalledPlugin(key);\n if (verified) {\n console.log(`Installed ${key} → ${verified}`);\n } else {\n console.warn(`Warning: failed to verify ${key} installation`);\n }\n }\n}\n","import type { Request, Response } from '../shared/protocol.js';\nimport { rawSend as sharedRawSend } from '../shared/client.js';\nimport { ensureDaemonInstalled, waitForDaemon } from './install.js';\n\nexport function rawSend(request: Request): Promise<Response> {\n return sharedRawSend(request, 10_000);\n}\n\nexport async function sendRequest(request: Request): Promise<Response> {\n const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n const MAX_ATTEMPTS = 5;\n const RETRY_DELAY_MS = 2000;\n let installedDaemon = false;\n let lastErr: unknown;\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n try {\n return await rawSend(request);\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT' && code !== 'ECONNREFUSED') {\n throw err;\n }\n\n if (attempt === MAX_ATTEMPTS) break;\n\n if (process.platform === 'darwin' && !installedDaemon) {\n installedDaemon = true;\n await ensureDaemonInstalled();\n await waitForDaemon(5000);\n } else {\n process.stderr.write(`Daemon not ready, retrying (${attempt}/${MAX_ATTEMPTS - 1})...\\n`);\n await sleep(RETRY_DELAY_MS);\n }\n }\n }\n\n if (process.platform !== 'darwin') {\n const lines = [`Sisyphus daemon is not running.`];\n if (process.platform === 'linux') {\n lines.push(\n '',\n ' Start options:',\n ' sisyphusd & # Run in background',\n ' nohup sisyphusd > ~/.sisyphus/daemon.log 2>&1 & # Persist after logout',\n '',\n ' For systemd (recommended):',\n ' # Create ~/.config/systemd/user/sisyphus.service with:',\n ' # [Unit]',\n ' # Description=Sisyphus Daemon',\n ' # [Service]',\n ' # ExecStart=/usr/bin/env node <path-to-sisyphusd>',\n ' # Restart=always',\n ' # [Install]',\n ' # WantedBy=default.target',\n ' systemctl --user enable --now sisyphus',\n );\n } else {\n lines.push(\n '',\n ' Start it manually: sisyphusd &',\n );\n }\n lines.push(\n '',\n ' Diagnose: sisyphus doctor',\n ' Logs: tail -f ~/.sisyphus/daemon.log',\n );\n throw new Error(lines.join('\\n'));\n }\n throw lastErr;\n}\n","import { execSync } from 'node:child_process';\n\nexport function isTmuxInstalled(): boolean {\n try {\n execSync('which tmux', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nexport function assertTmux(): void {\n if (!process.env.TMUX) {\n throw new Error('Not running inside a tmux pane. Sisyphus requires tmux.');\n }\n}\n\nexport function getTmuxSession(): string {\n assertTmux();\n return execSync('tmux display-message -p \"#{session_name}\"', { encoding: 'utf8' }).trim();\n}\n\n","import type { Command } from 'commander';\nimport { join } from 'node:path';\nimport { execSync } from 'node:child_process';\nimport { assertTmux, getTmuxSession } from '../tmux.js';\nimport { shellQuote } from '../../shared/shell.js';\n\n\n/**\n * Opens the dashboard in a new tmux window (for background use, e.g. from `start`).\n *\n * Tracks the window by its tmux window ID stored in the @sisyphus_dashboard\n * session option — not by window name, which is fragile (renames, collisions).\n * The \"; exit\" suffix closes the window when the TUI exits.\n *\n * Returns true if a new dashboard was created, false if an existing one was focused.\n */\nexport function openDashboardWindow(tmuxSession: string, cwd: string): boolean {\n // Check for existing dashboard by stored window ID\n try {\n const storedId = execSync(\n `tmux show-option -t ${shellQuote(tmuxSession)} -v @sisyphus_dashboard`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] },\n ).trim();\n\n if (storedId) {\n try {\n execSync(\n `tmux display-message -t ${shellQuote(storedId)} -p \"#{window_id}\"`,\n { stdio: 'pipe' },\n );\n execSync(`tmux select-window -t ${shellQuote(storedId)}`, { stdio: 'pipe' });\n return false;\n } catch {\n // Window is gone — fall through to create a new one\n }\n }\n } catch {\n // Option not set — fall through to create\n }\n\n const tuiPath = join(import.meta.dirname, 'tui.js');\n\n const windowId = execSync(\n `tmux new-window -n \"sisyphus-dashboard\" -c ${shellQuote(cwd)} -P -F \"#{window_id}\"`,\n { encoding: 'utf-8' },\n ).trim();\n\n const cmd = `node ${shellQuote(tuiPath)} --cwd ${shellQuote(cwd)}; exit`;\n execSync(\n `tmux send-keys -t ${shellQuote(windowId)} ${shellQuote(cmd)} Enter`,\n );\n\n execSync(\n `tmux set-option -t ${shellQuote(tmuxSession)} @sisyphus_dashboard ${shellQuote(windowId)}`,\n { stdio: 'pipe' },\n );\n\n return true;\n}\n\nexport function registerDashboard(program: Command): void {\n program\n .command('dashboard')\n .description('Launch the TUI dashboard for monitoring and managing sessions')\n .action(async () => {\n assertTmux();\n const tuiPath = join(import.meta.dirname, 'tui.js');\n execSync(`node ${shellQuote(tuiPath)} --cwd ${shellQuote(process.cwd())}`, {\n stdio: 'inherit',\n });\n });\n}\n","import type { Command } from 'commander';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { readStdin } from '../stdin.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerSpawn(program: Command): void {\n program\n .command('spawn')\n .description('Spawn a new agent (orchestrator only)')\n .argument('[instruction]', 'Task instruction for the agent')\n .option('--agent-type <type>', 'Agent role label (default: worker)', 'worker')\n .requiredOption('--name <name>', 'Agent name')\n .option('--instruction <instruction>', 'Task instruction for the agent (or pipe via stdin)')\n .option('--repo <name>', 'Repo subdirectory to use for this agent')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (positionalInstruction: string | undefined, opts: { agentType: string; name: string; instruction?: string; repo?: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const instruction = opts.instruction ?? positionalInstruction ?? await readStdin();\n if (!instruction) {\n console.error('Error: --instruction is required (or pipe via stdin)');\n process.exit(1);\n }\n\n const sisyphusCwd = process.env['SISYPHUS_CWD'] ?? process.cwd();\n\n if (opts.repo && (opts.repo.includes('/') || opts.repo.includes('..') || opts.repo.includes('\\\\'))) {\n console.error('Error: --repo must be a directory name, not a path');\n process.exit(1);\n }\n\n if (opts.repo && opts.repo !== '.') {\n const repoPath = join(sisyphusCwd, opts.repo);\n if (!existsSync(repoPath)) {\n console.error(`Error: repo directory does not exist: ${repoPath}`);\n process.exit(1);\n }\n }\n\n const request: Request = {\n type: 'spawn',\n sessionId,\n agentType: opts.agentType,\n name: opts.name,\n instruction,\n ...(opts.repo ? { repo: opts.repo } : {}),\n };\n const response = await sendRequest(request);\n if (response.ok) {\n const agentId = response.data?.agentId as string;\n console.log(`Agent spawned: ${agentId}`);\n console.log(\"Run `sisyphus yield` when done spawning agents.\");\n } else {\n console.error(`Error: ${response.error}`);\n if (response.error?.includes(\"Unknown session\")) console.error(\"Hint: run `sisyphus list` to see active sessions.\");\n process.exit(1);\n }\n });\n}\n","export function readStdin(): Promise<string | null> {\n if (process.stdin.isTTY) return Promise.resolve(null);\n\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk: Buffer) => chunks.push(chunk));\n process.stdin.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf-8').trim();\n resolve(text || null);\n });\n process.stdin.on('error', reject);\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { readStdin } from '../stdin.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerSubmit(program: Command): void {\n program\n .command('submit')\n .description('Submit work report and exit (agent only)')\n .option('--report <report>', 'Work report (or pipe via stdin)')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { report?: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n const agentId = process.env.SISYPHUS_AGENT_ID;\n if (!sessionId || !agentId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID (and SISYPHUS_AGENT_ID) environment variables');\n process.exit(1);\n }\n\n const report = opts.report ?? await readStdin();\n if (!report) {\n console.error('Error: provide --report or pipe content via stdin');\n process.exit(1);\n }\n\n const request: Request = { type: 'submit', sessionId, agentId, report };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Report submitted successfully');\n console.log('Your pane will close. The orchestrator resumes when all agents finish.');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { readStdin } from '../stdin.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerYield(program: Command): void {\n program\n .command('yield')\n .description('Yield control back to daemon (orchestrator only)')\n .option('--prompt <text>', 'Instructions for the next orchestrator cycle (or pipe via stdin)')\n .option('--mode <mode>', 'System prompt mode for next cycle (planning, implementation, validation)')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { prompt?: string; mode?: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const nextPrompt = opts.prompt ?? await readStdin() ?? undefined;\n\n const request: Request = { type: 'yield', sessionId, agentId: 'orchestrator', nextPrompt, mode: opts.mode };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Yielded. Waiting for agents to complete.');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerComplete(program: Command): void {\n program\n .command('complete')\n .description('Mark session as completed (orchestrator only)')\n .requiredOption('--report <report>', 'Final completion report')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { report: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const request: Request = { type: 'complete', sessionId, report: opts.report };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Session completed.');\n console.log(`\\nTo keep working in this session:`);\n console.log(` sisyphus continue # reactivate session and clear roadmap for new work`);\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerContinue(program: Command): void {\n program\n .command('continue')\n .description('Clear roadmap and continue working on a completed session (stays in current cycle)')\n .addHelpText('after', '\\n Use `continue` when a session completed but you want to add more work.\\n Use `resume` when you want to restart with specific new instructions.\\n')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const request: Request = { type: 'continue', sessionId };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Session reactivated. Roadmap cleared.');\n console.log('\\nThe previous roadmap has been wiped — you are starting fresh.');\n console.log('Consider writing a new roadmap before spawning agents.');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport type { Session, Agent, OrchestratorCycle } from '../../shared/types.js';\nimport { computeActiveTimeMs } from '../../shared/utils.js';\nimport { roadmapPath, cycleLogPath } from '../../shared/paths.js';\nimport { formatDuration, statusColor } from '../../shared/format.js';\n\nconst COLOR_CODES: Record<string, string> = {\n green: '\\x1b[32m', yellow: '\\x1b[33m', cyan: '\\x1b[36m',\n red: '\\x1b[31m', gray: '\\x1b[90m', white: '\\x1b[37m',\n};\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\n\nfunction colorize(text: string, status: string): string {\n const colorName = statusColor(status);\n const code = COLOR_CODES[colorName];\n if (!code) return `${text}\\x1b[0m`;\n return `${code}${text}\\x1b[0m`;\n}\n\nfunction inferOrchestratorPhase(session: Session): string {\n const cycles = session.orchestratorCycles;\n if (cycles.length === 0) return 'planning';\n const lastCycle = cycles[cycles.length - 1];\n\n if (!lastCycle.completedAt) {\n // Orchestrator pane is alive\n const elapsed = Date.now() - new Date(lastCycle.timestamp).getTime();\n if (elapsed < 5000 || lastCycle.agentsSpawned.length === 0) return 'planning';\n return 'spawning';\n } else {\n // Orchestrator yielded\n const runningAgents = session.agents.filter(\n a => lastCycle.agentsSpawned.includes(a.id) && a.status === 'running'\n );\n if (runningAgents.length > 0) {\n return `waiting on ${runningAgents.map(a => a.id).join(', ')}`;\n }\n return 'starting';\n }\n}\n\nfunction formatAgent(agent: Agent, verbose: boolean): string {\n const status = colorize(agent.status, agent.status);\n const name = `${BOLD}${agent.name}${RESET}`;\n const type = `${DIM}(${agent.agentType})${RESET}`;\n const duration = formatDuration(agent.activeMs);\n let line = ` ${agent.id} ${name} ${type} — ${status} ${DIM}(${duration})${RESET}`;\n if (verbose && agent.instruction) {\n const truncated = agent.instruction.length > 200 ? agent.instruction.slice(0, 200) + '...' : agent.instruction;\n line += `\\n ${DIM}Instruction: ${truncated}${RESET}`;\n }\n if (agent.reports.length > 0) {\n for (const r of agent.reports) {\n const label = r.type === 'final' ? 'Final' : 'Update';\n line += `\\n ${label}: ${r.summary}`;\n }\n }\n if (agent.killedReason) {\n line += `\\n Reason: ${agent.killedReason}`;\n }\n return line;\n}\n\nfunction formatCycle(cycle: OrchestratorCycle, phase?: string): string {\n let duration: string;\n if (cycle.completedAt) {\n duration = ` ${DIM}(${formatDuration(cycle.activeMs)})${RESET}`;\n } else {\n const elapsed = formatDuration(cycle.activeMs);\n duration = ` ${DIM}(running, ${elapsed})${RESET}`;\n }\n const agents = cycle.agentsSpawned.length > 0\n ? ` — agents: ${cycle.agentsSpawned.join(', ')}`\n : '';\n const phaseStr = phase ? ` — orchestrator: ${phase}` : '';\n return ` Cycle ${cycle.cycle}${duration}${agents}${phaseStr}`;\n}\n\nfunction computeLastActivity(session: Session): Date | null {\n const timestamps: number[] = [];\n\n for (const cycle of session.orchestratorCycles) {\n timestamps.push(new Date(cycle.timestamp).getTime());\n if (cycle.completedAt) timestamps.push(new Date(cycle.completedAt).getTime());\n }\n\n for (const agent of session.agents) {\n timestamps.push(new Date(agent.spawnedAt).getTime());\n if (agent.completedAt) timestamps.push(new Date(agent.completedAt).getTime());\n for (const r of agent.reports) {\n timestamps.push(new Date(r.timestamp).getTime());\n }\n }\n\n if (timestamps.length === 0) return null;\n return new Date(Math.max(...timestamps));\n}\n\nfunction readRoadmap(cwd: string, sessionId: string): string | null {\n try {\n return readFileSync(roadmapPath(cwd, sessionId), 'utf8');\n } catch {\n return null;\n }\n}\n\nfunction readCycleLog(cwd: string, sessionId: string, cycle: number): string | null {\n try {\n const path = cycleLogPath(cwd, sessionId, cycle);\n if (!existsSync(path)) return null;\n return readFileSync(path, 'utf8');\n } catch {\n return null;\n }\n}\n\nfunction capturePaneOutput(paneId: string, lines: number = 50): string | null {\n try {\n return execSync(\n `tmux capture-pane -t \"${paneId}\" -p -S -${lines}`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] },\n ).trimEnd();\n } catch {\n return null;\n }\n}\n\nfunction printSession(session: Session, verbose: boolean): void {\n const status = colorize(session.status, session.status);\n const sessionDuration = formatDuration(session.createdAt, session.completedAt);\n console.log(`\\n${BOLD}Session: ${session.id}${RESET}`);\n console.log(` Status: ${status}`);\n console.log(` Task: ${session.task}`);\n if (session.context) {\n const truncated = !verbose && session.context.length > 120 ? session.context.slice(0, 120) + '...' : session.context;\n console.log(` Context: ${truncated}`);\n }\n console.log(` CWD: ${session.cwd}`);\n console.log(` Created: ${session.createdAt}`);\n const activeTime = formatDuration(computeActiveTimeMs(session));\n console.log(` Duration: ${sessionDuration}${session.completedAt ? '' : ' (ongoing)'} (${activeTime} active)`);\n\n const lastActivity = computeLastActivity(session);\n if (lastActivity) {\n console.log(` Last activity: ${formatDuration(Date.now() - lastActivity.getTime())} ago`);\n }\n\n console.log(` Orchestrator cycles: ${session.orchestratorCycles.length}`);\n\n // Active agents block\n const runningAgents = session.agents.filter(a => a.status === 'running');\n if (runningAgents.length > 0) {\n console.log(`\\n${BOLD}Active agents (${runningAgents.length}):${RESET}`);\n for (const agent of runningAgents) {\n const name = `${BOLD}${agent.name}${RESET}`;\n const type = `${DIM}(${agent.agentType})${RESET}`;\n const duration = formatDuration(agent.activeMs);\n console.log(` ${agent.id} ${name} ${type} running ${duration}`);\n if (verbose && agent.instruction) {\n const truncated = agent.instruction.length > 200 ? agent.instruction.slice(0, 200) + '...' : agent.instruction;\n console.log(` ${DIM}Instruction: ${truncated}${RESET}`);\n }\n }\n }\n\n // Roadmap\n const roadmap = readRoadmap(session.cwd, session.id);\n if (roadmap) {\n console.log(`\\n${BOLD}Roadmap:${RESET}`);\n console.log(roadmap);\n }\n\n if (session.orchestratorCycles.length > 0) {\n console.log(`\\n ${BOLD}Cycles:${RESET}`);\n const cycles = session.orchestratorCycles;\n for (let i = 0; i < cycles.length; i++) {\n const isLast = i === cycles.length - 1;\n const phase = isLast && session.status === 'active' ? inferOrchestratorPhase(session) : undefined;\n console.log(formatCycle(cycles[i], phase));\n\n // Verbose: show cycle log\n if (verbose) {\n const log = readCycleLog(session.cwd, session.id, cycles[i].cycle);\n if (log) {\n const lines = log.split('\\n');\n const preview = lines.slice(0, 20).join('\\n');\n console.log(` ${DIM}--- cycle log ---${RESET}`);\n for (const line of preview.split('\\n')) {\n console.log(` ${DIM}${line}${RESET}`);\n }\n if (lines.length > 20) {\n console.log(` ${DIM}... (${lines.length - 20} more lines)${RESET}`);\n }\n }\n }\n }\n }\n\n if (session.agents.length > 0) {\n console.log(`\\n ${BOLD}Agents:${RESET}`);\n for (const agent of session.agents) {\n console.log(formatAgent(agent, verbose));\n }\n }\n\n // Verbose: capture live pane output\n if (verbose) {\n // Orchestrator pane (from last running cycle)\n const lastCycle = session.orchestratorCycles[session.orchestratorCycles.length - 1];\n if (lastCycle && !lastCycle.completedAt && lastCycle.paneId) {\n const output = capturePaneOutput(lastCycle.paneId);\n if (output) {\n console.log(`\\n<orchestrator-pane-output lines=\"50\">`);\n console.log(output);\n console.log(`</orchestrator-pane-output>`);\n }\n }\n\n // Running agent panes\n for (const agent of runningAgents) {\n if (agent.paneId) {\n const output = capturePaneOutput(agent.paneId, 30);\n if (output) {\n console.log(`\\n<agent-pane-output agent=\"${agent.id}\" name=\"${agent.name}\" lines=\"30\">`);\n console.log(output);\n console.log(`</agent-pane-output>`);\n }\n }\n }\n }\n\n // Completion report\n if (verbose && session.completionReport) {\n console.log(`\\n${BOLD}Completion Report:${RESET}`);\n console.log(session.completionReport);\n }\n}\n\nexport function registerStatus(program: Command): void {\n program\n .command('status')\n .description('Show session status')\n .argument('[session-id]', 'Session ID (defaults to SISYPHUS_SESSION_ID env)')\n .option('-v, --verbose', 'Show detailed output (roadmap, pane output, agent instructions)')\n .action(async (sessionIdArg?: string, opts?: { verbose?: boolean }) => {\n const sessionId = sessionIdArg ?? process.env.SISYPHUS_SESSION_ID;\n const verbose = opts?.verbose ?? false;\n\n const request: Request = { type: 'status', sessionId };\n const response = await sendRequest(request);\n if (response.ok) {\n const session = response.data?.session as Session | undefined;\n if (session) {\n printSession(session, verbose);\n } else {\n console.log('No session found');\n }\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { basename } from 'node:path';\n\ninterface SessionSummary {\n id: string;\n name?: string;\n task: string;\n status: string;\n agentCount: number;\n createdAt: string;\n cwd?: string;\n}\n\nconst STATUS_COLORS: Record<string, string> = {\n active: '\\x1b[32m',\n paused: '\\x1b[33m',\n completed: '\\x1b[36m',\n};\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\n\nfunction truncateTask(task: string, max: number): string {\n if (task.length <= max) return task;\n return task.slice(0, max - 1) + '…';\n}\n\nexport function registerList(program: Command): void {\n program\n .command('list')\n .description('List sessions (defaults to current project)')\n .option('-a, --all', 'Show sessions from all projects')\n .option('--cwd <path>', 'Project directory to list sessions for (overrides SISYPHUS_CWD)')\n .action(async (opts: { all?: boolean; cwd?: string }) => {\n const cwd = opts.cwd ?? process.env['SISYPHUS_CWD'] ?? process.cwd();\n const request: Request = { type: 'list', cwd, all: opts.all };\n const response = await sendRequest(request);\n if (response.ok) {\n const sessions = (response.data?.sessions ?? []) as SessionSummary[];\n const totalCount = response.data?.totalCount as number | undefined;\n const filtered = response.data?.filtered as boolean | undefined;\n\n if (sessions.length === 0) {\n if (filtered && totalCount && totalCount > 0) {\n console.log(`No sessions in this project. ${totalCount} session(s) in other projects.`);\n console.log(`${DIM}Run ${RESET}sisyphus list --all${DIM} to show all.${RESET}`);\n } else {\n console.log('No sessions');\n }\n return;\n }\n\n for (const s of sessions) {\n const color = STATUS_COLORS[s.status] ?? '';\n const status = `${color}${s.status}${RESET}`;\n const agents = `${DIM}${s.agentCount} agent(s)${RESET}`;\n const task = truncateTask(s.task, 60);\n const label = s.name ? `${s.name} ${DIM}(${s.id.slice(0, 8)})${RESET}` : s.id;\n const cwdLabel = opts.all && s.cwd ? ` ${DIM}${basename(s.cwd)}${RESET}` : '';\n console.log(` ${BOLD}${label}${RESET} ${status} ${agents} ${task}${cwdLabel}`);\n }\n\n if (filtered && totalCount && totalCount > sessions.length) {\n const otherCount = totalCount - sessions.length;\n console.log(`\\n${DIM}${otherCount} more session(s) in other projects. Run ${RESET}sisyphus list --all${DIM} to show all.${RESET}`);\n }\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport { readStdin } from '../stdin.js';\nimport { assertTmux } from '../tmux.js';\n\nexport function registerReport(program: Command): void {\n program\n .command('report')\n .description('Send a progress report without exiting (agent only)')\n .option('--message <message>', 'Progress report content')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (opts: { message?: string; session?: string }) => {\n assertTmux();\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n const agentId = process.env.SISYPHUS_AGENT_ID;\n if (!sessionId || !agentId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID (and SISYPHUS_AGENT_ID) environment variables');\n process.exit(1);\n }\n\n const content = opts.message ?? await readStdin();\n if (!content) {\n console.error('Error: provide --message or pipe content via stdin');\n process.exit(1);\n }\n\n const request: Request = { type: 'report', sessionId, agentId, content };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Progress report recorded');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerResume(program: Command): void {\n program\n .command('resume')\n .description('Respawn orchestrator with new instructions (for paused/completed sessions)')\n .addHelpText('after', '\\n Use `resume` to restart a paused or completed session with new instructions.\\n Use `continue` to keep working on a completed session without new instructions.\\n')\n .argument('<session-id>', 'Session ID to resume')\n .argument('[message]', 'Additional instructions for the orchestrator')\n .action(async (sessionId: string, message?: string) => {\n const cwd = process.env['SISYPHUS_CWD'] ?? process.cwd();\n const request: Request = { type: 'resume', sessionId, cwd, message };\n const response = await sendRequest(request);\n if (response.ok) {\n const tmuxSessionName = response.data?.tmuxSessionName as string | undefined;\n console.log(`Session ${sessionId} resumed`);\n if (tmuxSessionName) {\n console.log(`Tmux session: ${tmuxSessionName}`);\n console.log(` tmux attach -t ${tmuxSessionName}`);\n }\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerKill(program: Command): void {\n program\n .command('kill <sessionId>')\n .description('Kill a running session and all its agents')\n .action(async (sessionId: string) => {\n const request: Request = { type: 'kill', sessionId };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log(`Session ${sessionId} killed.`);\n if (response.data) {\n const { killedAgents } = response.data as { killedAgents: number };\n console.log(`Cleaned up: ${killedAgents} agent(s) killed, tmux window removed.`);\n }\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { createInterface } from 'node:readline';\nimport { uninstallDaemon } from '../install.js';\n\nasync function confirm(question: string): Promise<boolean> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim().toLowerCase() === 'y');\n });\n });\n}\n\nexport function registerUninstall(program: Command): void {\n program\n .command('uninstall')\n .description('Unload the sisyphus daemon from launchd and remove the plist')\n .option('--purge', 'Also remove all session data in ~/.sisyphus')\n .option('-y, --yes', 'Skip confirmation prompt for --purge')\n .action(async (opts: { purge?: boolean; yes?: boolean }) => {\n const purge = opts.purge ?? false;\n\n if (purge && !opts.yes) {\n const ok = await confirm('This will delete all session data in ~/.sisyphus. Continue? (y/N) ');\n if (!ok) {\n console.log('Aborted.');\n return;\n }\n }\n\n await uninstallDaemon(purge);\n });\n}\n","import type { Command } from 'commander';\nimport { rawSend } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerNotify(program: Command): void {\n const notify = program\n .command('notify')\n .description('Internal notifications (fire-and-forget)');\n\n notify\n .command('pane-exited')\n .description('Notify daemon that a tmux pane exited')\n .requiredOption('--pane-id <paneId>', 'Pane ID that exited')\n .action(async (opts: { paneId: string }) => {\n try {\n const request: Request = { type: 'pane-exited', paneId: opts.paneId };\n await rawSend(request);\n } catch {\n // Fire-and-forget: daemon may be stopped, socket gone, etc.\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\nimport type { MessageSource } from '../../shared/types.js';\n\nexport function registerMessage(program: Command): void {\n program\n .command('message <content>')\n .description('Queue a message for the orchestrator to see on next cycle')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (content: string, opts: { session?: string }) => {\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const source: MessageSource | undefined = process.env.SISYPHUS_AGENT_ID\n ? { type: 'agent' as const, agentId: process.env.SISYPHUS_AGENT_ID }\n : undefined;\n\n const request: Request = { type: 'message', sessionId, content, source };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Message queued');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerUpdateTask(program: Command): void {\n program\n .command('update-task <task>')\n .description('Update the session task/goal')\n .option('--session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID env var)')\n .action(async (task: string, opts: { session?: string }) => {\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: provide --session or set SISYPHUS_SESSION_ID environment variable');\n process.exit(1);\n }\n\n const request: Request = { type: 'update-task', sessionId, task };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log('Task updated');\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerRollback(program: Command): void {\n program\n .command('rollback <sessionId> <cycle>')\n .description('Roll back a session to a previous cycle boundary')\n .action(async (sessionId: string, cycleStr: string) => {\n const toCycle = parseInt(cycleStr, 10);\n if (isNaN(toCycle) || toCycle < 1) {\n console.error('Error: cycle must be a positive integer');\n process.exit(1);\n }\n\n const cwd = process.env['SISYPHUS_CWD'] ?? process.cwd();\n const request: Request = { type: 'rollback', sessionId, cwd, toCycle };\n const response = await sendRequest(request);\n if (response.ok) {\n const data = response.data as { restoredToCycle: number };\n console.log(`Session ${sessionId} rolled back to cycle ${data.restoredToCycle}.`);\n console.log(`Session is now paused. Use 'sisyphus resume ${sessionId}' to respawn the orchestrator.`);\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { sendRequest } from '../client.js';\nimport type { Request } from '../../shared/protocol.js';\n\nexport function registerRestartAgent(program: Command): void {\n program\n .command('restart-agent <agentId>')\n .description('Restart a failed/killed/lost agent in a new tmux pane')\n .option('-s, --session <sessionId>', 'Session ID (defaults to SISYPHUS_SESSION_ID)')\n .action(async (agentId: string, opts: { session?: string }) => {\n const sessionId = opts.session ?? process.env.SISYPHUS_SESSION_ID;\n if (!sessionId) {\n console.error('Error: No session ID. Use --session or set SISYPHUS_SESSION_ID.');\n process.exit(1);\n }\n\n const request: Request = { type: 'restart-agent', sessionId, agentId };\n const response = await sendRequest(request);\n if (response.ok) {\n console.log(`Agent ${agentId} restarted.`);\n } else {\n console.error(`Error: ${response.error}`);\n process.exit(1);\n }\n });\n}\n","import type { Command } from 'commander';\nimport { DEFAULT_KEY, setupTmuxKeybind } from '../tmux-setup.js';\n\nexport function registerSetupKeybind(program: Command): void {\n program\n .command('setup-keybind [key]')\n .description('Install the sisyphus-cycle tmux keybinding (default: M-s)')\n .action(async (key: string | undefined) => {\n const resolvedKey = key ?? DEFAULT_KEY;\n const result = setupTmuxKeybind(resolvedKey);\n\n switch (result.status) {\n case 'installed':\n console.log(result.message);\n break;\n case 'already-installed':\n console.log(result.message);\n break;\n case 'conflict':\n console.log(`Key ${resolvedKey} is already bound:`);\n console.log(` ${result.existingBinding}`);\n console.log('');\n console.log('Use a different key, e.g.:');\n console.log(' sisyphus setup-keybind M-S');\n console.log(' sisyphus setup-keybind M-w');\n console.log(' sisyphus setup-keybind M-j');\n break;\n }\n });\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, statSync } from 'node:fs';\nimport type { Command } from 'commander';\nimport { daemonLogPath, daemonPidPath, globalDir, socketPath } from '../../shared/paths.js';\nimport { isInstalled } from '../install.js';\nimport { detectTerminal, checkItermOptionKey, isNvimAvailable, isBeginCommandInstalled } from '../onboard.js';\nimport { cycleScriptPath, DEFAULT_KEY, getExistingBinding, isSisyphusBinding, sisyphusTmuxConfPath } from '../tmux-setup.js';\n\ninterface Check {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n detail: string;\n fix?: string;\n}\n\nfunction checkNodeVersion(): Check {\n const major = parseInt(process.versions.node.split('.')[0]!, 10);\n if (major < 22) {\n return { name: 'Node.js', status: 'fail', detail: `v${process.versions.node} (v22+ required)`, fix: 'Install Node.js 22+: https://nodejs.org' };\n }\n return { name: 'Node.js', status: 'ok', detail: `v${process.versions.node}` };\n}\n\nfunction checkClaudeCli(): Check {\n try {\n execSync('which claude', { stdio: 'pipe' });\n return { name: 'Claude CLI', status: 'ok', detail: 'Found on PATH' };\n } catch {\n return {\n name: 'Claude CLI',\n status: 'fail',\n detail: 'Not found on PATH',\n fix: 'Install Claude Code: https://docs.anthropic.com/en/docs/claude-code/overview',\n };\n }\n}\n\nfunction checkGit(): Check {\n try {\n const version = execSync('git --version', { encoding: 'utf-8', stdio: 'pipe' }).trim();\n return { name: 'git', status: 'ok', detail: version };\n } catch {\n return { name: 'git', status: 'fail', detail: 'Not found on PATH', fix: 'Install git: https://git-scm.com/downloads' };\n }\n}\n\nfunction checkTmuxVersion(): Check {\n try {\n const version = execSync('tmux -V', { encoding: 'utf-8', stdio: 'pipe' }).trim();\n // Parse \"tmux X.Y\" or \"tmux next-X.Y\"\n const match = version.match(/(\\d+\\.\\d+)/);\n if (!match) return { name: 'tmux version', status: 'warn', detail: `Could not parse version: ${version}` };\n const ver = parseFloat(match[1]);\n if (ver < 3.2) {\n const upgradeHint = process.platform === 'darwin' ? 'brew install tmux (or upgrade)' : 'apt install tmux (Debian/Ubuntu) or your package manager';\n return { name: 'tmux version', status: 'warn', detail: `${version} (3.2+ recommended for popup support)`, fix: upgradeHint };\n }\n return { name: 'tmux version', status: 'ok', detail: version };\n } catch {\n return { name: 'tmux version', status: 'warn', detail: 'Could not determine version' };\n }\n}\n\nfunction checkDaemonInstalled(): Check {\n if (process.platform === 'darwin') {\n if (isInstalled()) {\n return { name: 'Daemon plist', status: 'ok', detail: 'Installed in LaunchAgents' };\n }\n return {\n name: 'Daemon plist',\n status: 'fail',\n detail: 'Not installed',\n fix: 'Run any sisyphus command to auto-install, or: sisyphus start \"test\"',\n };\n }\n // Linux: check if PID file exists (daemon started manually)\n const pid = daemonPidPath();\n if (existsSync(pid)) {\n return { name: 'Daemon setup', status: 'ok', detail: `PID file found at ${pid}` };\n }\n return {\n name: 'Daemon setup',\n status: 'fail',\n detail: 'Daemon not running (no PID file)',\n fix: 'Start manually: sisyphusd & — or configure via systemd',\n };\n}\n\nfunction checkDaemonRunning(): Check {\n const pid = daemonPidPath();\n if (!existsSync(pid)) {\n const fix = process.platform === 'darwin'\n ? 'launchctl load -w ~/Library/LaunchAgents/com.sisyphus.daemon.plist'\n : 'sisyphusd & — or check if the process is running';\n return {\n name: 'Daemon process',\n status: 'fail',\n detail: 'No PID file found',\n fix,\n };\n }\n try {\n const sock = socketPath();\n execSync(`test -S \"${sock}\"`, { stdio: 'pipe' });\n return { name: 'Daemon process', status: 'ok', detail: `Socket at ${sock}` };\n } catch {\n return {\n name: 'Daemon process',\n status: 'warn',\n detail: 'PID file exists but socket not found',\n fix: `Check logs: tail -20 ${daemonLogPath()}`,\n };\n }\n}\n\nfunction checkTmux(): Check {\n try {\n execSync('which tmux', { stdio: 'pipe' });\n } catch {\n const installHint = process.platform === 'darwin' ? 'brew install tmux' : 'apt install tmux (Debian/Ubuntu) or your package manager';\n return { name: 'tmux', status: 'fail', detail: 'Not found on PATH', fix: installHint };\n }\n try {\n execSync('tmux list-sessions', { stdio: 'pipe' });\n return { name: 'tmux', status: 'ok', detail: 'Running' };\n } catch {\n return { name: 'tmux', status: 'warn', detail: 'Installed but no server running' };\n }\n}\n\nfunction checkCycleScript(): Check {\n const path = cycleScriptPath();\n if (!existsSync(path)) {\n return {\n name: 'Cycle script',\n status: 'fail',\n detail: `Not found at ${path}`,\n fix: 'sisyphus setup-keybind',\n };\n }\n try {\n const mode = statSync(path).mode;\n if ((mode & 0o111) === 0) {\n return {\n name: 'Cycle script',\n status: 'fail',\n detail: 'Not executable',\n fix: `chmod +x ${path}`,\n };\n }\n } catch { /* ignore stat errors */ }\n return { name: 'Cycle script', status: 'ok', detail: path };\n}\n\nfunction checkTmuxKeybind(): Check {\n const existing = getExistingBinding(DEFAULT_KEY);\n if (existing === null) {\n // Also check if the sisyphus tmux.conf exists (binding might be configured but tmux not running)\n if (existsSync(sisyphusTmuxConfPath())) {\n return {\n name: `Tmux keybind (${DEFAULT_KEY})`,\n status: 'warn',\n detail: 'Configured in sisyphus tmux.conf but not active (tmux may not be running)',\n };\n }\n return {\n name: `Tmux keybind (${DEFAULT_KEY})`,\n status: 'fail',\n detail: 'Not bound',\n fix: 'sisyphus setup-keybind',\n };\n }\n if (isSisyphusBinding(existing)) {\n return { name: `Tmux keybind (${DEFAULT_KEY})`, status: 'ok', detail: 'Bound to sisyphus-cycle' };\n }\n return {\n name: `Tmux keybind (${DEFAULT_KEY})`,\n status: 'warn',\n detail: `Bound to something else: ${existing}`,\n fix: 'sisyphus setup-keybind M-S (or another free key)',\n };\n}\n\nfunction checkGlobalDir(): Check {\n const dir = globalDir();\n if (existsSync(dir)) {\n return { name: 'Data directory', status: 'ok', detail: dir };\n }\n return { name: 'Data directory', status: 'warn', detail: `${dir} does not exist (created on first use)` };\n}\n\nfunction checkTerminal(): Check {\n if (process.platform !== 'darwin') {\n return { name: 'Terminal', status: 'ok', detail: 'Non-macOS (skipped)' };\n }\n const terminal = detectTerminal();\n if (terminal.isIterm) {\n return { name: 'Terminal', status: 'ok', detail: terminal.name };\n }\n return {\n name: 'Terminal',\n status: 'warn',\n detail: terminal.name ? terminal.name : 'unknown',\n fix: 'iTerm2 recommended for best experience: https://iterm2.com',\n };\n}\n\nfunction checkItermRightOptionKey(): Check | null {\n if (process.platform !== 'darwin') return null;\n const terminal = detectTerminal();\n if (!terminal.isIterm) return null;\n const result = checkItermOptionKey();\n if (!result.checked) return null;\n if (result.allCorrect) {\n return { name: 'Right Option Key', status: 'ok', detail: 'Esc+' };\n }\n const profiles = result.incorrectProfiles.map((p) => `\"${p}\"`).join(', ');\n return {\n name: 'Right Option Key',\n status: 'warn',\n detail: `Not Esc+ for ${profiles}`,\n fix: 'iTerm2 \\u2192 Settings \\u2192 Profiles \\u2192 Keys \\u2192 Right Option Key \\u2192 Esc+',\n };\n}\n\nfunction checkBeginCommand(): Check {\n if (isBeginCommandInstalled()) {\n return { name: '/begin command', status: 'ok', detail: 'Installed' };\n }\n return {\n name: '/begin command',\n status: 'warn',\n detail: 'Not installed',\n fix: 'sisyphus setup',\n };\n}\n\nfunction checkNvim(): Check {\n if (!isNvimAvailable()) {\n const fix = process.platform === 'darwin' ? 'brew install neovim' : 'Install neovim from https://neovim.io';\n return { name: 'nvim', status: 'warn', detail: 'Not installed', fix };\n }\n try {\n const version = execSync('nvim --version', { encoding: 'utf-8', stdio: 'pipe' }).split('\\n')[0]?.replace('NVIM ', '');\n return { name: 'nvim', status: 'ok', detail: version ?? 'installed' };\n } catch {\n return { name: 'nvim', status: 'ok', detail: 'installed' };\n }\n}\n\nconst SYMBOLS = { ok: '\\u2713', warn: '!', fail: '\\u2717' } as const;\n\nexport function registerDoctor(program: Command): void {\n program\n .command('doctor')\n .description('Check sisyphus installation health')\n .action(async () => {\n const itermCheck = checkItermRightOptionKey();\n const checks: Check[] = [\n checkNodeVersion(),\n checkClaudeCli(),\n checkGit(),\n checkTmux(),\n checkTmuxVersion(),\n checkTerminal(),\n ...(itermCheck ? [itermCheck] : []),\n checkGlobalDir(),\n checkDaemonInstalled(),\n checkDaemonRunning(),\n checkCycleScript(),\n checkTmuxKeybind(),\n checkBeginCommand(),\n checkNvim(),\n ];\n\n let hasIssues = false;\n for (const c of checks) {\n const sym = SYMBOLS[c.status];\n console.log(` ${sym} ${c.name}: ${c.detail}`);\n if (c.status !== 'ok') hasIssues = true;\n }\n\n // Print fixes\n const fixable = checks.filter((c) => c.fix && c.status !== 'ok');\n if (fixable.length > 0) {\n console.log('\\nFixes:');\n for (const c of fixable) {\n console.log(` ${c.name}: ${c.fix}`);\n }\n }\n\n if (!hasIssues) {\n console.log('\\nAll checks passed.');\n }\n });\n}\n","import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport interface TerminalInfo {\n name: string;\n isIterm: boolean;\n}\n\nexport interface ItermOptionKeyResult {\n checked: boolean;\n allCorrect: boolean;\n incorrectProfiles: string[];\n}\n\nexport interface NvimInfo {\n installed: boolean;\n autoInstalled: boolean;\n version: string;\n lazyVimInstalled: boolean;\n}\n\nexport interface CommandInfo {\n installed: boolean;\n autoInstalled: boolean;\n path: string;\n}\n\nexport interface OnboardResult {\n tmuxInstalled: boolean;\n tmuxAutoInstalled: boolean;\n terminal: TerminalInfo;\n itermOptionKey: ItermOptionKeyResult;\n tmuxDefaultsWritten: boolean;\n nvim: NvimInfo;\n command: CommandInfo;\n}\n\nexport function detectTerminal(): TerminalInfo {\n const termProgram = process.env['TERM_PROGRAM'] || '';\n const isIterm = termProgram === 'iTerm.app' || !!process.env['ITERM_SESSION_ID'];\n return { name: termProgram || 'unknown', isIterm };\n}\n\nfunction isTmuxAvailable(): boolean {\n try {\n execSync('which tmux', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isBrewAvailable(): boolean {\n try {\n execSync('which brew', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction tryAutoInstallTmux(): boolean {\n if (!isBrewAvailable()) return false;\n try {\n console.log(' Installing tmux via Homebrew...');\n execSync('brew install tmux', { stdio: 'inherit' });\n return isTmuxAvailable();\n } catch {\n return false;\n }\n}\n\nexport function checkItermOptionKey(): ItermOptionKeyResult {\n if (process.platform !== 'darwin') {\n return { checked: false, allCorrect: true, incorrectProfiles: [] };\n }\n\n const plistPath = join(homedir(), 'Library', 'Preferences', 'com.googlecode.iterm2.plist');\n if (!existsSync(plistPath)) {\n return { checked: false, allCorrect: false, incorrectProfiles: [] };\n }\n\n try {\n const json = execSync(\n `plutil -extract \"New Bookmarks\" json -o - \"${plistPath}\"`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] },\n );\n const profiles = JSON.parse(json) as Array<Record<string, unknown>>;\n const currentProfile = process.env['ITERM_PROFILE'];\n const incorrect: string[] = [];\n for (const profile of profiles) {\n const name = (profile['Name'] as string) || 'Unnamed';\n // Only check the current profile (or all if we can't detect which)\n if (currentProfile && name !== currentProfile) continue;\n // 0 = Normal, 1 = Meta, 2 = Esc+\n if (profile['Right Option Key Sends'] !== 2) {\n incorrect.push(name);\n }\n }\n return { checked: true, allCorrect: incorrect.length === 0, incorrectProfiles: incorrect };\n } catch {\n return { checked: false, allCorrect: false, incorrectProfiles: [] };\n }\n}\n\nfunction hasExistingTmuxConf(): boolean {\n return (\n existsSync(join(homedir(), '.tmux.conf')) ||\n existsSync(join(homedir(), '.config', 'tmux', 'tmux.conf'))\n );\n}\n\nconst TMUX_DEFAULTS = `# Sensible tmux defaults (installed by sisyphus)\n# Customize freely — sisyphus won't overwrite this file.\n\n# Enable mouse (click panes, scroll, resize)\nset -g mouse on\n\n# Scrollback history\nset -g history-limit 50000\n\n# 256 color + true color support\nset -g default-terminal \"tmux-256color\"\nset -as terminal-overrides \",*:Tc\"\n\n# Low escape delay (keeps Option/Meta keybindings responsive)\nset -sg escape-time 10\n\n# Window numbering from 1\nset -g base-index 1\nsetw -g pane-base-index 1\n\n# Renumber windows when one closes\nset -g renumber-windows on\n\n# Clipboard integration\nset -g set-clipboard on\n\n# Focus events (for editors)\nset -g focus-events on\n\n# --- Pane navigation (no prefix needed) ---\nbind -n C-h select-pane -L\nbind -n C-j select-pane -D\nbind -n C-k select-pane -U\nbind -n C-l select-pane -R\n\n# --- Window navigation (no prefix needed) ---\nbind -n C-n next-window\nbind -n C-p previous-window\n\n# --- New window / splits preserve cwd ---\nbind c new-window -c \"#{pane_current_path}\"\nbind '\"' split-window -v -c \"#{pane_current_path}\"\nbind % split-window -h -c \"#{pane_current_path}\"\n\n# --- Kill pane + rebalance ---\nbind x kill-pane \\\\; select-layout even-horizontal\n\n# --- Auto-rebalance on pane close ---\nset-hook -g after-kill-pane \"select-layout even-horizontal\"\nset-hook -g pane-exited \"select-layout even-horizontal\"\n\n# --- Manual re-tile ---\nbind = select-layout even-horizontal\n\n# --- Scroll (no prefix needed) ---\nbind -n C-u copy-mode \\\\; send-keys -X halfpage-up\nbind -n C-d copy-mode \\\\; send-keys -X halfpage-down\n\n# --- Vi copy mode ---\nsetw -g mode-keys vi\nbind -T copy-mode-vi v send-keys -X begin-selection\nbind -T copy-mode-vi y send-keys -X copy-selection-and-cancel\n`;\n\nfunction writeTmuxDefaults(): void {\n const confPath = join(homedir(), '.tmux.conf');\n writeFileSync(confPath, TMUX_DEFAULTS, 'utf8');\n}\n\nexport function isNvimAvailable(): boolean {\n try {\n execSync('which nvim', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction getNvimVersion(): string {\n try {\n return execSync('nvim --version', { encoding: 'utf-8', stdio: 'pipe' }).split('\\n')[0]?.replace('NVIM ', '') || 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\nfunction hasLazyVimConfig(): boolean {\n return existsSync(join(homedir(), '.config', 'nvim', 'lazy-lock.json'));\n}\n\nexport function tryAutoInstallNvim(): NvimInfo {\n if (isNvimAvailable()) {\n return { installed: true, autoInstalled: false, version: getNvimVersion(), lazyVimInstalled: hasLazyVimConfig() };\n }\n if (!isBrewAvailable()) {\n return { installed: false, autoInstalled: false, version: '', lazyVimInstalled: false };\n }\n try {\n console.log(' Installing neovim via Homebrew...');\n execSync('brew install neovim', { stdio: 'inherit' });\n } catch {\n return { installed: false, autoInstalled: false, version: '', lazyVimInstalled: false };\n }\n if (!isNvimAvailable()) {\n return { installed: false, autoInstalled: false, version: '', lazyVimInstalled: false };\n }\n // Clone LazyVim starter config if no nvim config exists\n const nvimConfigDir = join(homedir(), '.config', 'nvim');\n let lazyVimInstalled = false;\n if (!existsSync(nvimConfigDir)) {\n try {\n console.log(' Cloning LazyVim starter config...');\n execSync(`git clone https://github.com/LazyVim/starter ${nvimConfigDir}`, { stdio: 'inherit' });\n // Remove .git so user owns the config\n const gitDir = join(nvimConfigDir, '.git');\n if (existsSync(gitDir)) {\n execSync(`rm -rf \"${gitDir}\"`, { stdio: 'pipe' });\n }\n lazyVimInstalled = true;\n } catch {\n // Non-fatal — nvim is installed, just no starter config\n }\n }\n return { installed: true, autoInstalled: true, version: getNvimVersion(), lazyVimInstalled };\n}\n\nfunction beginCommandPath(): string {\n return join(homedir(), '.claude', 'commands', 'sisyphus', 'begin.md');\n}\n\nfunction bundledBeginCommandPath(): string {\n const distDir = dirname(fileURLToPath(import.meta.url));\n return join(distDir, 'templates', 'begin.md');\n}\n\nexport function isBeginCommandInstalled(): boolean {\n return existsSync(beginCommandPath());\n}\n\nexport function installBeginCommand(): CommandInfo {\n const dest = beginCommandPath();\n if (existsSync(dest)) {\n return { installed: true, autoInstalled: false, path: dest };\n }\n const src = bundledBeginCommandPath();\n if (!existsSync(src)) {\n return { installed: false, autoInstalled: false, path: dest };\n }\n try {\n mkdirSync(dirname(dest), { recursive: true });\n writeFileSync(dest, readFileSync(src, 'utf-8'), 'utf8');\n return { installed: true, autoInstalled: true, path: dest };\n } catch {\n return { installed: false, autoInstalled: false, path: dest };\n }\n}\n\nexport function runOnboarding(): OnboardResult {\n const terminal = detectTerminal();\n const tmuxAlreadyInstalled = isTmuxAvailable();\n\n let tmuxInstalled = tmuxAlreadyInstalled;\n let tmuxAutoInstalled = false;\n let tmuxDefaultsWritten = false;\n\n // Auto-install tmux if missing\n if (!tmuxAlreadyInstalled && process.platform === 'darwin') {\n tmuxAutoInstalled = tryAutoInstallTmux();\n tmuxInstalled = tmuxAutoInstalled;\n\n // Write sensible defaults only for fresh tmux installs (don't touch existing configs)\n if (tmuxAutoInstalled && !hasExistingTmuxConf()) {\n writeTmuxDefaults();\n tmuxDefaultsWritten = true;\n }\n }\n\n // Check iTerm2 right option key\n let itermOptionKey: ItermOptionKeyResult = { checked: false, allCorrect: true, incorrectProfiles: [] };\n if (terminal.isIterm) {\n itermOptionKey = checkItermOptionKey();\n }\n\n // Nvim\n const nvim = tryAutoInstallNvim();\n\n // /begin command\n const command = installBeginCommand();\n\n return { tmuxInstalled, tmuxAutoInstalled, terminal, itermOptionKey, tmuxDefaultsWritten, nvim, command };\n}\n\nexport function formatOnboardingMessages(result: OnboardResult): string[] {\n const lines: string[] = [];\n\n // Terminal recommendation (macOS only)\n if (process.platform === 'darwin' && !result.terminal.isIterm) {\n lines.push(\n ` Terminal: ${result.terminal.name || 'unknown'}`,\n ' Tip: iTerm2 is recommended for the best experience with sisyphus.',\n ' Download: https://iterm2.com',\n '',\n );\n }\n\n // tmux status\n if (result.tmuxAutoInstalled) {\n lines.push(' \\u2713 tmux installed via Homebrew.');\n if (result.tmuxDefaultsWritten) {\n lines.push(' \\u2713 Default tmux config written to ~/.tmux.conf');\n }\n lines.push('');\n } else if (!result.tmuxInstalled) {\n const installHint = process.platform === 'darwin'\n ? ' Install Homebrew (https://brew.sh) then run: brew install tmux'\n : ' Install: apt install tmux (Debian/Ubuntu) or your package manager';\n lines.push(\n ' \\u2717 tmux is required but could not be installed automatically.',\n installHint,\n '',\n );\n }\n\n // iTerm2 right option key\n if (result.itermOptionKey.checked && !result.itermOptionKey.allCorrect) {\n const profiles = result.itermOptionKey.incorrectProfiles;\n lines.push(\n ' \\u26a0 Right Option Key is not sending Esc+ in iTerm2:',\n ...profiles.map((p) => ` \\u2022 Profile \"${p}\"`),\n '',\n ' Sisyphus uses Option keybindings (e.g., Option-s to cycle sessions).',\n ' Fix: iTerm2 \\u2192 Settings \\u2192 Profiles \\u2192 Keys \\u2192 Right Option Key \\u2192 Esc+',\n '',\n );\n }\n\n return lines;\n}\n","import type { Command } from 'commander';\nimport { buildCompanionContext } from '../../tui/lib/context.js';\n\nexport function registerCompanionContext(program: Command): void {\n program\n .command('companion-context')\n .description('Output session context JSON for companion hook')\n .option('--cwd <path>', 'Project directory', process.cwd())\n .action((opts: { cwd: string }) => {\n const context = buildCompanionContext(opts.cwd);\n process.stdout.write(JSON.stringify({ additionalContext: context }));\n });\n}\n","import { execSync } from 'node:child_process';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Command } from 'commander';\nimport { isTmuxInstalled } from '../tmux.js';\nimport { isNvimAvailable, detectTerminal, checkItermOptionKey } from '../onboard.js';\n\nfunction templatePath(name: string): string {\n return join(dirname(fileURLToPath(import.meta.url)), 'templates', name);\n}\n\nfunction isClaudeCode(): boolean {\n return !!process.env['CLAUDECODE'];\n}\n\nfunction printNonClaudeMessage(): void {\n console.log(`\n ╔══════════════════════════════════════════════════╗\n ║ sisyphus getting-started — Interactive Tutorial ║\n ╚══════════════════════════════════════════════════╝\n\n This command provides an interactive tutorial best experienced\n inside Claude Code. Claude will walk you through setup step by step.\n\n To start:\n 1. Open Claude Code: claude\n 2. Run: sisyphus getting-started\n\n If you just want the quick reference, run:\n sisyphus --help\n sisyphus doctor\n`);\n}\n\nfunction printStep0(): void {\n const tmuxInstalled = isTmuxInstalled();\n const inTmux = !!process.env['TMUX'];\n let tmuxSession: string | null = null;\n if (process.env['TMUX']) {\n const segments = process.env['TMUX'].split(',');\n const pathPart = segments[0];\n if (pathPart) {\n const parts = pathPart.split('/');\n tmuxSession = parts[parts.length - 1] || null;\n }\n }\n\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 0: Entry & Tmux Gate\n\n## Environment Data\n- tmuxInstalled: ${tmuxInstalled}\n- inTmux: ${inTmux}\n- tmuxSession: ${tmuxSession ?? 'none'}\n\n## Tutorial Overview\n\nThis tutorial has 6 steps. Share this overview so the user knows what's coming and can skip ahead:\n\n| Step | Topic | Command |\n|------|-------|---------|\n| 0 | Entry & tmux gate (you are here) | \\`sisyphus getting-started\\` |\n| 1 | Tmux basics — sessions, panes, navigation | \\`--tutorial 1\\` |\n| 2 | Nvim basics — open, save, quit (optional) | \\`--tutorial 2\\` |\n| 3 | Sisyphus concepts — session model & keybinds | \\`--tutorial 3\\` |\n| 4 | Live demo — launch and observe a real session | \\`--tutorial 4\\` |\n| 5 | What's next — real usage guidance & suggestions | \\`--tutorial 5\\` |\n\nTell the user they can skip to any step with \\`sisyphus getting-started --tutorial <N>\\`.\n\n## Instructions for Claude\n\nYou are guiding a user through the Sisyphus interactive tutorial.\n\n### First: Ask if they want the tutorial\n\nAsk the user if they'd like the interactive walkthrough. If they decline, give this quick summary and stop:\n\n> Sisyphus is a multi-agent orchestrator for Claude Code. Start a session with \\`sisyphus start \"task\"\\`,\n> monitor with \\`sisyphus dashboard\\`, and check health with \\`sisyphus doctor\\`.\n\n### If they want the tutorial:\n\n**Case 1: tmux is NOT installed (tmuxInstalled: false)**\n- Explain what tmux is in 2-3 sentences: \"tmux is a terminal multiplexer — it lets you split your terminal into multiple panes and keep sessions running in the background. Sisyphus uses it to give each agent its own workspace.\"\n- Show this ASCII diagram:\n\n\\`\\`\\`\n Regular terminal: With tmux:\n ┌──────────────┐ ┌──────┬──────┐\n │ │ │ Agent│ Agent│\n │ one view │ │ 001 │ 002 │\n │ │ ├──────┼──────┤\n │ │ │ Agent│ Orch │\n └──────────────┘ │ 003 │ │\n └──────┴──────┘\n\\`\\`\\`\n\n- Tell them to install tmux:\n - macOS: \\`brew install tmux\\`\n - Linux: \\`apt install tmux\\` or their package manager\n- After install, re-run: \\`sisyphus getting-started --tutorial 0\\` to verify\n\n**Case 2: tmux installed but NOT in a tmux session (inTmux: false)**\n- Tell the user they need to be inside a tmux session for the tutorial\n- Have them run: \\`tmux new-session\\`\n- Then resume the conversation with Claude in the new tmux session: \\`claude\\`\n- Then re-run: \\`sisyphus getting-started --tutorial 0\\` to verify\n\n**Case 3: In tmux (inTmux: true)**\n- Tell the user they're all set — tmux is running\n- Proceed by running: \\`sisyphus getting-started --tutorial 1\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep1(): void {\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 1: Tmux Basics\n\n## Instructions for Claude\n\nTeach the user tmux fundamentals. Be conversational and encouraging.\n\n### 1. Explain the concepts with diagrams\n\n**Sessions, Windows, and Panes:**\n\n\\`\\`\\`\ntmux session \"work\"\n├── window 1: \"code\"\n│ ┌──────────┬──────────┐\n│ │ pane 1 │ pane 2 │\n│ │ (editor)│ (tests) │\n│ └──────────┴──────────┘\n└── window 2: \"servers\"\n ┌──────────────────────┐\n │ pane 1 │\n │ (dev server) │\n └──────────────────────┘\n\\`\\`\\`\n\n- **Session**: A collection of windows. Persists even if you close the terminal.\n- **Window**: Like a tab. Each window fills the screen.\n- **Pane**: A split within a window. Sisyphus puts each agent in its own pane.\n\n### 2. Hands-on: Create a test split\n\nRun this command for the user:\n\\`\\`\\`\ntmux split-window -h\n\\`\\`\\`\n\nTell them: \"I just split your terminal. You should see two panes side by side.\"\n\nExplain navigation:\n- \\`Ctrl+l\\`: move to the right pane\n- \\`Ctrl+h\\`: move to the left pane\n- \\`Ctrl+j\\`: move to the pane below\n- \\`Ctrl+k\\`: move to the pane above\n- No prefix key needed — just hold Ctrl and press the direction letter\n- For windows: \\`Ctrl+n\\` next window, \\`Ctrl+p\\` previous window\n\nAsk them to try navigating between panes.\n\n### 3. Clean up the test pane\n\nOnce they confirm they can navigate, close the extra pane:\n\\`\\`\\`\ntmux kill-pane -t {the other pane}\n\\`\\`\\`\n\nOr tell them they can type \\`exit\\` in the extra pane to close it.\n\n### 4. Teach essential commands\n\n- **Detach**: \\`Ctrl-b d\\` — leaves tmux running in background, returns to normal terminal\n- **Reattach**: \\`tmux attach\\` (or \\`tmux a\\`) — reconnects to the running session\n- **Scroll up/down**: \\`Ctrl+u\\` / \\`Ctrl+d\\` — scroll half-page up/down (no prefix needed). Press \\`q\\` to exit scroll mode.\n- **New window**: \\`Ctrl-b n\\` — opens a new window in the current directory\n- **Kill pane**: \\`Ctrl-b x\\` — closes the current pane and rebalances layout\n- **Re-tile**: \\`Ctrl-b =\\` — rebalance all panes to equal widths\n\n### 5. Verification\n\nAsk the user to confirm: \"Can you navigate between panes with Ctrl+h and Ctrl+l?\"\n\nOnce confirmed, proceed:\n\\`\\`\\`\nsisyphus getting-started --tutorial 2\n\\`\\`\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep2(): void {\n const nvimInstalled = isNvimAvailable();\n\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 2: Nvim Basics\n\n## Environment Data\n- nvimInstalled: ${nvimInstalled}\n\n## Instructions for Claude\n\nThis step is OPTIONAL. Nvim is useful for reviewing and editing files when you jump into agent panes, but not required.\n\nNote: The sisyphus dashboard has keys that auto-open files in nvim — users don't need to know how to open files from the command line. Focus on what they'll need once they're INSIDE nvim.\n\n### If nvim is NOT installed (nvimInstalled: false)\n\nAsk the user: \"Neovim is handy for reviewing and editing files in tmux panes. Want me to install it, or skip this step?\"\n\n- **Install**: Run \\`brew install neovim\\` (macOS) or suggest their package manager\n- **Skip**: That's fine — they can use \\`cat\\`, \\`less\\`, or any editor they prefer. Proceed to step 3.\n\n### If nvim IS installed (nvimInstalled: true)\n\nBriefly explain the key concept — nvim has two modes:\n\n- **Normal mode** (default): Keys are commands, not text. This is where you navigate.\n- **Insert mode**: Press \\`i\\` to enter. Now you type normally. \\`Esc\\` goes back to normal.\n\nThen tell the user: \"I'm going to open an interactive tutorial file in a pane to your right. It walks you through everything — navigation, editing, saving. Follow the instructions inside the file.\"\n\nOpen the bundled tutorial file in a split pane:\n\\`\\`\\`\ncp ${templatePath('nvim-tutorial.txt')} /tmp/sisyphus-nvim-tutorial.txt\ntmux split-window -h \"nvim /tmp/sisyphus-nvim-tutorial.txt\"\n\\`\\`\\`\n\nTell them to click on the right pane (or \\`Ctrl+l\\`) and follow the instructions in the file. When they \\`:wq\\` or \\`ZZ\\`, the pane closes and they're back in Claude.\n\nTell them: \"When you jump into an agent's pane and the dashboard opens a file, you'll land in normal mode. Now you know how to look around, make edits, and get out.\"\n\n### Verification\n\nAsk if they were able to edit and save the file (or if they skipped).\n\nProceed:\n\\`\\`\\`\nsisyphus getting-started --tutorial 3\n\\`\\`\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep3(): void {\n // Detect iTerm Right Option Key status for environment data\n let rightOptionKeyStatus = 'unknown';\n const terminal = detectTerminal();\n if (!terminal.isIterm) {\n rightOptionKeyStatus = 'not-iterm';\n } else {\n const result = checkItermOptionKey();\n if (!result.checked) {\n rightOptionKeyStatus = 'could-not-check';\n } else if (result.allCorrect) {\n rightOptionKeyStatus = 'ok';\n } else {\n rightOptionKeyStatus = `incorrect:${result.incorrectProfiles.join(',')}`;\n }\n }\n\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 3: Sisyphus Concepts & Keybinds\n\n## Environment Data\n- rightOptionKeyStatus: ${rightOptionKeyStatus}\n\n## Instructions for Claude\n\n### 1. CRITICAL FIRST: Right Option Key Setup\n\n**This must be done before anything else.** Sisyphus keybinds use the Option key as \"Meta\". By default, macOS terminals send special characters when you press Option (e.g., Option+s types \\`ß\\`). We need the RIGHT Option key to send escape sequences instead.\n\n**Check the environment data above:**\n\n- **rightOptionKeyStatus: ok** — They're all set, briefly confirm and move on.\n\n- **rightOptionKeyStatus: incorrect:ProfileName** — Walk them through the fix:\n\n > Your Right Option key isn't configured correctly yet. Here's how to fix it:\n >\n > 1. Open **iTerm2 Settings** (Cmd+,)\n > 2. Go to **Profiles** → select your profile (shown above)\n > 3. Click the **Keys** tab\n > 4. At the bottom, find **Right Option Key**\n > 5. Change it from **Normal** to **Esc+**\n >\n > \\`\\`\\`\n > ┌─ iTerm2 Settings ──────────────────────────┐\n > │ Profiles > Keys │\n > │ │\n > │ Right Option Key: │\n > │ ○ Normal (sends special chars like ß) │\n > │ ● Esc+ (sends escape sequences) ← ✓ │\n > └─────────────────────────────────────────────┘\n > \\`\\`\\`\n >\n > **Why right and not left?** You'll still want the left Option key for\n > typing special characters (accents, symbols). The right Option key\n > becomes your \"Meta\" key for tmux/sisyphus keybinds.\n\n After they change it, have them verify by re-running \\`sisyphus doctor\\` — look for \"Right Option Key: Esc+\".\n\n- **rightOptionKeyStatus: not-iterm** — They're not using iTerm2. Explain:\n > Sisyphus keybinds use Option as Meta. In iTerm2 this is configured via\n > \"Right Option Key → Esc+\". For your terminal, look for a similar setting\n > like \"Option sends Meta\" or \"Option sends Esc+\". Without this, pressing\n > Option+s will type a special character instead of triggering the keybind.\n\n- **rightOptionKeyStatus: could-not-check** or **unknown** — Ask them to manually check:\n > Press Option+s in your terminal. If you see \\`ß\\` (or another special character),\n > your Option key needs to be reconfigured. In iTerm2: Settings → Profiles → Keys →\n > Right Option Key → Esc+.\n\n### 2. Explain the session model\n\nThis is the KEY concept. Use the diagram and be clear:\n\n\\`\\`\\`\n YOUR tmux session (\"work\") Sisyphus tmux session (\"sisyphus-abc123\")\n ┌─────────────────────┐ ┌──────────┬──────────┬──────────┐\n │ │ │ Orch │ Agent │ Agent │\n │ Your normal work │ ←──→ │ (yellow)│ (blue) │ (green) │\n │ + dashboard │ │ │ │ │\n │ │ │ Plans & │ Writes │ Writes │\n │ │ │ assigns │ code │ tests │\n └─────────────────────┘ └──────────┴──────────┴──────────┘\n\\`\\`\\`\n\nKey points:\n- Sisyphus creates its OWN tmux session — it doesn't clutter yours\n- The **orchestrator** (yellow pane) plans work and spawns agents\n- **Agents** (colored panes) work in parallel on subtasks\n- Your session stays clean — you get a **dashboard** for monitoring\n- You can jump between your session and the sisyphus session to observe\n\n### 3. Teach keybinds\n\nTwo keybinds to remember (both use the RIGHT Option key):\n\n| Keybind | Action |\n|---------|--------|\n| Right Option + s | Cycle through sisyphus sessions |\n| Right Option + Shift + s | Jump back to dashboard |\n\n### 4. Verify keybinds are installed\n\nRun \\`sisyphus doctor\\` and check the output. Look for:\n- \"Cycle script\" — should be ✓\n- \"Tmux keybind\" — should be ✓\n- \"Right Option Key\" — should be \"Esc+\"\n\nIf cycle script or keybind is missing, run: \\`sisyphus setup-keybind\\`\n\n### 5. Test the keybind\n\nHave the user try pressing Right Option + s. Nothing should happen yet (no sisyphus session running) — and that's fine. The important thing is no special character appears.\n\nIf they see \\`ß\\` or similar, circle back to the Right Option Key setup above.\n\n### 6. Verification\n\nConfirm:\n- They understand the two-session model (their session vs sisyphus session)\n- \\`sisyphus doctor\\` shows keybinds installed AND Right Option Key: Esc+\n- Right Option + s doesn't produce a special character\n\nProceed:\n\\`\\`\\`\nsisyphus getting-started --tutorial 4\n\\`\\`\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep4(): void {\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 4: Demo Session\n\n## Instructions for Claude\n\nThis is the grand finale — a live demo session.\n\n### 1. Health check\n\nRun \\`sisyphus doctor\\` first. If any checks are failing, help the user fix them before proceeding.\nAll core checks (tmux, daemon, keybinds) should be ✓.\n\n### 2. BEFORE launching: Teach navigation\n\n**This is critical.** When \\`sisyphus start\\` runs, it auto-opens the dashboard in a new tmux window. The user will suddenly be looking at the dashboard and may feel \"stuck\". Teach them how to navigate BEFORE launching:\n\nExplain clearly:\n\n> Before we launch, you need to know how to move between tmux windows. Right now you're in a window with Claude. When sisyphus starts, it'll open a dashboard in a new window. Think of windows like tabs:\n>\n> \\`\\`\\`\n> Window 1 (you are here) Window 2 (dashboard)\n> ┌──────────────────┐ ┌──────────────────┐\n> │ Claude Code │ │ Sisyphus │\n> │ (this session) │ → │ Dashboard │\n> └──────────────────┘ └──────────────────┘\n> Ctrl+n → ← Ctrl+p\n> \\`\\`\\`\n>\n> - **\\`Ctrl+n\\`** — next window (go to dashboard)\n> - **\\`Ctrl+p\\`** — previous window (come back here)\n>\n> And remember from step 3:\n> - **Right Option + s** — jump to the sisyphus agent session (where you can watch agents work live)\n> - **Right Option + Shift + s** — jump back to dashboard\n\nHave the user confirm they understand these keybinds before proceeding.\n\n### 3. Set expectations, copy demo app, and launch\n\nFirst, copy the demo todo app to a temp directory and init a git repo (sisyphus needs git):\n\\`\\`\\`\nrm -rf /tmp/sisyphus-tutorial-demo\ncp -r ${templatePath('tutorial-demo')} /tmp/sisyphus-tutorial-demo\ngit -C /tmp/sisyphus-tutorial-demo init\ngit -C /tmp/sisyphus-tutorial-demo add -A\ngit -C /tmp/sisyphus-tutorial-demo commit -m \"Initial todo app\"\n\\`\\`\\`\n\nTell the user:\n\n> I've set up a small todo app in /tmp/sisyphus-tutorial-demo — a Node.js API\n> with a few files. I'm going to launch sisyphus on it. Here's what will happen:\n> 1. The dashboard opens automatically (you'll be switched to it)\n> 2. Press **Ctrl+p** to come back here to Claude — I'll guide you through what to watch\n> 3. The session takes a few minutes. You can watch agents work live!\n\nThen launch from the demo directory:\n\\`\\`\\`\ncd /tmp/sisyphus-tutorial-demo && sisyphus start \"Add three improvements to this todo app: (1) add a priority field (high/medium/low) to todos, (2) add a GET /todos/stats endpoint that returns counts of total/done/pending todos, (3) add tests for the new features. Explain your thinking at each step.\" -c \"TUTORIAL DEMO: A user is watching this session to learn how sisyphus works. Be EXTRA VERBOSE — explain your reasoning, narrate what you're doing, and make your planning visible. When spawning agents, give each agent context that this is a tutorial demo and they should explain their work clearly. Keep scope small: 2-3 agents, 1-2 cycles.\"\n\\`\\`\\`\n\nAfter launching, tell them:\n\n> The dashboard just opened. Press **Ctrl+p** to come back here — I'll provide live commentary as the session runs so you know what's happening.\n\nWait for them to confirm they're back, then start live commentary.\n\n### 4. Live commentary loop\n\n**This is the most important part of the demo.** Don't just launch and wait — actively narrate.\n\nOnce the user is back, start a polling loop. Every ~45 seconds, run \\`sisyphus status --verbose <session-id>\\` and provide SHORT, contextual commentary about what's happening. The \\`--verbose\\` flag shows agent instructions, full roadmap, cycle logs, and live pane output from the orchestrator and running agents — use this rich data to narrate what's actually happening, not just phase names.\n\n**How to narrate each phase:**\n\n- **Cycle 1, no agents yet**: \"The orchestrator is reading the codebase and planning. It's figuring out how to split the work. Check the dashboard (\\`Ctrl+n\\`) — you'll see the roadmap updating.\"\n\n- **Agents spawning**: \"Agents just spawned! You should see new panes appearing. Try \\`Right Option + s\\` to jump to the sisyphus session and watch them work. Each colored pane is an independent Claude instance.\"\n\n- **Agents working**: \"Agent-001 is working on [X], Agent-002 is on [Y]. They're working in parallel — this is the key advantage of sisyphus. Jump over and watch if you like (\\`Right Option + s\\`).\"\n\n- **Agents submitting**: \"Agent-001 just submitted its report! [N] more to go. When all agents finish, the orchestrator will respawn to review.\"\n\n- **Between cycles**: \"All agents done. The orchestrator is respawning with fresh context to review the reports and decide what's next. This is the cycle boundary — the orchestrator never runs out of context because it starts fresh each time.\"\n\n- **Completion**: \"The session is complete! Let me show you the results.\"\n\n**Important:**\n- Keep commentary to 1-3 sentences per check — don't wall-of-text\n- Remind them of navigation keys when relevant (\"jump over with Right Option + s to see this live\")\n- If agents are still working with no change, say so briefly (\"Still working... Agent-001 is the furthest along\")\n- Reference specific agent names and tasks from the status output\n- Stop polling when status shows \"completed\"\n\nBetween polls, encourage the user to explore:\n> \"While we wait, try jumping around: \\`Ctrl+n\\` for dashboard, \\`Right Option + s\\` for the agent session, \\`Right Option + Shift + s\\` to jump back. I'll keep narrating here.\"\n\n### 5. After completion\n\nOnce the session shows \"completed\":\n\n- Show them what the agents built: \\`cd /tmp/sisyphus-tutorial-demo && git log --oneline\\`\n- Run the tests to prove the work: \\`cd /tmp/sisyphus-tutorial-demo && node --test test.js\\`\n- Show the session artifacts: find the session dir in \\`.sisyphus/sessions/\\` and show \\`roadmap.md\\`\n- Explain: \"Every session creates a roadmap, agent reports, and logs — all stored in .sisyphus/sessions/\"\n\n### 6. Proceed to wrap-up\n\nTell the user the demo is done. Then run:\n\\`\\`\\`\nsisyphus getting-started --tutorial 5\n\\`\\`\\`\n</claude-instructions>\n`);\n}\n\nfunction printStep5(): void {\n // Gather codebase context for suggestions\n let recentCommits = '';\n let topLevelFiles = '';\n try {\n recentCommits = execSync('git log --oneline -15 2>/dev/null', { encoding: 'utf-8' }).trim();\n } catch { /* not in a git repo */ }\n try {\n topLevelFiles = execSync('ls -1 2>/dev/null', { encoding: 'utf-8' }).trim();\n } catch { /* ignore */ }\n\n console.log(`\n<claude-instructions>\n# Sisyphus Getting Started — Step 5: What's Next\n\n## Codebase Context\n<recent-commits>\n${recentCommits || '(no git repo detected)'}\n</recent-commits>\n\n<top-level-files>\n${topLevelFiles || '(could not list)'}\n</top-level-files>\n\n## Instructions for Claude\n\n### 1. Congratulate them\n\nTell them they've completed the tutorial and recap what they learned:\n- tmux basics (sessions, panes, navigation)\n- nvim basics for reviewing files\n- The sisyphus session model (separate tmux session for orchestrator + agents)\n- Monitoring with dashboard and keybinds\n- A live session lifecycle\n\n### 2. Navigation cheat sheet\n\n| Key | Action |\n|-----|--------|\n| \\`Ctrl+n\\` / \\`Ctrl+p\\` | Next/previous tmux window |\n| \\`Ctrl+h/j/k/l\\` | Navigate between panes |\n| \\`Right Option + s\\` | Jump to sisyphus agent session |\n| \\`Right Option + Shift + s\\` | Jump to dashboard |\n\n### 3. How to use sisyphus for REAL work\n\nThis is the most important part. Explain clearly:\n\n> **Sisyphus is for big, end-to-end features — the kind that need exploration,\n> planning, and parallel implementation across multiple systems.**\n>\n> You don't need to define the task precisely. Broad is fine — the orchestrator\n> will explore the codebase, write specs, plan phases, and break it down itself.\n\n**Real sisyphus sessions (from production use):**\n- \"Design and implement a human-in-the-loop agent inbox system\" — exploration, spec writing, DB schema, API endpoints, UI components, webhook integration, e2e validation\n- \"Build multi-user organization features — invites, privilege gating, org switcher, workspace sharing, credit tracking\" — touched auth, DB, API, UI, billing, permissions\n- \"Rework all 5 worker onboarding templates to match production pipeline patterns\" — mapped existing patterns, designed new architecture, implemented across templates, validated with e2e tests\n- \"Autonomous failure detection system across 8 sequential phases\" — monitoring, alerting, recovery, dashboard, with each phase building on the last\n- \"Comprehensive code quality audit — find and fix dead code, null handling, useless fallbacks\" — systematic codebase-wide analysis and cleanup\n- \"Implement @requirements.md\" — point it at a spec and let it go\n\n**NOT good for sisyphus:**\n- Five unrelated small tasks bundled together (\"fix the login bug, update the README, add a loading spinner\") — these aren't one feature, they're a todo list\n- Something Claude Code in plan mode would handle — plan mode already handles substantial single-engineer work. If it fits in one Claude session, just do it directly.\n- Quick fixes, bug fixes, small refactors — use regular Claude Code\n\n**How to start:**\nThe easiest way is the \\`/sisyphus:begin\\` slash command inside Claude Code. Just tell Claude\nwhat you want to build and it'll hand it off to sisyphus with the right context.\n\nOr directly: \\`sisyphus start \"your task\" -c \"any background context\"\\`\n\n### 4. Suggest real tasks for THEIR codebase\n\nLook at the recent commits and top-level files above. Based on what you can see of their project, suggest 2-3 concrete sisyphus-scale tasks they could try. Be specific to their codebase — reference actual directories, patterns, or areas you can see.\n\nIf there are no commits or files (e.g., they ran this from /tmp), skip this section.\n\nFormat as:\n> Based on your codebase, here are some tasks sisyphus would be great for:\n> - \"...\"\n> - \"...\"\n\n### 5. There's more to learn\n\nTell them:\n\n> There's actually a lot of depth to how sisyphus works — the design is intentional\n> and there's real reasoning behind why it does things the way it does. If you want\n> to understand the philosophy, or you want a deeper rundown on the dashboard,\n> monitoring, configuration, or how to steer sessions — just ask and I'll explain.\n\nIf the user says yes or asks to learn more, run \\`sisyphus getting-started --explain\\`\nand use its output to explain the system to them conversationally. Don't dump the whole\nthing — answer what they're curious about, using the reference as your source material.\n</claude-instructions>\n`);\n}\n\nfunction printExplain(): void {\n console.log(`\n<claude-instructions>\n# Sisyphus — Comprehensive Reference\n\nThis is a detailed reference for how sisyphus works. The user asked to understand\nsisyphus more deeply. Use this to answer their questions conversationally — don't dump\nthe whole thing. Read through it, then respond to what they're curious about.\n\n## Design Philosophy\n\nSisyphus is built on specific insights about how to get the best work out of LLM agents.\nThese aren't arbitrary — each design decision solves a real failure mode.\n\n### 1. The Orchestrator as \"Human-in-the-Loop\"\n\nWhen you use Claude Code effectively, YOU are the orchestrator — you review work,\nsteer direction, break problems down, and assign the next piece. Sisyphus automates\nthat human role. The orchestrator does what a skilled developer does when prompting\nClaude: explore the codebase, understand the problem, write specs, plan phases,\nassign focused work, review results, and iterate.\n\nThe strategy layer mirrors how developers actually work on end-to-end features:\nexplore, understand, spec, plan, implement, review, validate. The orchestrator\nfollows this same workflow, but runs it with parallel agents.\n\n### 2. Fresh Context Kills Shortcuts\n\nThe orchestrator is KILLED after every cycle and respawned fresh. This is the most\nimportant design decision.\n\nWhen an LLM accumulates context over a long session, it starts taking shortcuts.\nIt \"knows\" what it did earlier, so it skips re-reading, assumes things still hold,\nand builds on stale understanding. A fresh start forces honest reassessment every\ncycle — the orchestrator reads the actual state, not its memory of it.\n\nThis is inspired by adversarial training (think GANs) — better results come from\nadversarial pressure. Each fresh orchestrator effectively audits the previous cycle's\nwork because it has no stake in defending prior decisions. It sees the roadmap, the\nreports, the code — and judges them with fresh eyes.\n\n### 3. Single-Focus Agents\n\nEach agent gets ONE task with a fully self-contained instruction. No context switching,\nno juggling multiple concerns, no \"also while you're there could you...\"\n\nLLMs perform dramatically better when focused. An agent implementing a priority field\ndoesn't think about the stats endpoint. It reads the relevant context, does its one\nthing well, and reports back. The orchestrator handles decomposition — agents handle\nexecution.\n\n### 4. Shared Context Directory (Saved Research)\n\nEvery session has a context/ directory where agents save research, specs, plans, and\ndesign docs. These files persist across ALL cycles and are visible to the orchestrator\nand subsequent agents.\n\nThis means research is never repeated. Cycle 1 agents explore and write findings to\ncontext/explore-auth-system.md. Cycle 3 agents read those findings and build on them.\nKnowledge accumulates even though the orchestrator itself is stateless.\n\n### 5. Two-Layer Planning (Strategy + Roadmap)\n\nThe system maintains two documents at different abstraction levels:\n\n**strategy.md** — The high-level problem-solving map. What phases exist, what gates\nbetween them, what backtrack paths exist. Updated every few cycles when the shape of\nwork changes. Helps the orchestrator see the forest.\n\n**roadmap.md** — Working memory. Updated every cycle. Current Stage, Exit Criteria,\nActive Context, Next Steps. The orchestrator reads this first each cycle to understand\nwhere things stand. Helps the orchestrator see the trees.\n\nThis prevents the failure mode where a single document becomes either too abstract\nto act on or too detailed to show the big picture.\n\n### 6. Adversarial Review Is Built In\n\nThe orchestrator doesn't just implement — it runs mandatory critique cycles. After\nimplementation, review agents attack different dimensions: code reuse, quality,\nefficiency, correctness. Fix agents address the findings. Re-review until only nits\nremain. Multiple agents auditing each other produces better results than any single\nagent reviewing its own work.\n\nThe rule: never let 2+ stages complete without critique. Small issues compound into\narchitectural problems if unchecked.\n\n### 7. Evidence Over Assumptions\n\nValidation requires PROOF — command output, test results, HTTP responses. \"The code\nlooks correct\" is not evidence. \"All 14 tests pass\" is. This catches the gap between\ncode that looks right and code that works.\n\n## Architecture Overview\n\n\\`\\`\\`\n┌─────────────────────────────────────────────────────────────────────┐\n│ USER'S TMUX SESSION │\n│ │\n│ ┌─────────────────────────┐ ┌──────────────────────────────────┐ │\n│ │ Window 1: Claude Code │ │ Window 2: Dashboard (TUI) │ │\n│ │ │ │ │ │\n│ │ User's normal work │ │ Real-time session monitor │ │\n│ │ + this conversation │ │ Roadmap, agents, reports │ │\n│ │ │ │ Interactive controls │ │\n│ └─────────────────────────┘ └──────────────────────────────────┘ │\n└──────────────────────────────────┬──────────────────────────────────┘\n │ Right Option+s / Right Option+Shift+s\n ▼\n┌─────────────────────────────────────────────────────────────────────┐\n│ SISYPHUS TMUX SESSION │\n│ (created per sisyphus session) │\n│ │\n│ ┌──────────┬──────────┬──────────┬──────────┐ │\n│ │ Orch │ Agent │ Agent │ Agent │ ← panes │\n│ │ (yellow) │ (blue) │ (green) │ (magenta)│ │\n│ │ │ │ │ │ │\n│ │ Plans, │ Impl │ Tests │ Docs │ ← each is a │\n│ │ assigns, │ feature │ │ │ Claude Code │\n│ │ reviews │ │ │ │ instance │\n│ └──────────┴──────────┴──────────┴──────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n │\n ▼\n┌─────────────────────────────────────────────────────────────────────┐\n│ DAEMON (sisyphusd) │\n│ Background process via launchd │\n│ │\n│ Listens on ~/.sisyphus/daemon.sock │\n│ Manages session lifecycle, pane monitoring, state persistence │\n│ Polls panes to detect when agents/orchestrator finish │\n└─────────────────────────────────────────────────────────────────────┘\n\\`\\`\\`\n\n## The Session Lifecycle (in detail)\n\n\\`\\`\\`\n ┌──────────────────────────────────────────────────────────────────┐\n │ SESSION LIFECYCLE │\n │ │\n │ sisyphus start \"task\" │\n │ │ │\n │ ▼ │\n │ ┌─────────┐ spawn agents ┌──────────────┐ │\n │ │ Orch │ ──────────────────→ │ Agents work │ │\n │ │ plans │ then yields │ in parallel │ │\n │ └────┬────┘ └──────┬───────┘ │\n │ │ │ each calls │\n │ │ orchestrator │ sisyphus submit │\n │ │ is KILLED │ when done │\n │ │ ▼ │\n │ │ ┌──────────────┐ │\n │ │ │ All agents │ │\n │ │ │ finished? │ │\n │ │ └──────┬───────┘ │\n │ │ │ yes │\n │ │ ┌──────────────────────┘ │\n │ │ ▼ │\n │ │ ┌─────────┐ │\n │ └──── │ Respawn │ Fresh orchestrator with full state │\n │ next cycle │ Orch │ Reviews reports, plans next cycle │\n │ └────┬────┘ │\n │ │ │\n │ ▼ │\n │ ┌───────────────┐ ┌───────────┐ │\n │ │ More work │──yes──→ │ Spawn │ → (loop) │\n │ │ needed? │ │ agents │ │\n │ └───────┬───────┘ └───────────┘ │\n │ │ no │\n │ ▼ │\n │ ┌───────────────┐ │\n │ │ sisyphus │ │\n │ │ complete │ │\n │ └───────────────┘ │\n └──────────────────────────────────────────────────────────────────┘\n\\`\\`\\`\n\n**Key insight**: The orchestrator is STATELESS. It gets killed after each yield and\nrespawned fresh with the complete session state (roadmap, agent reports, cycle history).\nThis means it never runs out of context, no matter how many cycles a session takes.\n\n## The Dashboard\n\nThe dashboard is a real-time TUI that shows session state. Launch with \\`sisyphus dashboard\\`\nor it auto-opens when a session starts.\n\n**Dashboard sections:**\n- **Header**: Session ID, status, task description\n- **Roadmap**: Current strategic plan with checked/unchecked items\n- **Agents**: List of all agents with status, duration, and report summaries\n- **Cycles**: Orchestrator cycle history\n- **Messages**: Recent session messages\n\n**Dashboard keys:**\n| Key | Action |\n|-----|--------|\n| \\`m\\` | Message the orchestrator (steer direction mid-session) |\n| \\`w\\` | Jump to the sisyphus tmux session (watch agents work) |\n| \\`k\\` | Kill the session |\n| \\`r\\` | Resume a paused/completed session |\n| \\`q\\` | Quit the dashboard |\n| \\`↑/↓\\` | Scroll through content |\n| \\`Tab\\` | Cycle through sections |\n\n**The \\`m\\` key is the most powerful feature.** You can message the orchestrator at any time\nto course-correct: \"Focus on the API layer first\", \"Skip the tests for now\",\n\"The approach for auth is wrong, use JWT instead\". The orchestrator reads these\nmessages when it respawns each cycle.\n\n## Monitoring Strategy\n\nSisyphus sessions should be actively monitored. Here's what to watch for:\n\n**Things that go wrong:**\n- Agents stuck waiting for user input (they're autonomous — they shouldn't need input)\n- Agents going down rabbit holes or working on the wrong thing\n- Merge conflicts between agents touching the same files\n- Orchestrator spawning too many agents or too few\n- Agents crashing or getting killed unexpectedly\n\n**When to intervene:**\n- Use \\`m\\` in the dashboard to message the orchestrator with corrections\n- Use \\`sisyphus kill <id>\\` to stop a runaway session\n- Use \\`sisyphus resume <id> \"new instructions\"\\` to restart with different direction\n\n**Useful monitoring commands:**\n\\`\\`\\`\nsisyphus status <id> # Quick status check\nsisyphus status --verbose <id> # Full detail: roadmap, pane output, agent instructions\nsisyphus dashboard # Interactive TUI\ntail -f ~/.sisyphus/daemon.log # Daemon activity log\n\\`\\`\\`\n\n## The .sisyphus/ Directory\n\nEverything sisyphus does lives in a \\`.sisyphus/\\` directory at the root of your project.\nThis is project-local — each project gets its own. It contains:\n\n\\`\\`\\`\n.sisyphus/\n├── config.json # Project-specific config (model, poll interval, etc.)\n├── orchestrator.md # Optional custom orchestrator prompt override\n└── sessions/\n ├── <session-id-1>/ # Each session gets its own directory\n ├── <session-id-2>/\n └── ...\n\\`\\`\\`\n\nThere's also a global directory at \\`~/.sisyphus/\\` for the daemon socket, PID file,\nlogs, keybind scripts, and global config. But the session state — the roadmaps,\nreports, context files, cycle logs — all lives in your project's \\`.sisyphus/sessions/\\`.\n\n## Session Files\n\nEvery session creates a directory at \\`.sisyphus/sessions/<id>/\\` with:\n\n\\`\\`\\`\n.sisyphus/sessions/<id>/\n├── state.json # Session state (agents, cycles, status)\n├── roadmap.md # Strategic plan (updated by orchestrator each cycle)\n├── goal.md # Original task description\n├── strategy.md # High-level strategy notes\n├── logs/\n│ ├── cycle-000.md # What the orchestrator did in cycle 0\n│ ├── cycle-001.md # What it did in cycle 1, etc.\n│ └── ...\n├── reports/\n│ ├── agent-001-final.md # Agent's final report\n│ ├── agent-002-update.md # Agent's progress update\n│ └── ...\n├── prompts/ # System/user prompts sent to orchestrator and agents\n└── context/ # Shared context files for agents\n\\`\\`\\`\n\n## Configuration\n\n**Global config**: \\`~/.sisyphus/config.json\\`\n**Project config**: \\`.sisyphus/config.json\\` (overrides global)\n\nOptions:\n- \\`model\\` — Claude model for orchestrator and agents\n- \\`orchestratorPrompt\\` — Path to custom orchestrator prompt\n- \\`pollIntervalMs\\` — How often daemon checks pane status (default: 2000)\n\n## Starting Sessions — Best Practices\n\n**The /sisyphus:begin slash command** is the recommended way to start. Inside Claude Code:\n\\`\\`\\`\n/sisyphus:begin\n\\`\\`\\`\nThen describe your task. Claude will hand it off with the right context.\n\n**Direct CLI:**\n\\`\\`\\`\nsisyphus start \"task description\" -c \"background context\"\nsisyphus start \"Implement @requirements.md\" -n my-feature\n\\`\\`\\`\n\n**Reference files with @**: \\`sisyphus start \"Build @docs/spec.md\"\\` — the orchestrator\nwill read the referenced file as part of its planning.\n\n**The -c flag** adds background context the orchestrator sees but doesn't act on directly.\nUse it for constraints: \\`-c \"Don't modify the auth module, use the existing API\"\\`\n\n**The -n flag** gives the session a human-readable name for easier tracking.\n\n## CLI Command Reference\n\n| Command | Purpose |\n|---------|---------|\n| \\`sisyphus start \"task\"\\` | Start a new session |\n| \\`sisyphus status [id]\\` | Check session status |\n| \\`sisyphus status -v [id]\\` | Detailed status with pane output |\n| \\`sisyphus list\\` | List all sessions |\n| \\`sisyphus dashboard\\` | Open the TUI dashboard |\n| \\`sisyphus resume <id> \"msg\"\\` | Resume with new instructions |\n| \\`sisyphus kill <id>\\` | Stop a session |\n| \\`sisyphus doctor\\` | Check installation health |\n| \\`sisyphus setup\\` | Run setup/onboarding |\n| \\`sisyphus setup-keybind\\` | Install tmux keybinds |\n\n## Troubleshooting\n\n**Daemon not running:**\n\\`\\`\\`\nsisyphusd restart\n\\`\\`\\`\n\n**Keybinds not working (special characters appear):**\niTerm2 → Settings → Profiles → Keys → Right Option Key → Esc+\n\n**Agents stuck:** Check \\`sisyphus status --verbose <id>\\` to see pane output. If an\nagent is waiting for input, kill the session and restart with clearer instructions.\n\n**Dashboard not opening:** Run \\`sisyphus dashboard\\` manually. Must be inside tmux.\n\n**Session seems hung:** Check \\`tail -20 ~/.sisyphus/daemon.log\\` for errors.\nThe daemon polls panes every 2s — if a pane dies unexpectedly, it'll be detected.\n</claude-instructions>\n`);\n}\n\nconst STEPS: Array<() => void> = [printStep0, printStep1, printStep2, printStep3, printStep4, printStep5];\n\nexport function registerGettingStarted(program: Command): void {\n program\n .command('getting-started')\n .description('Interactive tutorial (best with Claude Code)')\n .option('--tutorial <step>', 'Tutorial step (0-5)', parseInt)\n .option('--explain', 'Comprehensive reference for how sisyphus works')\n .action((opts) => {\n if (opts.explain) {\n printExplain();\n return;\n }\n if (opts.tutorial !== undefined) {\n const step = opts.tutorial as number;\n if (step < 0 || step > 5 || Number.isNaN(step)) {\n console.error(`Invalid tutorial step: ${opts.tutorial}. Must be 0-5.`);\n process.exit(1);\n }\n STEPS[step]!();\n return;\n }\n if (!isClaudeCode()) {\n printNonClaudeMessage();\n return;\n }\n printStep0();\n });\n}\n","import type { Command } from 'commander';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nconst DEFAULT_CONFIG = {};\n\nconst ORCHESTRATOR_TEMPLATE = `# Custom Orchestrator Prompt\n\n<!-- This file overrides the default orchestrator system prompt. -->\n<!-- Delete this file to use the built-in prompt. -->\n<!-- See: https://github.com/silasrhyneer/sisyphi for details. -->\n`;\n\nexport function registerInit(program: Command): void {\n program\n .command('init')\n .description('Initialize sisyphus configuration for this project')\n .option('--orchestrator', 'Also create a custom orchestrator prompt template')\n .action((opts: { orchestrator?: boolean }) => {\n const cwd = process.cwd();\n const sisDir = join(cwd, '.sisyphus');\n const configPath = join(sisDir, 'config.json');\n\n if (existsSync(configPath)) {\n console.log(`Already initialized: ${configPath}`);\n return;\n }\n\n mkdirSync(sisDir, { recursive: true });\n writeFileSync(configPath, JSON.stringify(DEFAULT_CONFIG, null, 2) + '\\n', 'utf-8');\n console.log(`Created ${configPath}`);\n\n if (opts.orchestrator) {\n const orchPath = join(sisDir, 'orchestrator.md');\n if (!existsSync(orchPath)) {\n writeFileSync(orchPath, ORCHESTRATOR_TEMPLATE, 'utf-8');\n console.log(`Created ${orchPath}`);\n }\n }\n\n console.log('');\n console.log('Configuration options (add to .sisyphus/config.json):');\n console.log(' orchestratorEffort — \"low\" | \"medium\" | \"high\" | \"max\" (default: \"high\")');\n console.log(' agentEffort — \"low\" | \"medium\" | \"high\" | \"max\" (default: \"medium\")');\n console.log(' pollIntervalMs — Daemon poll interval in ms (default: 5000)');\n console.log(' autoUpdate — Auto-update daemon on restart (default: true)');\n console.log(' notifications — { enabled: boolean, sound: string } (default: enabled, Hero.aiff)');\n });\n}\n","import { execSync } from 'node:child_process';\nimport type { Command } from 'commander';\nimport { runOnboarding, type OnboardResult } from '../onboard.js';\nimport { ensureDaemonInstalled, isInstalled } from '../install.js';\nimport { setupTmuxKeybind, DEFAULT_KEY, DEFAULT_HOME_KEY } from '../tmux-setup.js';\n\nfunction getTmuxVersion(): string {\n try {\n return execSync('tmux -V', { encoding: 'utf-8', stdio: 'pipe' }).trim();\n } catch {\n return 'installed';\n }\n}\n\nfunction printResults(result: OnboardResult, daemonOk: boolean, keybindMsg: string): void {\n console.log('');\n console.log('Setting up Sisyphus...');\n console.log('');\n\n // tmux\n if (result.tmuxInstalled) {\n const detail = getTmuxVersion();\n console.log(` \\u2713 tmux: ${detail}${result.tmuxAutoInstalled ? ' (just installed)' : ''}`);\n } else {\n const hint = process.platform === 'darwin'\n ? 'Install Homebrew (https://brew.sh) then: brew install tmux'\n : 'apt install tmux (Debian/Ubuntu) or your package manager';\n console.log(` \\u2717 tmux: Not installed \\u2014 ${hint}`);\n }\n\n // tmux config\n if (result.tmuxDefaultsWritten) {\n console.log(' \\u2713 tmux config: Sensible defaults written to ~/.tmux.conf');\n }\n\n // Terminal\n if (process.platform === 'darwin') {\n if (result.terminal.isIterm) {\n console.log(` \\u2713 Terminal: ${result.terminal.name}`);\n } else {\n const name = result.terminal.name ? result.terminal.name : 'unknown';\n console.log(` \\u26a0 Terminal: ${name} \\u2014 iTerm2 recommended (https://iterm2.com)`);\n }\n }\n\n // iTerm option key\n if (result.itermOptionKey.checked) {\n if (result.itermOptionKey.allCorrect) {\n console.log(' \\u2713 Right Option Key: Esc+');\n } else {\n const profiles = result.itermOptionKey.incorrectProfiles.map((p) => `\"${p}\"`).join(', ');\n console.log(` \\u26a0 Right Option Key: Not set to Esc+ for ${profiles}`);\n console.log(' Fix: iTerm2 \\u2192 Settings \\u2192 Profiles \\u2192 Keys \\u2192 Right Option Key \\u2192 Esc+');\n }\n }\n\n // Daemon\n if (daemonOk) {\n console.log(' \\u2713 Daemon: Running');\n } else {\n console.log(' \\u2717 Daemon: Failed to start');\n }\n\n // Keybindings\n console.log(` \\u2713 Keybindings: ${keybindMsg}`);\n\n // /begin command\n if (result.command.installed) {\n console.log(` \\u2713 /begin command: ${result.command.path}${result.command.autoInstalled ? ' (just installed)' : ''}`);\n } else {\n console.log(' \\u2717 /begin command: Failed to install');\n }\n\n // Nvim\n if (result.nvim.installed) {\n const extra = result.nvim.autoInstalled ? ' (just installed)' : '';\n console.log(` \\u2713 Editor: nvim ${result.nvim.version}${extra}`);\n if (result.nvim.lazyVimInstalled) {\n console.log(' \\u2713 LazyVim: Starter config installed to ~/.config/nvim/');\n }\n } else {\n console.log(' \\u26a0 Editor: nvim not installed');\n if (process.platform === 'darwin') {\n console.log(' Install: brew install neovim');\n }\n }\n\n console.log('');\n console.log(\"Run 'sisyphus getting-started' for a usage guide.\");\n console.log('');\n}\n\nexport function registerSetup(program: Command): void {\n program\n .command('setup')\n .description('One-time setup: install dependencies, daemon, keybindings, and commands')\n .action(async () => {\n // 1. Onboarding (tmux, terminal, iterm, nvim, plugin)\n const result = runOnboarding();\n\n // 2. Daemon\n let daemonOk = false;\n try {\n await ensureDaemonInstalled();\n daemonOk = true;\n } catch {\n daemonOk = isInstalled();\n }\n\n // 3. Keybindings\n const keybindResult = setupTmuxKeybind();\n let keybindMsg: string;\n if (keybindResult.status === 'installed' || keybindResult.status === 'already-installed') {\n keybindMsg = `${DEFAULT_KEY} (cycle), ${DEFAULT_HOME_KEY} (dashboard)`;\n } else {\n keybindMsg = keybindResult.message;\n }\n\n printResults(result, daemonOk, keybindMsg);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,eAAe;AACxB,SAAS,cAAAA,aAAY,aAAAC,YAAW,gBAAAC,qBAAoB;AACpD,SAAS,WAAAC,UAAS,QAAAC,aAAY;AAC9B,SAAS,iBAAAC,sBAAqB;;;ACR9B,SAAS,YAAAC,iBAAgB;;;ACDzB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,cAAAC,aAAY,aAAAC,YAAW,gBAAAC,eAAc,QAAQ,cAAAC,aAAY,iBAAAC,sBAAqB;AACvF,SAAS,eAAe;AACxB,SAAS,WAAAC,gBAAe;AACxB,SAAS,SAAS,QAAAC,OAAM,eAAe;AACvC,SAAS,qBAAqB;;;ACL9B,SAAS,gBAAgB;AACzB,SAAS,YAAY,WAAW,cAAc,eAAe,WAAW,kBAAkB;AAC1F,SAAS,eAAe;AACxB,SAAS,YAAY;AAGd,IAAM,cAAc;AACpB,IAAM,mBAAmB;AAEhC,IAAM,uBAAuB;AAEtB,SAAS,kBAA0B;AACxC,SAAO,KAAK,UAAU,GAAG,OAAO,gBAAgB;AAClD;AAEO,SAAS,iBAAyB;AACvC,SAAO,KAAK,UAAU,GAAG,OAAO,eAAe;AACjD;AAEO,SAAS,qBAA6B;AAC3C,SAAO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AC5B,eAAe,OAAO;AACtB,yBAAyB,OAAO;AAChC,uBAAuB,OAAO;AAC9B,aAAa,OAAO;AACpB,cAAc,OAAO;AAErB,QAAQ,YAAY,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAS5B;AAGD,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,IAAM,WAAW,KAAK,CAAC;AACvB,IAAM,cAAc,CAAC,UAAU,mBAAmB,QAAQ,UAAU,MAAM,QAAQ,SAAS,aAAa,aAAa,IAAI;AACzH,IAAI,CAACC,YAAW,UAAU,CAAC,KAAK,YAAY,CAAC,YAAY,SAAS,QAAQ,GAAG;AAC3E,EAAAC,WAAU,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;AAC1C,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,6DAA6D;AACzE,UAAQ,IAAI,EAAE;AAChB;AAEA,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAe;AACrD,UAAQ,MAAM,IAAI,OAAO;AACzB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","mkdirSync","readFileSync","dirname","join","fileURLToPath","execSync","execSync","existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","homedir","join","execSync","execSync","join","homedir","existsSync","mkdirSync","writeFileSync","execSync","unlinkSync","resolve","readFileSync","rawSend","sleep","resolve","execSync","join","execSync","execSync","join","program","program","execSync","existsSync","join","resolve","program","join","existsSync","program","program","program","program","execSync","existsSync","readFileSync","readFileSync","existsSync","execSync","program","RESET","BOLD","DIM","program","program","program","program","resolve","program","program","rawSend","program","program","program","program","program","execSync","existsSync","execSync","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","join","fileURLToPath","plistPath","execSync","existsSync","program","program","execSync","dirname","join","fileURLToPath","join","dirname","fileURLToPath","execSync","program","existsSync","mkdirSync","writeFileSync","join","program","execSync","execSync","program","readFileSync","join","dirname","fileURLToPath","existsSync","mkdirSync"]}