Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/sudocode-ai--sudocode/badge.svg)](/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

i

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)

  1. {
  2. "name": "sudocode-marketplace",
  3. "description": "Local marketplace for sudocode plugins",
  4. "owner": {
  5. "name": "sudocode AI"
  6. },
  7. "plugins": [
  8. {
  9. "name": "sudocode",
  10. "source": "./",
  11. "description": "Git-native spec and issue management for AI-assisted development",
  12. "version": "0.2.0"
  13. }
  14. ]
  15. }
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)

  1. <div align="center">
  2. <picture>
  3. <source media="(prefers-color-scheme: dark)" srcset="media/banner-otto-dusk.gif">
  4. <source media="(prefers-color-scheme: light)" srcset="media/banner-otto-day.gif">
  5. <img alt="sudocode banner" src="media/banner-otto-day.gif">
  6. </picture>
  7. </div>
  8. <h1 align="center">sudocode</h1>
  9. <div align="center">
  10. <a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
  11. <img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 22px;" />
  12. </a><a target="_blank" href="https://www.npmjs.com/package/sudocode" style="background:none">
  13. <img src="https://img.shields.io/badge/npm-sudocode-orange" style="height: 22px;" />
  14. </a><a target="_blank" href="https://docs.sudocode.ai" style="background:none">
  15. <img src="https://img.shields.io/badge/Docs-docs-green" style="height: 22px;" alt="Documentation" />
  16. </a><a target="_blank" href="https://discord.gg/5t8GUW65EW" style="background:none">
  17. <img src="https://img.shields.io/discord/1115708641052471446?logo=discord&logoColor=5865F2&label=Discord&color=5865F2" style="height: 22px;" alt="Discord" />
  18. </a>
  19. </div>
  20. <br/>
  21. <p align="center">
  22. <code>npm install -g sudocode</code>
  23. </p>
  24. <p align="center">
  25. <b>Automate the logistics of managing context and agents. Direct the work instead of babysitting agents.</b></p>
  26. 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.
  27. ### Key capabilities
  28. - Automate context handoff for complex tasks with sudocode's git-native agent memory system
  29. - Bring order to chaos by organizing your requirements, background context, and implementation plans into structured, executable issue graphs
  30. - Visualize outputs and execution feedback in real-time
  31. - Run as many Claude Code/Codex/Cursor (+more) agents in parallel as you can handle
  32. ### How it works
  33. 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.
  34. 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.
  35. ### How to use it
  36. The sudocode package includes a CLI, local server/UI, and an MCP server.
  37. 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.
  38. 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.
  39. <div style="margin: 2em 0;">
  40. <img src="media/screenshots/issue-kanban.png" alt="Issue kanban view">
  41. </div>
  42. 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.
  43. <div style="margin: 2em 0;">
  44. <img src="media/screenshots/spec-viewer.png" alt="Spec editor view">
  45. </div>
  46. 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.
  47. <div style="margin: 2em 0;">
  48. <img src="media/screenshots/workflow.png" alt="Workflow automation view">
  49. </div>
  50. If you're up for it, you can even monitor all running agent trajectories at the same time.
  51. <div style="margin: 2em 0;">
  52. <img src="media/screenshots/execution-panel.png" alt="Execution monitoring panel">
  53. </div>
  54. **sudocode** provides a structured yet flexible system for organizing the chaos of human-AI collaboration in software development.
  55. ## Quick Start
  56. ```bash
  57. # Install globally (recommended: use npx instead to avoid Node version conflicts)
  58. npm install -g sudocode
  59. # Initialize a sudocode project in your project directory.
  60. sudocode init
  61. # Run the local sudocode server from anywhere
  62. sudocode server
  63. # To connect your agent directly to sudocode, install our plugin
  64. claude plugin marketplace add sudocode-ai/sudocode
  65. claude plugin install sudocode
  66. # Note, instructions for other agents can be found in the quick start guide
  67. ```
  68. Check out our [Quick Start Guide](https://docs.sudocode.ai/quickstart#step-4%3A-set-up-your-agent) for tutorials and walkthroughs.
  69. ## External Integrations
  70. 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.
  71. **Supported Integrations:**
  72. | Integration | Description | Sync Direction |
  73. |-------------|-------------|----------------|
  74. | **[Beads](https://github.com/steveyegge/beads)** | Git-native issues system | Bidirectional |
  75. | **[Spec-Kit](https://github.com/github/spec-kit)** | Markdown-based specification system | Bidirectional |
  76. | **[OpenSpec](https://github.com/Fission-AI/OpenSpec)** | Structured spec and change proposal system | Bidirectional |
  77. | **Jira** | Atlassian issue tracking | *Coming soon* |
  78. | **Linear** | Modern issue tracking | *Coming soon* |
  79. In the sudocode UI, enable integrations in Settings > Integrations. Via the CLI, update with `sudocode plugin`.
  80. 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.
  81. 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!
  82. ## Context-as-Code
  83. 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.
  84. 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.
  85. - **Distributed Collaboration**: Human developers and AI agents share one logical database across multiple environments through git synchronization
  86. - **Lightweight**: All your context lives under your control in your repo
  87. - **Integrated Audit Trail**: Context can be recovered with git's immutable change tracking
  88. - **Agent Persistence**: Reduce agent hallucinations and amnesia by keeping task context in version-controlled files instead of ephemeral conversations
  89. Git handles distribution while AI handles merge conflicts.
  90. ## Spec-Driven Development
  91. 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.
  92. - **Structured Context**: Create connections between your specs with a rich graph structure, and organize context dynamically so it is easily discoverable by agents
  93. - **Advanced Organization**: Create structured task dependencies to keep track of blocking issues and hidden relationships between tasks
  94. - **Iterative Refinement**: Move through multiple refinement stages as agents provide bi-directional feedback as they implement on your specs
  95. Reduce the chaos of "vibe coding" by establishing clear, executable requirements in order to produce predictable outcomes.
  96. ## Context Structure
  97. sudocode implements a **4-tiered abstraction structure** for representing context, corresponding to increasing granularity from high-level requirements to low-level implementation:
  98. ### 1. Spec (Specification)
  99. A primitive for **user intent** and context—requirements, RFCs, research questions, design decisions. Specs capture **WHAT** you want.
  100. - Organized as nodes in a graph structure
  101. - Support hierarchical relationships and cross-cutting links
  102. - Stored as human-editable Markdown with YAML frontmatter
  103. - Live in `.sudocode/specs/`
  104. ### 2. Issue
  105. A primitive for **agent intent** and context—work items derived from specs, capturing tasks within agent scope.
  106. - Link back to specific requirements in specs via `[[@ISSUE-001]]` references
  107. - Support hierarchical organization, dependencies, and relationships
  108. - Graph relationship types: `blocks`, `related`, `parent-child`, `discovered-from`
  109. - Stored as Markdown + JSONL (`.sudocode/issues/`)
  110. ### 3. Agent
  111. The **execution abstraction**—represents the actual trajectory of an agentic loop run against an issue.
  112. - Tracks agent system (Claude Code, Codex, etc.) and configurations
  113. - One-to-many relationship with issues (supports multiple execution sessions per issue)
  114. - Captures sub/multi-agent structures and unique workflows
  115. - Configuration stored in `.sudocode/agents/`
  116. ### 4. Artifact
  117. A primitive representing **state changes** from agent execution.
  118. - e.g. Code diffs for coding agents, reports for research agents, documentation updates for docs agents
  119. - Multiple artifacts per execution
  120. ## Key Features
  121. ### Dual Issue/Spec Representation
  122. Every entity has both a **human-editable format** (Markdown + YAML) and a **machine-optimized format** (JSONL + SQLite):
  123. - Write specs and issues as readable Markdown
  124. - Query and process through SQLite for performance
  125. - Auto-sync between formats (5-second debounce)
  126. - Git-friendly primary storage
  127. ### Bidirectional Linking
  128. Relationships are tracked in both directions:
  129. ```markdown
  130. ## Requirements
  131. 1. Support OAuth 2.0 [[ISSUE-001]]
  132. 2. Multi-factor authentication [[ISSUE-002]]
  133. See also [[SPEC-010]] for API design patterns.
  134. ```
  135. Backlinks are automatically tracked in the relationship graph.
  136. ### Graph-Based Planning
  137. Navigate dependencies, hierarchies, and relationships:
  138. - Topological ordering for execution (no-dependency, high-priority tasks first)
  139. - Hierarchical execution with subtask handoffs
  140. - Automatic issue claiming for multi-agent concurrency
  141. ### Agent Feedback Loops
  142. Agents can update specs with findings during execution, bridging lower to higher abstraction levels to keep humans in the loop.
  143. ### IDE Integration
  144. 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.
  145. **Supported Editors:**
  146. - VS Code (`code`)
  147. - Cursor (`cursor`)
  148. - Windsurf (`windsurf`)
  149. - IntelliJ IDEA (`idea`)
  150. - Zed (`zed`)
  151. - Xcode (`xed`)
  152. - Custom command
  153. **Configuration:**
  154. Editor settings are in `.sudocode/config.json` (gitignored, created during init):
  155. ```json
  156. {
  157. "editor": {
  158. "editorType": "vs-code"
  159. }
  160. }
  161. ```
  162. **Supported Editor Types:**
  163. - `"vs-code"` - Visual Studio Code
  164. - `"cursor"` - Cursor
  165. - `"windsurf"` - Windsurf
  166. - `"intellij"` - IntelliJ IDEA
  167. - `"zed"` - Zed
  168. - `"xcode"` - Xcode
  169. - `"custom"` - Custom command (requires `customCommand` field)
  170. **Custom Editor Example:**
  171. ```json
  172. {
  173. "editor": {
  174. "editorType": "custom",
  175. "customCommand": "code-insiders"
  176. }
  177. }
  178. ```
  179. **Troubleshooting:**
  180. If the editor doesn't open:
  181. 1. Verify the editor is installed and in your PATH
  182. 2. Test the command manually: `code /path/to/directory`
  183. 3. Check the editor type in your config matches your installation
  184. 4. For macOS GUI apps, ensure the command-line tool is installed (e.g., VS Code's "Install 'code' command in PATH")
  185. ## Architecture
  186. ### Distributed Git Database
  187. - **Source of Truth**: JSONL files (`.sudocode/specs/specs.jsonl`, `.sudocode/issues/issues.jsonl`) committed to git
  188. - **Local Cache**: Each machine maintains a SQLite cache (`.sudocode/cache.db`, gitignored)
  189. - **Auto-Export**: SQLite → JSONL after CRUD operations (5-second debounce)
  190. - **Auto-Import**: JSONL → SQLite when JSONL is newer (e.g., after `git pull`)
  191. - **Conflict Resolution**: Git handles distribution, AI handles merge conflicts
  192. This design provides centralized database semantics through distributed git infrastructure.
  193. ## Development Flow
  194. ### 1. Create a Spec
  195. Define requirements, behaviors, abstractions, and design decisions:
  196. ```bash
  197. sudocode spec create auth-system
  198. # Then update created spec markdown file.
  199. ```
  200. ### 2. Create Sub-Specs (Optional)
  201. For complex specs, create hierarchical or cross-cutting relationships by creating references between specs and issues.
  202. ```markdown
  203. See [[SPEC-002]] for detailed API contracts.
  204. ```
  205. ### 3. Plan and Create Issues
  206. Invoke a planning agent to collaboratively define implementation issues.
  207. The agent:
  208. - Creates issues with `blocks`, `related`, `parent-child` relationships
  209. - Embeds issue references back into the spec: `[[@ISSUE-001]]`
  210. - Populates bidirectional links (issue → spec, spec → issue)
  211. TODO: Add a plan CLI command that hooks into the configured agent.
  212. ### 4. Execute Issues
  213. 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.
  214. - Issues with no blockers and higher priority execute first (topological order)
  215. - Agents can update specs with findings and feedback during execution
  216. - Multiple agent executions can run simultaneously
  217. ### 5. Manage Artifacts
  218. Artifacts and tracked as agents execute.
  219. - Code changes are marked for review or directly committed (user settings)
  220. - Issues are updated with artifact references for traceability
  221. ## Philosophy
  222. sudocode embraces:
  223. 1. **Context-as-Code**: Version-controlled, human-readable requirements and plans are persisted in source control
  224. 2. **Git-Native**: Everything lives in git—no external databases or services
  225. 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
  1. /**
  2. * Update command handlers
  3. */
  4. import chalk from "chalk";
  5. import { execSync } from "child_process";
  6. import { execFile } from "child_process";
  7. import { promisify } from "util";
  8. import * as fs from "fs";
  9. import * as path from "path";
  10. import * as os from "os";
  11. import * as crypto from "crypto";
  12. import { pipeline } from "stream/promises";
  13. import { createWriteStream } from "fs";
  14. import https from "https";
  15. import { checkForUpdates, dismissUpdate } from "../update-checker.js";
  16. import { detectInstallSource, detectPlatform, getBinaryInstallDir } from "../install-source.js";
  17. const execFileAsync = promisify(execFile);
  18. const GITHUB_REPO = "sudocode-ai/sudocode";
  19. /**
  20. * Detect which sudocode package is globally installed
  21. * Returns the package name to update
  22. */
  23. async function detectInstalledPackage(): Promise<string> {
  24. try {
  25. // Check if metapackage is installed
  26. execSync("npm list -g sudocode --depth=0", {
  27. stdio: "pipe",
  28. encoding: "utf8",
  29. });
  30. return "sudocode"; // Metapackage is installed
  31. } catch {
  32. // Metapackage not found, fall back to CLI
  33. return "@sudocode-ai/cli";
  34. }
  35. }
  36. /**
  37. * Install package with smart force retry
  38. * Tries without --force first, retries with --force only on EEXIST
  39. */
  40. function installPackageWithRetry(packageName: string): void {
  41. const baseCommand = `npm install -g ${packageName}`;
  42. console.log();
  43. console.log(chalk.cyan(`Running: ${baseCommand}`));
  44. console.log();
  45. try {
  46. // First attempt: without --force
  47. execSync(baseCommand, { stdio: "inherit" });
  48. } catch (error) {
  49. // Check if it's an EEXIST error
  50. if (error instanceof Error && error.message.includes("EEXIST")) {
  51. console.log();
  52. console.log(
  53. chalk.yellow("File already exists, retrying with --force...")
  54. );
  55. console.log();
  56. try {
  57. // Retry with --force
  58. const forceCommand = `${baseCommand} --force`;
  59. console.log(chalk.cyan(`Running: ${forceCommand}`));
  60. console.log();
  61. execSync(forceCommand, { stdio: "inherit" });
  62. } catch (retryError) {
  63. // If retry also fails, throw the error to be handled by caller
  64. throw retryError;
  65. }
  66. } else {
  67. // Not an EEXIST error, re-throw
  68. throw error;
  69. }
  70. }
  71. // Refresh Volta shim if sudocode is managed by Volta
  72. // This is necessary because Volta caches package locations at shell initialization
  73. if (isUsingVoltaForSudocode()) {
  74. console.log();
  75. console.log(chalk.dim("Detected Volta - refreshing package shim..."));
  76. try {
  77. execSync(`volta install ${packageName}`, { stdio: "inherit" });
  78. } catch (voltaError) {
  79. // Volta refresh failed - not critical since npm install succeeded
  80. console.log(chalk.yellow("Warning: Failed to refresh Volta shim"));
  81. console.log(chalk.dim("You may need to re-install sudocode"));
  82. }
  83. }
  84. }
  85. /**
  86. * Check if sudocode was installed via Volta
  87. *
  88. * Volta is a Node.js version manager that creates shims for globally installed packages.
  89. * When a package is installed via npm while Volta is active, the binary is placed in
  90. * Volta's managed directory (typically ~/.volta/bin or $VOLTA_HOME/bin).
  91. *
  92. * This function detects if the sudocode binary is managed by Volta by:
  93. * 1. Checking if Volta is installed on the system
  94. * 2. Getting the actual path of the sudocode executable
  95. * 3. Verifying the path is within Volta's managed directories
  96. *
  97. * Why this matters:
  98. * Volta caches the resolved paths of executables at shell initialization time.
  99. * When sudocode is updated via `npm install -g`, the files are updated but the
  100. * current shell session continues to use the old cached path until the shell
  101. * is restarted. This is Volta's intended behavior for performance.
  102. *
  103. * @returns true if sudocode binary is managed by Volta, false otherwise
  104. */
  105. function isUsingVoltaForSudocode(): boolean {
  106. try {
  107. // First check if Volta exists on the system
  108. execSync("volta --version", { stdio: "pipe" });
  109. // Get the actual path of the sudocode binary
  110. const binPath = execSync("which sudocode", {
  111. stdio: "pipe",
  112. encoding: "utf8",
  113. }).trim();
  114. // Check VOLTA_HOME environment variable if set (user may have custom location)
  115. const voltaHome = process.env.VOLTA_HOME;
  116. if (voltaHome) {
  117. return binPath.startsWith(voltaHome);
  118. }
  119. // Fall back to checking for default /.volta/ directory in path
  120. return binPath.includes("/.volta/");
  121. } catch {
  122. // Volta not installed, which command failed, or other error
  123. return false;
  124. }
  125. }
  126. /**
  127. * Best-effort update of the Claude Code marketplace plugin.
  128. * If the claude CLI is not available, prints a note and moves on.
  129. */
  130. function updateClaudePlugin(): void {
  131. try {
  132. execSync("claude --version", { stdio: "pipe" });
  133. } catch {
  134. console.log();
  135. console.log(
  136. chalk.dim("Claude CLI not found — skipping marketplace plugin update")
  137. );
  138. return;
  139. }
  140. try {
  141. console.log();
  142. console.log(chalk.dim("Updating Claude Code marketplace plugin..."));
  143. execSync("claude plugin marketplace update sudocode-ai/sudocode", {
  144. stdio: "inherit",
  145. });
  146. execSync("claude plugin update sudocode@sudocode-marketplace", {
  147. stdio: "inherit",
  148. });
  149. console.log(chalk.green("✓ Claude Code plugin updated"));
  150. } catch {
  151. // Best-effort — don't fail the overall update
  152. }
  153. }
  154. /**
  155. * Download a file from a URL, following redirects
  156. */
  157. function downloadFile(url: string, destPath: string): Promise<void> {
  158. return new Promise((resolve, reject) => {
  159. https.get(url, (res) => {
  160. if (res.statusCode === 301 || res.statusCode === 302) {
  161. downloadFile(res.headers.location!, destPath).then(resolve).catch(reject);
  162. return;
  163. }
  164. if (res.statusCode !== 200) {
  165. reject(new Error(`HTTP ${res.statusCode} for ${url}`));
  166. return;
  167. }
  168. const ws = createWriteStream(destPath);
  169. pipeline(res, ws).then(resolve).catch(reject);
  170. }).on("error", reject);
  171. });
  172. }
  173. /**
  174. * Compute SHA256 checksum of a file
  175. */
  176. function sha256File(filePath: string): string {
  177. const hash = crypto.createHash("sha256");
  178. hash.update(fs.readFileSync(filePath));
  179. return hash.digest("hex");
  180. }
  181. /**
  182. * Handle binary self-update (Unix only).
  183. * On Windows, prints reinstall instructions and exits.
  184. */
  185. async function handleBinaryUpdate(): Promise<void> {
  186. const platform = detectPlatform();
  187. console.log(chalk.dim(`Install source: binary (${platform})`));
  188. // Windows: self-update not supported
  189. if (process.platform === "win32") {
  190. console.log();
  191. console.log(chalk.red("Self-update is not supported on Windows."));
  192. console.log();
  193. console.log("To update, remove the current installation and reinstall:");
  194. console.log();
  195. console.log(chalk.yellow(' Remove-Item -Recurse -Force "$env:LOCALAPPDATA\\sudocode"'));
  196. console.log(chalk.yellow(" irm https://raw.githubusercontent.com/sudocode-ai/sudocode/main/scripts/install.ps1 | iex"));
  197. console.log();
  198. process.exit(1);
  199. }
  200. // Fetch latest release tag
  201. console.log(chalk.dim("Fetching latest release..."));
  202. let releaseTag: string;
  203. try {
  204. const response = await fetch(
  205. `https://api.github.com/repos/${GITHUB_REPO}/releases/latest`,
  206. { headers: { Accept: "application/vnd.github+json" } }
  207. );
  208. if (!response.ok) throw new Error(`GitHub API returned ${response.status}`);
  209. const data = (await response.json()) as { tag_name: string };
  210. releaseTag = data.tag_name;
  211. } catch (error) {
  212. console.log(chalk.red("Failed to fetch latest release from GitHub"));
  213. if (error instanceof Error) console.log(chalk.dim(error.message));
  214. process.exit(1);
  215. }
  216. // Download manifest
  217. const manifestUrl = `https://github.com/${GITHUB_REPO}/releases/download/${releaseTag}/manifest.json`;
  218. const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "sudocode-update-"));
  219. try {
  220. const manifestPath = path.join(tempDir, "manifest.json");
  221. console.log(chalk.dim("Downloading manifest..."));
  222. await downloadFile(manifestUrl, manifestPath);
  223. const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as {
  224. version: string;
  225. platforms: Record<string, { url: string; sha256: string; size: number }>;
  226. };
  227. const platformInfo = manifest.platforms[platform];
  228. if (!platformInfo) {
  229. console.log(chalk.red(`No binary available for platform: ${platform}`));
  230. console.log("Available platforms:", Object.keys(manifest.platforms).join(", "));
  231. process.exit(1);
  232. }
  233. // Download tarball
  234. const tarballPath = path.join(tempDir, "sudocode.tar.gz");
  235. console.log(`Downloading sudocode ${manifest.version}...`);
  236. await downloadFile(platformInfo.url, tarballPath);
  237. // Verify checksum
  238. console.log(chalk.dim("Verifying checksum..."));
  239. const computed = sha256File(tarballPath);
  240. if (computed !== platformInfo.sha256) {
  241. console.log(chalk.red("Checksum mismatch!"));
  242. console.log(` Expected: ${platformInfo.sha256}`);
  243. console.log(` Got: ${computed}`);
  244. process.exit(1);
  245. }
  246. console.log(chalk.dim("Checksum verified"));
  247. // Extract
  248. const extractDir = path.join(tempDir, "extract");
  249. fs.mkdirSync(extractDir, { recursive: true });
  250. await execFileAsync("tar", ["-xzf", tarballPath, "-C", extractDir]);
  251. // Find extracted directory
  252. const entries = fs.readdirSync(extractDir);
  253. const extracted = entries.find((e) =>
  254. fs.statSync(path.join(extractDir, e)).isDirectory()
  255. );
  256. if (!extracted) {
  257. console.log(chalk.red("Empty archive"));
  258. process.exit(1);
  259. }
  260. const extractedDir = path.join(extractDir, extracted);
  261. // Determine install directory
  262. const installDir = getBinaryInstallDir();
  263. if (!installDir) {
  264. console.log(chalk.red("Could not determine install directory"));
  265. console.log("Set SUDOCODE_INSTALL_DIR environment variable and try again");
  266. process.exit(1);
  267. }
  268. // Replace files
  269. console.log(chalk.dim(`Installing to ${installDir}...`));
  270. // Copy bin/ contents
  271. const srcBin = path.join(extractedDir, "bin");
  272. const destBin = path.join(installDir, "bin");
  273. if (fs.existsSync(srcBin)) {
  274. for (const file of fs.readdirSync(srcBin)) {
  275. const srcFile = path.join(srcBin, file);
  276. const destFile = path.join(destBin, file);
  277. // Skip symlinks (sdc) — recreate after
  278. const stat = fs.lstatSync(srcFile);
  279. if (stat.isSymbolicLink()) continue;
  280. // On Linux, overwriting a running executable fails with ETXTBSY.
  281. // Unlinking first removes the directory entry while the OS keeps the
  282. // old inode alive for the running process. The new copy gets a fresh inode.
  283. try { fs.unlinkSync(destFile); } catch { /* may not exist */ }
  284. fs.copyFileSync(srcFile, destFile);
  285. fs.chmodSync(destFile, 0o755);
  286. }
  287. // Recreate sdc symlink
  288. const sdcPath = path.join(destBin, "sdc");
  289. try { fs.unlinkSync(sdcPath); } catch { /* may not exist */ }
  290. fs.symlinkSync("sudocode", sdcPath);
  291. }
  292. // Copy node_modules/ (native modules like better-sqlite3)
  293. const srcModules = path.join(extractedDir, "node_modules");
  294. const destModules = path.join(installDir, "node_modules");
  295. if (fs.existsSync(srcModules)) {
  296. if (fs.existsSync(destModules)) fs.rmSync(destModules, { recursive: true });
  297. fs.cpSync(srcModules, destModules, { recursive: true });
  298. }
  299. // Copy public/ (frontend assets)
  300. const srcPublic = path.join(extractedDir, "public");
  301. const destPublic = path.join(installDir, "public");
  302. if (fs.existsSync(srcPublic)) {
  303. if (fs.existsSync(destPublic)) fs.rmSync(destPublic, { recursive: true });
  304. fs.cpSync(srcPublic, destPublic, { recursive: true });
  305. }
  306. // Copy package.json
  307. const srcPkg = path.join(extractedDir, "package.json");
  308. if (fs.existsSync(srcPkg)) {
  309. fs.copyFileSync(srcPkg, path.join(installDir, "package.json"));
  310. }
  311. console.log();
  312. console.log(chalk.green(`✓ Updated to ${manifest.version}`));
  313. console.log();
  314. console.log("Run 'sudocode --version' to verify the new version");
  315. // Best-effort: update Claude Code marketplace plugin
  316. updateClaudePlugin();
  317. } finally {
  318. // Cleanup temp dir
  319. try { fs.rmSync(tempDir, { recursive: true }); } catch { /* ignore */ }
  320. }
  321. }
  322. /**
  323. * Handle update check command
  324. */
  325. export async function handleUpdateCheck(): Promise<void> {
  326. console.log(chalk.cyan("Checking for updates..."));
  327. const info = await checkForUpdates();
  328. const source = detectInstallSource();
  329. if (!info) {
  330. console.log(chalk.yellow("Unable to check for updates"));
  331. console.log("Please try again later or check manually:");
  332. if (source === "binary") {
  333. console.log(" Check https://github.com/sudocode-ai/sudocode/releases");
  334. } else {
  335. const packageName = await detectInstalledPackage();
  336. console.log(` npm view ${packageName} version`);
  337. }
  338. return;
  339. }
  340. console.log(`Current version: ${chalk.cyan(info.current)}`);
  341. console.log(`Latest version: ${chalk.cyan(info.latest)}`);
  342. if (source === "binary") {
  343. console.log(`Source: ${chalk.dim(`binary (${detectPlatform()})`)}`);
  344. } else {
  345. const packageName = await detectInstalledPackage();
  346. console.log(`Package: ${chalk.dim(packageName)}`);
  347. }
  348. if (info.updateAvailable) {
  349. console.log();
  350. console.log(chalk.green("✓ Update available!"));
  351. console.log();
  352. console.log("To update, run:");
  353. console.log(chalk.yellow(` sudocode update`));
  354. if (source !== "binary") {
  355. const packageName = await detectInstalledPackage();
  356. console.log();
  357. console.log("Or manually:");
  358. console.log(chalk.yellow(` npm install -g ${packageName} --force`));
  359. }
  360. } else {
  361. console.log();
  362. console.log(chalk.green("✓ You are using the latest version"));
  363. }
  364. }
  365. /**
  366. * Handle update install command
  367. */
  368. export async function handleUpdate(): Promise<void> {
  369. console.log(chalk.cyan("Checking for updates..."));
  370. const source = detectInstallSource();
  371. // Binary install → use binary update flow
  372. if (source === "binary") {
  373. const info = await checkForUpdates();
  374. if (info && !info.updateAvailable) {
  375. console.log(chalk.green("✓ Already on latest version:"), info.current);
  376. return;
  377. }
  378. if (info) {
  379. console.log(`Updating from ${info.current} to ${info.latest}...`);
  380. }
  381. await handleBinaryUpdate();
  382. return;
  383. }
  384. // npm/Volta install → existing npm flow
  385. const info = await checkForUpdates();
  386. if (!info) {
  387. console.log(chalk.yellow("Unable to check for updates"));
  388. console.log("Attempting to update anyway...");
  389. } else if (!info.updateAvailable) {
  390. console.log(chalk.green("✓ Already on latest version:"), info.current);
  391. return;
  392. } else {
  393. console.log(`Updating from ${info.current} to ${info.latest}...`);
  394. }
  395. // Detect which package to update
  396. const packageToUpdate = await detectInstalledPackage();
  397. if (source === "volta") {
  398. console.log(chalk.dim("Detected Volta-managed installation"));
  399. } else if (packageToUpdate === "sudocode") {
  400. console.log(
  401. chalk.dim("Detected metapackage installation - updating all components")
  402. );
  403. } else {
  404. console.log(chalk.dim("Detected standalone CLI installation"));
  405. }
  406. try {
  407. installPackageWithRetry(packageToUpdate);
  408. console.log();
  409. console.log(chalk.green("✓ Update completed successfully!"));
  410. console.log();
  411. console.log("Run 'sudocode --version' to verify the new version");
  412. // Best-effort: update Claude Code marketplace plugin
  413. updateClaudePlugin();
  414. } catch (error) {
  415. console.log();
  416. console.error(chalk.red("✗ Update failed"));
  417. console.log();
  418. console.log("Please try updating manually:");
  419. console.log(chalk.yellow(` npm install -g ${packageToUpdate} --force`));
  420. console.log();
  421. if (error instanceof Error) {
  422. console.log("Error details:");
  423. console.log(chalk.dim(error.message));
  424. }
  425. process.exit(1);
  426. }
  427. }
  428. /**
  429. * Handle update dismiss command
  430. */
  431. export async function handleUpdateDismiss(): Promise<void> {
  432. const info = await checkForUpdates();
  433. if (!info) {
  434. console.log(chalk.yellow("Unable to check for updates"));
  435. return;
  436. }
  437. if (!info.updateAvailable) {
  438. console.log(chalk.green("✓ Already on latest version:"), info.current);
  439. console.log("No update notifications to dismiss");
  440. return;
  441. }
  442. dismissUpdate(info.latest);
  443. console.log(chalk.green("✓ Update notifications dismissed for 30 days"));
  444. console.log();
  445. console.log(
  446. `You won't be notified about version ${info.latest} for the next 30 days`
  447. );
  448. console.log("To update now, run:", chalk.cyan("sudocode update"));
  449. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.