sudocode
Lightweight agent orchestration dev tool that lives in your repo
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/sudocode-ai/sudocode with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/sudocode-ai/sudocode'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/sudocode-ai--sudocode)HTML
<a href="/listings/sudocode-ai--sudocode"><img src="/api/listings/sudocode-ai--sudocode/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
# Install globally (recommended: use npx instead to avoid Node version conflicts) npm install -g sudocode # Initialize a sudocode project in your project directory. sudocode init # Run the local sudocode server from anywhere sudocode server # To connect your agent directly to sudocode, install our plugin claude plugin marketplace add sudocode-ai/sudocode claude plugin install sudocode # Note, instructions for other agents can be found in the quick start guide
Check out our [Quick Start Guide](https://docs.sudocode.ai/quickstart#step-4%3A-set-up-your-agent) for tutorials and walkthroughs.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 15 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "name": "sudocode-marketplace",
- "description": "Local marketplace for sudocode plugins",
- "owner": {
- "name": "sudocode AI"
- },
- "plugins": [
- {
- "name": "sudocode",
- "source": "./",
- "description": "Git-native spec and issue management for AI-assisted development",
- "version": "0.2.0"
- }
- ]
- }
README.md · README · 316 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <div align="center">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="media/banner-otto-dusk.gif">
- <source media="(prefers-color-scheme: light)" srcset="media/banner-otto-day.gif">
- <img alt="sudocode banner" src="media/banner-otto-day.gif">
- </picture>
- </div>
- <h1 align="center">sudocode</h1>
- <div align="center">
- <a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
- <img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 22px;" />
- </a><a target="_blank" href="https://www.npmjs.com/package/sudocode" style="background:none">
- <img src="https://img.shields.io/badge/npm-sudocode-orange" style="height: 22px;" />
- </a><a target="_blank" href="https://docs.sudocode.ai" style="background:none">
- <img src="https://img.shields.io/badge/Docs-docs-green" style="height: 22px;" alt="Documentation" />
- </a><a target="_blank" href="https://discord.gg/5t8GUW65EW" style="background:none">
- <img src="https://img.shields.io/discord/1115708641052471446?logo=discord&logoColor=5865F2&label=Discord&color=5865F2" style="height: 22px;" alt="Discord" />
- </a>
- </div>
- <br/>
- <p align="center">
- <code>npm install -g sudocode</code>
- </p>
- <p align="center">
- <b>Automate the logistics of managing context and agents. Direct the work instead of babysitting agents.</b></p>
- sudocode is a lightweight agent orchestration system that lives in your repo. Adding sudocode into your repo adds instant organizational capabilities to your coding agents. They'll gain the ability to track context over long-horizon tasks and work collaboratively on complex tasks.
- ### Key capabilities
- - Automate context handoff for complex tasks with sudocode's git-native agent memory system
- - Bring order to chaos by organizing your requirements, background context, and implementation plans into structured, executable issue graphs
- - Visualize outputs and execution feedback in real-time
- - Run as many Claude Code/Codex/Cursor (+more) agents in parallel as you can handle
- ### How it works
- sudocode tracks human-specified requirements and objectives (what to do) as specs, and agent runtime context and plans (how to implement) as issues. These are trackable in git as a form of version-controlled memory for your agents. Specs/issues are both human and agent-editable. This allows agents to manage their own context and leave contextual breadcrumbs as they run for all agents to reference.
- Specs and issues form the backbone for advanced agent coordination and automation. Use specs to define high-level requirements and let agents carry out the implementation and manage their own issues.
- ### How to use it
- The sudocode package includes a CLI, local server/UI, and an MCP server.
- Use the CLI for managing specs and issues in sudocode's agent memory system. It contains a complete interface for viewing, editing, and managing relationships between entities.
- Use the local server to automatically sync memory and enable agent execution and visualization. The issue kanban view helps you track issue status and progress. You can spawn new agents, update agent implementation plans, and provide feedback or guidance to running agents in a single, focused view.
- <div style="margin: 2em 0;">
- <img src="media/screenshots/issue-kanban.png" alt="Issue kanban view">
- </div>
- The spec editor view boosts spec-driven development to new heights. Edit and review specs with a full-featured block or markdown editor. Agents leave feedback on specs as they execute, so you can track their work and stay in the know for with the code they produce.
- <div style="margin: 2em 0;">
- <img src="media/screenshots/spec-viewer.png" alt="Spec editor view">
- </div>
- Once you have a dependency graph of issues, you can also automate the implementation of each issue in the graph as a workflow. This runs each issue in topological order and accumulates changes in a temp branch/worktree. As it's executing, each issue will have its own commit, so you can revert backwards in the commit history if you want to continue developing from a specific point.
- <div style="margin: 2em 0;">
- <img src="media/screenshots/workflow.png" alt="Workflow automation view">
- </div>
- If you're up for it, you can even monitor all running agent trajectories at the same time.
- <div style="margin: 2em 0;">
- <img src="media/screenshots/execution-panel.png" alt="Execution monitoring panel">
- </div>
- **sudocode** provides a structured yet flexible system for organizing the chaos of human-AI collaboration in software development.
- ## Quick Start
- ```bash
- # Install globally (recommended: use npx instead to avoid Node version conflicts)
- npm install -g sudocode
- # Initialize a sudocode project in your project directory.
- sudocode init
- # Run the local sudocode server from anywhere
- sudocode server
- # To connect your agent directly to sudocode, install our plugin
- claude plugin marketplace add sudocode-ai/sudocode
- claude plugin install sudocode
- # Note, instructions for other agents can be found in the quick start guide
- ```
- Check out our [Quick Start Guide](https://docs.sudocode.ai/quickstart#step-4%3A-set-up-your-agent) for tutorials and walkthroughs.
- ## External Integrations
- sudocode now supports syncing with external spec and issue tracking systems through a plugin-based integration framework. This allows you to maintain specs and issues in your preferred tools while keeping sudocode's agent memory system in sync.
- **Supported Integrations:**
- | Integration | Description | Sync Direction |
- |-------------|-------------|----------------|
- | **[Beads](https://github.com/steveyegge/beads)** | Git-native issues system | Bidirectional |
- | **[Spec-Kit](https://github.com/github/spec-kit)** | Markdown-based specification system | Bidirectional |
- | **[OpenSpec](https://github.com/Fission-AI/OpenSpec)** | Structured spec and change proposal system | Bidirectional |
- | **Jira** | Atlassian issue tracking | *Coming soon* |
- | **Linear** | Modern issue tracking | *Coming soon* |
- In the sudocode UI, enable integrations in Settings > Integrations. Via the CLI, update with `sudocode plugin`.
- Integrations automatically create specs, issues, and relationships between synced entities and support real-time file watching for immediate sync updates. Use sudocode to link and implement work items across different systems.
- We're actively adding support for new integration targets. Please file an issue or drop a message for anything you would like sudocode to support!
- ## Context-as-Code
- Your context and designs are just as valuable as the code being written. Code is often over-specified, while your actual requirements are under-specified and come with design choices and intent that is not immediately captured.
- With sudocode, you treat your git repo as a distributed context database to capture context and make it readily available to coding agents. You can track user intent (specs), agent tasks (issues), and agent trajectories (executions) as they evolve alongside your codebase.
- - **Distributed Collaboration**: Human developers and AI agents share one logical database across multiple environments through git synchronization
- - **Lightweight**: All your context lives under your control in your repo
- - **Integrated Audit Trail**: Context can be recovered with git's immutable change tracking
- - **Agent Persistence**: Reduce agent hallucinations and amnesia by keeping task context in version-controlled files instead of ephemeral conversations
- Git handles distribution while AI handles merge conflicts.
- ## Spec-Driven Development
- A spec can be thought of as user intent + relevant context. Combined, a spec contains enough information for an agent to carry out the requirements defined in the task.
- - **Structured Context**: Create connections between your specs with a rich graph structure, and organize context dynamically so it is easily discoverable by agents
- - **Advanced Organization**: Create structured task dependencies to keep track of blocking issues and hidden relationships between tasks
- - **Iterative Refinement**: Move through multiple refinement stages as agents provide bi-directional feedback as they implement on your specs
- Reduce the chaos of "vibe coding" by establishing clear, executable requirements in order to produce predictable outcomes.
- ## Context Structure
- sudocode implements a **4-tiered abstraction structure** for representing context, corresponding to increasing granularity from high-level requirements to low-level implementation:
- ### 1. Spec (Specification)
- A primitive for **user intent** and context—requirements, RFCs, research questions, design decisions. Specs capture **WHAT** you want.
- - Organized as nodes in a graph structure
- - Support hierarchical relationships and cross-cutting links
- - Stored as human-editable Markdown with YAML frontmatter
- - Live in `.sudocode/specs/`
- ### 2. Issue
- A primitive for **agent intent** and context—work items derived from specs, capturing tasks within agent scope.
- - Link back to specific requirements in specs via `[[@ISSUE-001]]` references
- - Support hierarchical organization, dependencies, and relationships
- - Graph relationship types: `blocks`, `related`, `parent-child`, `discovered-from`
- - Stored as Markdown + JSONL (`.sudocode/issues/`)
- ### 3. Agent
- The **execution abstraction**—represents the actual trajectory of an agentic loop run against an issue.
- - Tracks agent system (Claude Code, Codex, etc.) and configurations
- - One-to-many relationship with issues (supports multiple execution sessions per issue)
- - Captures sub/multi-agent structures and unique workflows
- - Configuration stored in `.sudocode/agents/`
- ### 4. Artifact
- A primitive representing **state changes** from agent execution.
- - e.g. Code diffs for coding agents, reports for research agents, documentation updates for docs agents
- - Multiple artifacts per execution
- ## Key Features
- ### Dual Issue/Spec Representation
- Every entity has both a **human-editable format** (Markdown + YAML) and a **machine-optimized format** (JSONL + SQLite):
- - Write specs and issues as readable Markdown
- - Query and process through SQLite for performance
- - Auto-sync between formats (5-second debounce)
- - Git-friendly primary storage
- ### Bidirectional Linking
- Relationships are tracked in both directions:
- ```markdown
- ## Requirements
- 1. Support OAuth 2.0 [[ISSUE-001]]
- 2. Multi-factor authentication [[ISSUE-002]]
- See also [[SPEC-010]] for API design patterns.
- ```
- Backlinks are automatically tracked in the relationship graph.
- ### Graph-Based Planning
- Navigate dependencies, hierarchies, and relationships:
- - Topological ordering for execution (no-dependency, high-priority tasks first)
- - Hierarchical execution with subtask handoffs
- - Automatic issue claiming for multi-agent concurrency
- ### Agent Feedback Loops
- Agents can update specs with findings during execution, bridging lower to higher abstraction levels to keep humans in the loop.
- ### IDE Integration
- Open execution worktrees directly in your preferred IDE with a single click. The UI integrates with popular editors to streamline your workflow when reviewing or modifying agent-generated code.
- **Supported Editors:**
- - VS Code (`code`)
- - Cursor (`cursor`)
- - Windsurf (`windsurf`)
- - IntelliJ IDEA (`idea`)
- - Zed (`zed`)
- - Xcode (`xed`)
- - Custom command
- **Configuration:**
- Editor settings are in `.sudocode/config.json` (gitignored, created during init):
- ```json
- {
- "editor": {
- "editorType": "vs-code"
- }
- }
- ```
- **Supported Editor Types:**
- - `"vs-code"` - Visual Studio Code
- - `"cursor"` - Cursor
- - `"windsurf"` - Windsurf
- - `"intellij"` - IntelliJ IDEA
- - `"zed"` - Zed
- - `"xcode"` - Xcode
- - `"custom"` - Custom command (requires `customCommand` field)
- **Custom Editor Example:**
- ```json
- {
- "editor": {
- "editorType": "custom",
- "customCommand": "code-insiders"
- }
- }
- ```
- **Troubleshooting:**
- If the editor doesn't open:
- 1. Verify the editor is installed and in your PATH
- 2. Test the command manually: `code /path/to/directory`
- 3. Check the editor type in your config matches your installation
- 4. For macOS GUI apps, ensure the command-line tool is installed (e.g., VS Code's "Install 'code' command in PATH")
- ## Architecture
- ### Distributed Git Database
- - **Source of Truth**: JSONL files (`.sudocode/specs/specs.jsonl`, `.sudocode/issues/issues.jsonl`) committed to git
- - **Local Cache**: Each machine maintains a SQLite cache (`.sudocode/cache.db`, gitignored)
- - **Auto-Export**: SQLite → JSONL after CRUD operations (5-second debounce)
- - **Auto-Import**: JSONL → SQLite when JSONL is newer (e.g., after `git pull`)
- - **Conflict Resolution**: Git handles distribution, AI handles merge conflicts
- This design provides centralized database semantics through distributed git infrastructure.
- ## Development Flow
- ### 1. Create a Spec
- Define requirements, behaviors, abstractions, and design decisions:
- ```bash
- sudocode spec create auth-system
- # Then update created spec markdown file.
- ```
- ### 2. Create Sub-Specs (Optional)
- For complex specs, create hierarchical or cross-cutting relationships by creating references between specs and issues.
- ```markdown
- See [[SPEC-002]] for detailed API contracts.
- ```
- ### 3. Plan and Create Issues
- Invoke a planning agent to collaboratively define implementation issues.
- The agent:
- - Creates issues with `blocks`, `related`, `parent-child` relationships
- - Embeds issue references back into the spec: `[[@ISSUE-001]]`
- - Populates bidirectional links (issue → spec, spec → issue)
- TODO: Add a plan CLI command that hooks into the configured agent.
- ### 4. Execute Issues
- Invoke your coding agent to implement issues. Agents can pull ready issues or issue details to align on work items. Agents can also refer to specs for added context.
- - Issues with no blockers and higher priority execute first (topological order)
- - Agents can update specs with findings and feedback during execution
- - Multiple agent executions can run simultaneously
- ### 5. Manage Artifacts
- Artifacts and tracked as agents execute.
- - Code changes are marked for review or directly committed (user settings)
- - Issues are updated with artifact references for traceability
- ## Philosophy
- sudocode embraces:
- 1. **Context-as-Code**: Version-controlled, human-readable requirements and plans are persisted in source control
- 2. **Git-Native**: Everything lives in git—no external databases or services
- 3. **Flexible Structure**: Markdown content is free-form; structure emerges from user-defined conventions and usage patterns
cli/src/cli/update-commands.ts · Bundled script · 506 lines · 1 finding marked
- /**
- * Update command handlers
- */
- import chalk from "chalk";
- import { execSync } from "child_process";
- import { execFile } from "child_process";
- import { promisify } from "util";
- import * as fs from "fs";
- import * as path from "path";
- import * as os from "os";
- import * as crypto from "crypto";
- import { pipeline } from "stream/promises";
- import { createWriteStream } from "fs";
- import https from "https";
- import { checkForUpdates, dismissUpdate } from "../update-checker.js";
- import { detectInstallSource, detectPlatform, getBinaryInstallDir } from "../install-source.js";
- const execFileAsync = promisify(execFile);
- const GITHUB_REPO = "sudocode-ai/sudocode";
- /**
- * Detect which sudocode package is globally installed
- * Returns the package name to update
- */
- async function detectInstalledPackage(): Promise<string> {
- try {
- // Check if metapackage is installed
- execSync("npm list -g sudocode --depth=0", {
- stdio: "pipe",
- encoding: "utf8",
- });
- return "sudocode"; // Metapackage is installed
- } catch {
- // Metapackage not found, fall back to CLI
- return "@sudocode-ai/cli";
- }
- }
- /**
- * Install package with smart force retry
- * Tries without --force first, retries with --force only on EEXIST
- */
- function installPackageWithRetry(packageName: string): void {
- const baseCommand = `npm install -g ${packageName}`;
- console.log();
- console.log(chalk.cyan(`Running: ${baseCommand}`));
- console.log();
- try {
- // First attempt: without --force
- execSync(baseCommand, { stdio: "inherit" });
- } catch (error) {
- // Check if it's an EEXIST error
- if (error instanceof Error && error.message.includes("EEXIST")) {
- console.log();
- console.log(
- chalk.yellow("File already exists, retrying with --force...")
- );
- console.log();
- try {
- // Retry with --force
- const forceCommand = `${baseCommand} --force`;
- console.log(chalk.cyan(`Running: ${forceCommand}`));
- console.log();
- execSync(forceCommand, { stdio: "inherit" });
- } catch (retryError) {
- // If retry also fails, throw the error to be handled by caller
- throw retryError;
- }
- } else {
- // Not an EEXIST error, re-throw
- throw error;
- }
- }
- // Refresh Volta shim if sudocode is managed by Volta
- // This is necessary because Volta caches package locations at shell initialization
- if (isUsingVoltaForSudocode()) {
- console.log();
- console.log(chalk.dim("Detected Volta - refreshing package shim..."));
- try {
- execSync(`volta install ${packageName}`, { stdio: "inherit" });
- } catch (voltaError) {
- // Volta refresh failed - not critical since npm install succeeded
- console.log(chalk.yellow("Warning: Failed to refresh Volta shim"));
- console.log(chalk.dim("You may need to re-install sudocode"));
- }
- }
- }
- /**
- * Check if sudocode was installed via Volta
- *
- * Volta is a Node.js version manager that creates shims for globally installed packages.
- * When a package is installed via npm while Volta is active, the binary is placed in
- * Volta's managed directory (typically ~/.volta/bin or $VOLTA_HOME/bin).
- *
- * This function detects if the sudocode binary is managed by Volta by:
- * 1. Checking if Volta is installed on the system
- * 2. Getting the actual path of the sudocode executable
- * 3. Verifying the path is within Volta's managed directories
- *
- * Why this matters:
- * Volta caches the resolved paths of executables at shell initialization time.
- * When sudocode is updated via `npm install -g`, the files are updated but the
- * current shell session continues to use the old cached path until the shell
- * is restarted. This is Volta's intended behavior for performance.
- *
- * @returns true if sudocode binary is managed by Volta, false otherwise
- */
- function isUsingVoltaForSudocode(): boolean {
- try {
- // First check if Volta exists on the system
- execSync("volta --version", { stdio: "pipe" });
- // Get the actual path of the sudocode binary
- const binPath = execSync("which sudocode", {
- stdio: "pipe",
- encoding: "utf8",
- }).trim();
- // Check VOLTA_HOME environment variable if set (user may have custom location)
- const voltaHome = process.env.VOLTA_HOME;
- if (voltaHome) {
- return binPath.startsWith(voltaHome);
- }
- // Fall back to checking for default /.volta/ directory in path
- return binPath.includes("/.volta/");
- } catch {
- // Volta not installed, which command failed, or other error
- return false;
- }
- }
- /**
- * Best-effort update of the Claude Code marketplace plugin.
- * If the claude CLI is not available, prints a note and moves on.
- */
- function updateClaudePlugin(): void {
- try {
- execSync("claude --version", { stdio: "pipe" });
- } catch {
- console.log();
- console.log(
- chalk.dim("Claude CLI not found — skipping marketplace plugin update")
- );
- return;
- }
- try {
- console.log();
- console.log(chalk.dim("Updating Claude Code marketplace plugin..."));
- execSync("claude plugin marketplace update sudocode-ai/sudocode", {
- stdio: "inherit",
- });
- execSync("claude plugin update sudocode@sudocode-marketplace", {
- stdio: "inherit",
- });
- console.log(chalk.green("✓ Claude Code plugin updated"));
- } catch {
- // Best-effort — don't fail the overall update
- }
- }
- /**
- * Download a file from a URL, following redirects
- */
- function downloadFile(url: string, destPath: string): Promise<void> {
- return new Promise((resolve, reject) => {
- https.get(url, (res) => {
- if (res.statusCode === 301 || res.statusCode === 302) {
- downloadFile(res.headers.location!, destPath).then(resolve).catch(reject);
- return;
- }
- if (res.statusCode !== 200) {
- reject(new Error(`HTTP ${res.statusCode} for ${url}`));
- return;
- }
- const ws = createWriteStream(destPath);
- pipeline(res, ws).then(resolve).catch(reject);
- }).on("error", reject);
- });
- }
- /**
- * Compute SHA256 checksum of a file
- */
- function sha256File(filePath: string): string {
- const hash = crypto.createHash("sha256");
- hash.update(fs.readFileSync(filePath));
- return hash.digest("hex");
- }
- /**
- * Handle binary self-update (Unix only).
- * On Windows, prints reinstall instructions and exits.
- */
- async function handleBinaryUpdate(): Promise<void> {
- const platform = detectPlatform();
- console.log(chalk.dim(`Install source: binary (${platform})`));
- // Windows: self-update not supported
- if (process.platform === "win32") {
- console.log();
- console.log(chalk.red("Self-update is not supported on Windows."));
- console.log();
- console.log("To update, remove the current installation and reinstall:");
- console.log();
- console.log(chalk.yellow(' Remove-Item -Recurse -Force "$env:LOCALAPPDATA\\sudocode"'));
- console.log(chalk.yellow(" irm https://raw.githubusercontent.com/sudocode-ai/sudocode/main/scripts/install.ps1 | iex"));
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 214 on GitHub
- console.log();
- process.exit(1);
- }
- // Fetch latest release tag
- console.log(chalk.dim("Fetching latest release..."));
- let releaseTag: string;
- try {
- const response = await fetch(
- `https://api.github.com/repos/${GITHUB_REPO}/releases/latest`,
- { headers: { Accept: "application/vnd.github+json" } }
- );
- if (!response.ok) throw new Error(`GitHub API returned ${response.status}`);
- const data = (await response.json()) as { tag_name: string };
- releaseTag = data.tag_name;
- } catch (error) {
- console.log(chalk.red("Failed to fetch latest release from GitHub"));
- if (error instanceof Error) console.log(chalk.dim(error.message));
- process.exit(1);
- }
- // Download manifest
- const manifestUrl = `https://github.com/${GITHUB_REPO}/releases/download/${releaseTag}/manifest.json`;
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "sudocode-update-"));
- try {
- const manifestPath = path.join(tempDir, "manifest.json");
- console.log(chalk.dim("Downloading manifest..."));
- await downloadFile(manifestUrl, manifestPath);
- const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as {
- version: string;
- platforms: Record<string, { url: string; sha256: string; size: number }>;
- };
- const platformInfo = manifest.platforms[platform];
- if (!platformInfo) {
- console.log(chalk.red(`No binary available for platform: ${platform}`));
- console.log("Available platforms:", Object.keys(manifest.platforms).join(", "));
- process.exit(1);
- }
- // Download tarball
- const tarballPath = path.join(tempDir, "sudocode.tar.gz");
- console.log(`Downloading sudocode ${manifest.version}...`);
- await downloadFile(platformInfo.url, tarballPath);
- // Verify checksum
- console.log(chalk.dim("Verifying checksum..."));
- const computed = sha256File(tarballPath);
- if (computed !== platformInfo.sha256) {
- console.log(chalk.red("Checksum mismatch!"));
- console.log(` Expected: ${platformInfo.sha256}`);
- console.log(` Got: ${computed}`);
- process.exit(1);
- }
- console.log(chalk.dim("Checksum verified"));
- // Extract
- const extractDir = path.join(tempDir, "extract");
- fs.mkdirSync(extractDir, { recursive: true });
- await execFileAsync("tar", ["-xzf", tarballPath, "-C", extractDir]);
- // Find extracted directory
- const entries = fs.readdirSync(extractDir);
- const extracted = entries.find((e) =>
- fs.statSync(path.join(extractDir, e)).isDirectory()
- );
- if (!extracted) {
- console.log(chalk.red("Empty archive"));
- process.exit(1);
- }
- const extractedDir = path.join(extractDir, extracted);
- // Determine install directory
- const installDir = getBinaryInstallDir();
- if (!installDir) {
- console.log(chalk.red("Could not determine install directory"));
- console.log("Set SUDOCODE_INSTALL_DIR environment variable and try again");
- process.exit(1);
- }
- // Replace files
- console.log(chalk.dim(`Installing to ${installDir}...`));
- // Copy bin/ contents
- const srcBin = path.join(extractedDir, "bin");
- const destBin = path.join(installDir, "bin");
- if (fs.existsSync(srcBin)) {
- for (const file of fs.readdirSync(srcBin)) {
- const srcFile = path.join(srcBin, file);
- const destFile = path.join(destBin, file);
- // Skip symlinks (sdc) — recreate after
- const stat = fs.lstatSync(srcFile);
- if (stat.isSymbolicLink()) continue;
- // On Linux, overwriting a running executable fails with ETXTBSY.
- // Unlinking first removes the directory entry while the OS keeps the
- // old inode alive for the running process. The new copy gets a fresh inode.
- try { fs.unlinkSync(destFile); } catch { /* may not exist */ }
- fs.copyFileSync(srcFile, destFile);
- fs.chmodSync(destFile, 0o755);
- }
- // Recreate sdc symlink
- const sdcPath = path.join(destBin, "sdc");
- try { fs.unlinkSync(sdcPath); } catch { /* may not exist */ }
- fs.symlinkSync("sudocode", sdcPath);
- }
- // Copy node_modules/ (native modules like better-sqlite3)
- const srcModules = path.join(extractedDir, "node_modules");
- const destModules = path.join(installDir, "node_modules");
- if (fs.existsSync(srcModules)) {
- if (fs.existsSync(destModules)) fs.rmSync(destModules, { recursive: true });
- fs.cpSync(srcModules, destModules, { recursive: true });
- }
- // Copy public/ (frontend assets)
- const srcPublic = path.join(extractedDir, "public");
- const destPublic = path.join(installDir, "public");
- if (fs.existsSync(srcPublic)) {
- if (fs.existsSync(destPublic)) fs.rmSync(destPublic, { recursive: true });
- fs.cpSync(srcPublic, destPublic, { recursive: true });
- }
- // Copy package.json
- const srcPkg = path.join(extractedDir, "package.json");
- if (fs.existsSync(srcPkg)) {
- fs.copyFileSync(srcPkg, path.join(installDir, "package.json"));
- }
- console.log();
- console.log(chalk.green(`✓ Updated to ${manifest.version}`));
- console.log();
- console.log("Run 'sudocode --version' to verify the new version");
- // Best-effort: update Claude Code marketplace plugin
- updateClaudePlugin();
- } finally {
- // Cleanup temp dir
- try { fs.rmSync(tempDir, { recursive: true }); } catch { /* ignore */ }
- }
- }
- /**
- * Handle update check command
- */
- export async function handleUpdateCheck(): Promise<void> {
- console.log(chalk.cyan("Checking for updates..."));
- const info = await checkForUpdates();
- const source = detectInstallSource();
- if (!info) {
- console.log(chalk.yellow("Unable to check for updates"));
- console.log("Please try again later or check manually:");
- if (source === "binary") {
- console.log(" Check https://github.com/sudocode-ai/sudocode/releases");
- } else {
- const packageName = await detectInstalledPackage();
- console.log(` npm view ${packageName} version`);
- }
- return;
- }
- console.log(`Current version: ${chalk.cyan(info.current)}`);
- console.log(`Latest version: ${chalk.cyan(info.latest)}`);
- if (source === "binary") {
- console.log(`Source: ${chalk.dim(`binary (${detectPlatform()})`)}`);
- } else {
- const packageName = await detectInstalledPackage();
- console.log(`Package: ${chalk.dim(packageName)}`);
- }
- if (info.updateAvailable) {
- console.log();
- console.log(chalk.green("✓ Update available!"));
- console.log();
- console.log("To update, run:");
- console.log(chalk.yellow(` sudocode update`));
- if (source !== "binary") {
- const packageName = await detectInstalledPackage();
- console.log();
- console.log("Or manually:");
- console.log(chalk.yellow(` npm install -g ${packageName} --force`));
- }
- } else {
- console.log();
- console.log(chalk.green("✓ You are using the latest version"));
- }
- }
- /**
- * Handle update install command
- */
- export async function handleUpdate(): Promise<void> {
- console.log(chalk.cyan("Checking for updates..."));
- const source = detectInstallSource();
- // Binary install → use binary update flow
- if (source === "binary") {
- const info = await checkForUpdates();
- if (info && !info.updateAvailable) {
- console.log(chalk.green("✓ Already on latest version:"), info.current);
- return;
- }
- if (info) {
- console.log(`Updating from ${info.current} to ${info.latest}...`);
- }
- await handleBinaryUpdate();
- return;
- }
- // npm/Volta install → existing npm flow
- const info = await checkForUpdates();
- if (!info) {
- console.log(chalk.yellow("Unable to check for updates"));
- console.log("Attempting to update anyway...");
- } else if (!info.updateAvailable) {
- console.log(chalk.green("✓ Already on latest version:"), info.current);
- return;
- } else {
- console.log(`Updating from ${info.current} to ${info.latest}...`);
- }
- // Detect which package to update
- const packageToUpdate = await detectInstalledPackage();
- if (source === "volta") {
- console.log(chalk.dim("Detected Volta-managed installation"));
- } else if (packageToUpdate === "sudocode") {
- console.log(
- chalk.dim("Detected metapackage installation - updating all components")
- );
- } else {
- console.log(chalk.dim("Detected standalone CLI installation"));
- }
- try {
- installPackageWithRetry(packageToUpdate);
- console.log();
- console.log(chalk.green("✓ Update completed successfully!"));
- console.log();
- console.log("Run 'sudocode --version' to verify the new version");
- // Best-effort: update Claude Code marketplace plugin
- updateClaudePlugin();
- } catch (error) {
- console.log();
- console.error(chalk.red("✗ Update failed"));
- console.log();
- console.log("Please try updating manually:");
- console.log(chalk.yellow(` npm install -g ${packageToUpdate} --force`));
- console.log();
- if (error instanceof Error) {
- console.log("Error details:");
- console.log(chalk.dim(error.message));
- }
- process.exit(1);
- }
- }
- /**
- * Handle update dismiss command
- */
- export async function handleUpdateDismiss(): Promise<void> {
- const info = await checkForUpdates();
- if (!info) {
- console.log(chalk.yellow("Unable to check for updates"));
- return;
- }
- if (!info.updateAvailable) {
- console.log(chalk.green("✓ Already on latest version:"), info.current);
- console.log("No update notifications to dismiss");
- return;
- }
- dismissUpdate(info.latest);
- console.log(chalk.green("✓ Update notifications dismissed for 30 days"));
- console.log();
- console.log(
- `You won't be notified about version ${info.latest} for the next 30 days`
- );
- console.log("To update now, run:", chalk.cyan("sudocode update"));
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.