mirror of
https://github.com/hanzoai/dev.git
synced 2026-10-25 03:32:32 +00:00
Merge origin/main: adopt remote workflow changes; keep release changes [skip ci]
This commit is contained in:
@@ -693,6 +693,30 @@ jobs:
|
||||
--skip-git-repo-check \
|
||||
- | tee .github/auto/AGENT_STDOUT.txt
|
||||
|
||||
- name: Assert agent success (fail on streaming/errors)
|
||||
if: steps.check_upstream.outputs.skip != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "Checking agent output for fatal errors..."
|
||||
if rg -n "^\\[.*\\] ERROR: (stream error|server error|exceeded retry limit)" .github/auto/AGENT_STDOUT.txt >/dev/null 2>&1; then
|
||||
echo "Agent reported a fatal error (stream/server). Failing job." >&2
|
||||
rg -n "^\\[.*\\] ERROR: (stream error|server error|exceeded retry limit)" .github/auto/AGENT_STDOUT.txt || true
|
||||
exit 1
|
||||
fi
|
||||
# Also flag 5xx responses from the proxy logs if present
|
||||
if [ -s .github/auto/openai-proxy.log ]; then
|
||||
if rg -n '"phase":"response_head".*"status":5\\d\\d' .github/auto/openai-proxy.log >/dev/null 2>&1; then
|
||||
echo "Proxy observed 5xx from upstream during agent run. Failing job." >&2
|
||||
rg -n '"phase":"response_head".*"status":5\\d\\d' .github/auto/openai-proxy.log | tail -n 5 || true
|
||||
exit 1
|
||||
fi
|
||||
if rg -n '"phase":"upstream_error"' .github/auto/openai-proxy.log >/dev/null 2>&1; then
|
||||
echo "Proxy upstream_error entries found. Failing job." >&2
|
||||
rg -n '"phase":"upstream_error"' .github/auto/openai-proxy.log | tail -n 10 || true
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Upload artifact - openai-proxy.log
|
||||
if: steps.check_upstream.outputs.skip != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
# JustEvery_ Code
|
||||
|
||||
 
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/logo.png" alt="Code Logo" width="400">
|
||||
</p>
|
||||
|
||||
 
|
||||
|
||||
**Code** is a fast, local coding agent for your terminal. It's a community-driven fork of `openai/codex` focused on real developer ergonomics: Browser integration, multi-agents, theming, and reasoning control — all while staying compatible with upstream.
|
||||
|
||||
 
|
||||
## Why Code
|
||||
|
||||
- 🌐 **Browser Integration** - CDP support, headless browsing, screenshots
|
||||
- 📝 **Diff Viewer** - Side-by-side diffs with syntax highlighting
|
||||
- 🤖 **Multi-Agent Commands** - /plan, /solve, /code with agent panels
|
||||
- 🎨 **Theme System** - /themes with live preview and accessibility
|
||||
- 🧠 **Reasoning Control** - /reasoning for dynamic effort adjustment
|
||||
- 🔌 **MCP support** – Extend with filesystem, DBs, APIs, or your own tools.
|
||||
- 🔒 **Safety modes** – Read-only, approvals, and workspace sandboxing.
|
||||
- 🔁 **Backwards compatible** – Supports `~/.codex/*` or default `~/.coder/*`
|
||||
|
||||
 
|
||||
| <img src="docs/screenshots/simple.png" alt="Simple interface" width="100%"><br>Simple interface | <img src="docs/screenshots/diff.png" alt="Unified diff viewer" width="100%"><br>Unified diffs |
|
||||
|:--:|:--:|
|
||||
|
||||
| <br><img src="docs/screenshots/browser.png" alt="Browser control" width="100%"><br>Browser control | <br><img src="docs/screenshots/agents.png" alt="Assist with Claude & Gemini" width="100%"><br>Assist with Claude & Gemini |
|
||||
|:--:|:--:|
|
||||
|
||||
|
||||
 
|
||||
## Quickstart
|
||||
|
||||
### Run
|
||||
|
||||
```bash
|
||||
npx -y @just-every/code
|
||||
```
|
||||
|
||||
### Install & Run
|
||||
|
||||
```bash
|
||||
npm install -g @just-every/code
|
||||
code // or `coder` if you're using VS Code
|
||||
```
|
||||
|
||||
Note: If another tool already provides a `code` command (e.g. VS Code), our CLI is also installed as `coder`. Use `coder` to avoid conflicts.
|
||||
|
||||
**Authenticate** (one of the following):
|
||||
- **Sign in with ChatGPT** (Plus/Pro/Team; uses models available to your plan)
|
||||
- Run `code` and pick "Sign in with ChatGPT"
|
||||
- Stores creds locally at `~/.coder/auth.json` (also reads legacy `~/.codex/auth.json`)
|
||||
- **API key** (usage-based)
|
||||
- Set `export OPENAI_API_KEY=xyz` and run `code`
|
||||
|
||||
### Install Claude & Gemini (optional)
|
||||
|
||||
Code supports orchestrating other AI CLI tools. Install these and config to use alongside Code.
|
||||
|
||||
```bash
|
||||
|
||||
npm install -g @anthropic-ai/claude-code @google/gemini-cli && claude "Just checking you're working! Let me know how I can exit." && gemini -i "Just checking you're working! Let me know how I can exit."
|
||||
```
|
||||
|
||||
 
|
||||
## Commands
|
||||
|
||||
### Browser
|
||||
```bash
|
||||
# Connect code to external Chrome browser (running CDP)
|
||||
/chrome # Connect with auto-detect port
|
||||
/chrome 9222 # Connect to specific port
|
||||
|
||||
# Switch to internal browser mode
|
||||
/browser # Use internal headless browser
|
||||
/browser https://example.com # Open URL in internal browser
|
||||
```
|
||||
|
||||
### Agents
|
||||
```bash
|
||||
# Plan code changes (Claude, Gemini and GPT-5 consensus)
|
||||
# All agents review task and create a consolidated plan
|
||||
/plan "Stop the AI from ordering pizza at 3AM"
|
||||
|
||||
# Solve complex problems (Claude, Gemini and GPT-5 race)
|
||||
# Fastest preferred (see https://arxiv.org/abs/2505.17813)
|
||||
/solve "Why does deleting one user drop the whole database?"
|
||||
|
||||
# Write code! (Claude, Gemini and GPT-5 consensus)
|
||||
# Creates multiple worktrees then implements the optimal solution
|
||||
/code "Show dark mode when I feel cranky"
|
||||
```
|
||||
|
||||
### General
|
||||
```bash
|
||||
# Try a new theme!
|
||||
/themes
|
||||
|
||||
# Change reasoning level
|
||||
/reasoning low|medium|high
|
||||
|
||||
# Start new conversation
|
||||
/new
|
||||
```
|
||||
|
||||
## CLI reference
|
||||
|
||||
```shell
|
||||
code [options] [prompt]
|
||||
|
||||
Options:
|
||||
--model <name> Override the model (gpt-5, claude-opus, etc.)
|
||||
--read-only Prevent file modifications
|
||||
--no-approval Skip approval prompts (use with caution)
|
||||
--config <key=val> Override config values
|
||||
--oss Use local open source models
|
||||
--sandbox <mode> Set sandbox level (read-only, workspace-write, etc.)
|
||||
--help Show help information
|
||||
--debug Log API requests and responses to file
|
||||
--version Show version number
|
||||
```
|
||||
|
||||
 
|
||||
## Memory & project docs
|
||||
|
||||
Code can remember context across sessions:
|
||||
|
||||
1. **Create an `AGENTS.md` or `CLAUDE.md` file** in your project root:
|
||||
```markdown
|
||||
# Project Context
|
||||
This is a React TypeScript application with:
|
||||
- Authentication via JWT
|
||||
- PostgreSQL database
|
||||
- Express.js backend
|
||||
|
||||
## Key files:
|
||||
- `/src/auth/` - Authentication logic
|
||||
- `/src/api/` - API client code
|
||||
- `/server/` - Backend services
|
||||
```
|
||||
|
||||
2. **Session memory**: Code maintains conversation history
|
||||
3. **Codebase analysis**: Automatically understands project structure
|
||||
|
||||
 
|
||||
## Non-interactive / CI mode
|
||||
|
||||
For automation and CI/CD:
|
||||
|
||||
```shell
|
||||
# Run a specific task
|
||||
code --no-approval "run tests and fix any failures"
|
||||
|
||||
# Generate reports
|
||||
code --read-only "analyze code quality and generate report"
|
||||
|
||||
# Batch processing
|
||||
code --config output_format=json "list all TODO comments"
|
||||
```
|
||||
|
||||
 
|
||||
## Model Context Protocol (MCP)
|
||||
|
||||
Code supports MCP for extended capabilities:
|
||||
|
||||
- **File operations**: Advanced file system access
|
||||
- **Database connections**: Query and modify databases
|
||||
- **API integrations**: Connect to external services
|
||||
- **Custom tools**: Build your own extensions
|
||||
|
||||
Configure MCP in `~/.codex/config.toml`:
|
||||
|
||||
```toml
|
||||
[[mcp_servers]]
|
||||
name = "filesystem"
|
||||
command = "npx"
|
||||
args = ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
|
||||
```
|
||||
|
||||
 
|
||||
## Configuration
|
||||
|
||||
Main config file: `~/.codex/config.toml`
|
||||
|
||||
```toml
|
||||
# Model settings
|
||||
model = "gpt-5"
|
||||
model_provider = "openai"
|
||||
|
||||
# Behavior
|
||||
approval_policy = "on_request" # untrusted | on-failure | on-request | never
|
||||
model_reasoning_effort = "medium" # low | medium | high
|
||||
sandbox_mode = "workspace_write"
|
||||
|
||||
# UI preferences see THEME_CONFIG.md
|
||||
[tui.theme]
|
||||
name = "light-photon"
|
||||
|
||||
# Add config for specific models
|
||||
[profiles.gpt-5]
|
||||
model = "gpt-5"
|
||||
model_provider = "openai"
|
||||
approval_policy = "never"
|
||||
model_reasoning_effort = "high"
|
||||
model_reasoning_summary = "detailed"
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
- `CODEX_HOME`: Override config directory location
|
||||
- `OPENAI_API_KEY`: Use API key instead of ChatGPT auth
|
||||
- `OPENAI_BASE_URL`: Use alternative API endpoints
|
||||
|
||||
 
|
||||
## FAQ
|
||||
|
||||
**How is this different from the original?**
|
||||
> This fork adds browser integration, multi-agent commands (`/plan`, `/solve`, `/code`), theme system, and enhanced reasoning controls while maintaining full compatibility.
|
||||
|
||||
**Can I use my existing Codex configuration?**
|
||||
> Yes! This fork is fully backward compatible with existing `~/.codex/` configurations.
|
||||
|
||||
**Does this work with ChatGPT Plus?**
|
||||
> Absolutely. Use the same "Sign in with ChatGPT" flow as the original.
|
||||
|
||||
**Is my data secure?**
|
||||
> Yes. Authentication stays on your machine, and we don't proxy your credentials or conversations.
|
||||
|
||||
 
|
||||
## Contributing
|
||||
|
||||
We welcome contributions! This fork maintains compatibility with upstream while adding community-requested features.
|
||||
|
||||
### Development workflow
|
||||
|
||||
```bash
|
||||
# Clone and setup
|
||||
git clone https://github.com/just-every/code.git
|
||||
cd code
|
||||
npm install
|
||||
|
||||
# Build (use fast build for development)
|
||||
./build-fast.sh
|
||||
|
||||
# Run locally
|
||||
./codex-rs/target/dev-fast/code
|
||||
```
|
||||
|
||||
### Opening a pull request
|
||||
|
||||
1. Fork the repository
|
||||
2. Create a feature branch: `git checkout -b feature/amazing-feature`
|
||||
3. Make your changes
|
||||
4. Run tests: `cargo test`
|
||||
5. Build successfully: `./build-fast.sh`
|
||||
6. Submit a pull request
|
||||
|
||||
|
||||
 
|
||||
## Legal & Use
|
||||
|
||||
### License & attribution
|
||||
- This project is a community fork of `openai/codex` under **Apache-2.0**. We preserve upstream LICENSE and NOTICE files.
|
||||
- **Code** is **not** affiliated with, sponsored by, or endorsed by OpenAI.
|
||||
|
||||
### Your responsibilities
|
||||
Using OpenAI, Anthropic or Google services through Code means you agree to **their Terms and policies**. In particular:
|
||||
- **Don't** programmatically scrape/extract content outside intended flows.
|
||||
- **Don't** bypass or interfere with rate limits, quotas, or safety mitigations.
|
||||
- Use your **own** account; don't share or rotate accounts to evade limits.
|
||||
- If you configure other model providers, you're responsible for their terms.
|
||||
|
||||
### Privacy
|
||||
- Your auth file lives at `~/.codex/auth.json`.
|
||||
- Inputs/outputs you send to AI providers are handled under their Terms and Privacy Policy; consult those documents (and any org-level data-sharing settings).
|
||||
|
||||
### Subject to change
|
||||
AI providers can change eligibility, limits, models, or authentication flows. Code supports **both** ChatGPT sign-in and API-key modes so you can pick what fits (local/hobby vs CI/automation).
|
||||
|
||||
 
|
||||
## License
|
||||
|
||||
Apache 2.0 - See [LICENSE](LICENSE) file for details.
|
||||
|
||||
This project is a community fork of the original Codex CLI. We maintain compatibility while adding enhanced features requested by the developer community.
|
||||
|
||||
 
|
||||
---
|
||||
**Need help?** Open an issue on [GitHub](https://github.com/just-every/code/issues) or check our documentation.
|
||||
Executable
+452
@@ -0,0 +1,452 @@
|
||||
#!/usr/bin/env node
|
||||
// Unified entry point for the Code CLI (fork of OpenAI Codex).
|
||||
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { platform as nodePlatform, arch as nodeArch } from "os";
|
||||
import { execSync } from "child_process";
|
||||
import { get as httpsGet } from "https";
|
||||
|
||||
// __dirname equivalent in ESM
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const { platform, arch } = process;
|
||||
|
||||
// Important: Never delegate to another system's `code` binary (e.g., VS Code).
|
||||
// When users run via `npx @just-every/code`, we must always execute our
|
||||
// packaged native binary by absolute path to avoid PATH collisions.
|
||||
|
||||
const isWSL = () => {
|
||||
if (platform !== "linux") return false;
|
||||
try {
|
||||
const txt = readFileSync("/proc/version", "utf8").toLowerCase();
|
||||
return txt.includes("microsoft");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let targetTriple = null;
|
||||
switch (platform) {
|
||||
case "linux":
|
||||
case "android":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-unknown-linux-musl";
|
||||
break;
|
||||
case "arm64":
|
||||
targetTriple = "aarch64-unknown-linux-musl";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "darwin":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-apple-darwin";
|
||||
break;
|
||||
case "arm64":
|
||||
targetTriple = "aarch64-apple-darwin";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "win32":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-pc-windows-msvc.exe";
|
||||
break;
|
||||
case "arm64":
|
||||
// We do not build this today, fall through...
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (!targetTriple) {
|
||||
throw new Error(`Unsupported platform: ${platform} (${arch})`);
|
||||
}
|
||||
|
||||
// Prefer new 'code-*' binary names; fall back to legacy 'coder-*' if missing.
|
||||
let binaryPath = path.join(__dirname, "..", "bin", `code-${targetTriple}`);
|
||||
let legacyBinaryPath = path.join(__dirname, "..", "bin", `coder-${targetTriple}`);
|
||||
|
||||
// --- Bootstrap helper (runs if the binary is missing, e.g. Bun blocked postinstall) ---
|
||||
import { existsSync, chmodSync, statSync, openSync, readSync, closeSync, mkdirSync, copyFileSync, readFileSync, unlinkSync, createWriteStream } from "fs";
|
||||
|
||||
const validateBinary = (p) => {
|
||||
try {
|
||||
const st = statSync(p);
|
||||
if (!st.isFile() || st.size === 0) {
|
||||
return { ok: false, reason: "empty or not a regular file" };
|
||||
}
|
||||
const fd = openSync(p, "r");
|
||||
try {
|
||||
const buf = Buffer.alloc(4);
|
||||
const n = readSync(fd, buf, 0, 4, 0);
|
||||
if (n < 2) return { ok: false, reason: "too short" };
|
||||
if (platform === "win32") {
|
||||
if (!(buf[0] === 0x4d && buf[1] === 0x5a)) return { ok: false, reason: "invalid PE header (missing MZ)" };
|
||||
} else if (platform === "linux" || platform === "android") {
|
||||
if (!(buf[0] === 0x7f && buf[1] === 0x45 && buf[2] === 0x4c && buf[3] === 0x46)) return { ok: false, reason: "invalid ELF header" };
|
||||
} else if (platform === "darwin") {
|
||||
const isMachO = (buf[0] === 0xcf && buf[1] === 0xfa && buf[2] === 0xed && buf[3] === 0xfe) ||
|
||||
(buf[0] === 0xca && buf[1] === 0xfe && buf[2] === 0xba && buf[3] === 0xbe);
|
||||
if (!isMachO) return { ok: false, reason: "invalid Mach-O header" };
|
||||
}
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, reason: e.message };
|
||||
}
|
||||
};
|
||||
|
||||
const getCacheDir = (version) => {
|
||||
const plt = nodePlatform();
|
||||
const home = process.env.HOME || process.env.USERPROFILE || "";
|
||||
let base = "";
|
||||
if (plt === "win32") {
|
||||
base = process.env.LOCALAPPDATA || path.join(home, "AppData", "Local");
|
||||
} else if (plt === "darwin") {
|
||||
base = path.join(home, "Library", "Caches");
|
||||
} else {
|
||||
base = process.env.XDG_CACHE_HOME || path.join(home, ".cache");
|
||||
}
|
||||
const dir = path.join(base, "just-every", "code", version);
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
};
|
||||
|
||||
const getCachedBinaryPath = (version) => {
|
||||
// targetTriple already includes the proper extension on Windows ("...msvc.exe").
|
||||
// Do not append another suffix; just use the exact targetTriple-derived name.
|
||||
const cacheDir = getCacheDir(version);
|
||||
return path.join(cacheDir, `code-${targetTriple}`);
|
||||
};
|
||||
|
||||
let lastBootstrapError = null;
|
||||
|
||||
const httpsDownload = (url, dest) => new Promise((resolve, reject) => {
|
||||
const req = httpsGet(url, (res) => {
|
||||
const status = res.statusCode || 0;
|
||||
if (status >= 300 && status < 400 && res.headers.location) {
|
||||
// follow one redirect recursively
|
||||
return resolve(httpsDownload(res.headers.location, dest));
|
||||
}
|
||||
if (status !== 200) {
|
||||
return reject(new Error(`HTTP ${status}`));
|
||||
}
|
||||
const out = createWriteStream(dest);
|
||||
res.pipe(out);
|
||||
out.on("finish", () => out.close(resolve));
|
||||
out.on("error", (e) => {
|
||||
try { unlinkSync(dest); } catch {}
|
||||
reject(e);
|
||||
});
|
||||
});
|
||||
req.on("error", (e) => {
|
||||
try { unlinkSync(dest); } catch {}
|
||||
reject(e);
|
||||
});
|
||||
req.setTimeout(120000, () => {
|
||||
req.destroy(new Error("download timed out"));
|
||||
});
|
||||
});
|
||||
|
||||
const tryBootstrapBinary = async () => {
|
||||
try {
|
||||
// 1) Read our published version
|
||||
const pkg = JSON.parse(readFileSync(path.join(__dirname, "..", "package.json"), "utf8"));
|
||||
const version = pkg.version;
|
||||
|
||||
const binDir = path.join(__dirname, "..", "bin");
|
||||
if (!existsSync(binDir)) mkdirSync(binDir, { recursive: true });
|
||||
|
||||
// 2) Fast path: user cache
|
||||
const cachePath = getCachedBinaryPath(version);
|
||||
if (existsSync(cachePath)) {
|
||||
const v = validateBinary(cachePath);
|
||||
if (v.ok) {
|
||||
// Prefer running directly from cache; mirror into node_modules on Unix
|
||||
if (platform !== "win32") {
|
||||
copyFileSync(cachePath, binaryPath);
|
||||
try { chmodSync(binaryPath, 0o755); } catch {}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 3) Try platform package (if present)
|
||||
try {
|
||||
const req = (await import("module")).createRequire(import.meta.url);
|
||||
const name = (() => {
|
||||
if (platform === "win32") return "@just-every/code-win32-x64"; // may be unpublished; falls through
|
||||
const plt = nodePlatform();
|
||||
const cpu = nodeArch();
|
||||
if (plt === "darwin" && cpu === "arm64") return "@just-every/code-darwin-arm64";
|
||||
if (plt === "darwin" && cpu === "x64") return "@just-every/code-darwin-x64";
|
||||
if (plt === "linux" && cpu === "x64") return "@just-every/code-linux-x64-musl";
|
||||
if (plt === "linux" && cpu === "arm64") return "@just-every/code-linux-arm64-musl";
|
||||
return null;
|
||||
})();
|
||||
if (name) {
|
||||
try {
|
||||
const pkgJson = req.resolve(`${name}/package.json`);
|
||||
const pkgDir = path.dirname(pkgJson);
|
||||
const src = path.join(pkgDir, "bin", `code-${targetTriple}`);
|
||||
if (existsSync(src)) {
|
||||
// Always ensure cache has the binary; on Unix mirror into node_modules
|
||||
copyFileSync(src, cachePath);
|
||||
if (platform !== "win32") {
|
||||
copyFileSync(cachePath, binaryPath);
|
||||
try { chmodSync(binaryPath, 0o755); } catch {}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} catch { /* ignore and fall back */ }
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
|
||||
// 4) Download from GitHub release
|
||||
const isWin = platform === "win32";
|
||||
const archiveName = isWin
|
||||
? `code-${targetTriple}.zip`
|
||||
: (() => { try { execSync("zstd --version", { stdio: "ignore", shell: true }); return `code-${targetTriple}.zst`; } catch { return `code-${targetTriple}.tar.gz`; } })();
|
||||
const url = `https://github.com/just-every/code/releases/download/v${version}/${archiveName}`;
|
||||
const tmp = path.join(binDir, `.${archiveName}.part`);
|
||||
return httpsDownload(url, tmp)
|
||||
.then(() => {
|
||||
if (isWin) {
|
||||
// Extract zip with robust fallbacks and use a safe temp dir, then move to cache
|
||||
try {
|
||||
const sysRoot = process.env.SystemRoot || process.env.windir || 'C:\\\Windows';
|
||||
const psFull = path.join(sysRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
||||
const unzipDest = getCacheDir(version); // extract directly to cache location
|
||||
const psCmd = `Expand-Archive -Path '${tmp}' -DestinationPath '${unzipDest}' -Force`;
|
||||
let ok = false;
|
||||
try { execSync(`"${psFull}" -NoProfile -NonInteractive -Command "${psCmd}"`, { stdio: 'ignore' }); ok = true; } catch {}
|
||||
if (!ok) { try { execSync(`powershell -NoProfile -NonInteractive -Command "${psCmd}"`, { stdio: 'ignore' }); ok = true; } catch {} }
|
||||
if (!ok) { try { execSync(`pwsh -NoProfile -NonInteractive -Command "${psCmd}"`, { stdio: 'ignore' }); ok = true; } catch {} }
|
||||
if (!ok) { execSync(`tar -xf "${tmp}" -C "${unzipDest}"`, { stdio: 'ignore', shell: true }); }
|
||||
} catch (e) {
|
||||
throw new Error(`failed to unzip: ${e.message}`);
|
||||
} finally { try { unlinkSync(tmp); } catch {} }
|
||||
} else {
|
||||
if (archiveName.endsWith(".zst")) {
|
||||
try { execSync(`zstd -d '${tmp}' -o '${binaryPath}'`, { stdio: 'ignore', shell: true }); }
|
||||
catch (e) { try { unlinkSync(tmp); } catch {}; throw new Error(`failed to decompress zst: ${e.message}`); }
|
||||
try { unlinkSync(tmp); } catch {}
|
||||
} else {
|
||||
try { execSync(`tar -xzf '${tmp}' -C '${binDir}'`, { stdio: 'ignore', shell: true }); }
|
||||
catch (e) { try { unlinkSync(tmp); } catch {}; throw new Error(`failed to extract tar.gz: ${e.message}`); }
|
||||
try { unlinkSync(tmp); } catch {}
|
||||
}
|
||||
}
|
||||
// On Windows, the file was extracted directly into the cache dir
|
||||
if (platform === "win32") {
|
||||
// Ensure the expected filename exists in cache; Expand-Archive extracts exact name
|
||||
// No action required here; validation occurs below against cachePath
|
||||
} else {
|
||||
try { copyFileSync(binaryPath, cachePath); } catch {}
|
||||
}
|
||||
|
||||
const v = validateBinary(platform === "win32" ? cachePath : binaryPath);
|
||||
if (!v.ok) throw new Error(`invalid binary (${v.reason})`);
|
||||
if (platform !== "win32") try { chmodSync(binaryPath, 0o755); } catch {}
|
||||
return true;
|
||||
})
|
||||
.catch((e) => { lastBootstrapError = e; return false; });
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// If missing, attempt to bootstrap into place (helps when Bun blocks postinstall)
|
||||
if (!existsSync(binaryPath) && !existsSync(legacyBinaryPath)) {
|
||||
const ok = await tryBootstrapBinary();
|
||||
if (!ok) {
|
||||
// retry legacy name in case archive provided coder-*
|
||||
if (existsSync(legacyBinaryPath) && !existsSync(binaryPath)) {
|
||||
binaryPath = legacyBinaryPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prefer cached binary when available
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(path.join(__dirname, "..", "package.json"), "utf8"));
|
||||
const version = pkg.version;
|
||||
const cached = getCachedBinaryPath(version);
|
||||
const v = existsSync(cached) ? validateBinary(cached) : { ok: false };
|
||||
if (v.ok) {
|
||||
binaryPath = cached;
|
||||
} else if (!existsSync(binaryPath) && existsSync(legacyBinaryPath)) {
|
||||
binaryPath = legacyBinaryPath;
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
// Check if binary exists and try to fix permissions if needed
|
||||
// fs imports are above; keep for readability if tree-shaken by bundlers
|
||||
import { spawnSync } from "child_process";
|
||||
if (existsSync(binaryPath)) {
|
||||
try {
|
||||
// Ensure binary is executable on Unix-like systems
|
||||
if (platform !== "win32") {
|
||||
chmodSync(binaryPath, 0o755);
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore permission errors, will be caught below if it's a real problem
|
||||
}
|
||||
} else {
|
||||
console.error(`Binary not found: ${binaryPath}`);
|
||||
if (lastBootstrapError) {
|
||||
const msg = (lastBootstrapError && (lastBootstrapError.message || String(lastBootstrapError))) || 'unknown bootstrap error';
|
||||
console.error(`Bootstrap error: ${msg}`);
|
||||
}
|
||||
console.error(`Please try reinstalling the package:`);
|
||||
console.error(` npm uninstall -g @just-every/code`);
|
||||
console.error(` npm install -g @just-every/code`);
|
||||
if (isWSL()) {
|
||||
console.error("Detected WSL. Install inside WSL (Ubuntu) separately:");
|
||||
console.error(" npx -y @just-every/code@latest (run inside WSL)");
|
||||
console.error("If installed globally on Windows, those binaries are not usable from WSL.");
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Lightweight header validation to provide clearer errors before spawn
|
||||
// Reuse the validateBinary helper defined above in the bootstrap section.
|
||||
|
||||
const validation = validateBinary(binaryPath);
|
||||
if (!validation.ok) {
|
||||
console.error(`The native binary at ${binaryPath} appears invalid: ${validation.reason}`);
|
||||
console.error("This can happen if the download failed or was modified by antivirus/proxy.");
|
||||
console.error("Please try reinstalling:");
|
||||
console.error(" npm uninstall -g @just-every/code");
|
||||
console.error(" npm install -g @just-every/code");
|
||||
if (platform === "win32") {
|
||||
console.error("If the issue persists, clear npm cache and disable antivirus temporarily:");
|
||||
console.error(" npm cache clean --force");
|
||||
}
|
||||
if (isWSL()) {
|
||||
console.error("Detected WSL. Ensure you install/run inside WSL, not Windows:");
|
||||
console.error(" npx -y @just-every/code@latest (inside WSL)");
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// If running under npx/npm, emit a concise notice about which binary path is used
|
||||
try {
|
||||
const ua = process.env.npm_config_user_agent || "";
|
||||
const isNpx = ua.includes("npx");
|
||||
if (isNpx && process.stderr && process.stderr.isTTY) {
|
||||
// Best-effort discovery of another 'code' on PATH for user clarity
|
||||
let otherCode = "";
|
||||
try {
|
||||
const cmd = process.platform === "win32" ? "where code" : "command -v code || which code || true";
|
||||
const out = spawnSync(process.platform === "win32" ? "cmd" : "bash", [
|
||||
process.platform === "win32" ? "/c" : "-lc",
|
||||
cmd,
|
||||
], { encoding: "utf8" });
|
||||
const line = (out.stdout || "").split(/\r?\n/).map((s) => s.trim()).filter(Boolean)[0];
|
||||
if (line && !line.includes("@just-every/code")) {
|
||||
otherCode = line;
|
||||
}
|
||||
} catch {}
|
||||
if (otherCode) {
|
||||
console.error(`@just-every/code: running bundled binary -> ${binaryPath}`);
|
||||
console.error(`Note: a different 'code' exists at ${otherCode}; not delegating.`);
|
||||
} else {
|
||||
console.error(`@just-every/code: running bundled binary -> ${binaryPath}`);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// Use an asynchronous spawn instead of spawnSync so that Node is able to
|
||||
// respond to signals (e.g. Ctrl-C / SIGINT) while the native binary is
|
||||
// executing. This allows us to forward those signals to the child process
|
||||
// and guarantees that when either the child terminates or the parent
|
||||
// receives a fatal signal, both processes exit in a predictable manner.
|
||||
const { spawn } = await import("child_process");
|
||||
|
||||
const child = spawn(binaryPath, process.argv.slice(2), {
|
||||
stdio: "inherit",
|
||||
env: { ...process.env, CODER_MANAGED_BY_NPM: "1", CODEX_MANAGED_BY_NPM: "1" },
|
||||
});
|
||||
|
||||
child.on("error", (err) => {
|
||||
// Typically triggered when the binary is missing or not executable.
|
||||
const code = err && err.code;
|
||||
if (code === 'EACCES') {
|
||||
console.error(`Permission denied: ${binaryPath}`);
|
||||
console.error(`Try running: chmod +x "${binaryPath}"`);
|
||||
console.error(`Or reinstall the package with: npm install -g @just-every/code`);
|
||||
} else if (code === 'EFTYPE' || code === 'ENOEXEC') {
|
||||
console.error(`Failed to execute native binary: ${binaryPath}`);
|
||||
console.error("The file may be corrupt or of the wrong type. Reinstall usually fixes this:");
|
||||
console.error(" npm uninstall -g @just-every/code && npm install -g @just-every/code");
|
||||
if (platform === 'win32') {
|
||||
console.error("On Windows, ensure the .exe downloaded correctly (proxy/AV can interfere).");
|
||||
console.error("Try clearing cache: npm cache clean --force");
|
||||
}
|
||||
if (isWSL()) {
|
||||
console.error("Detected WSL. Windows binaries cannot be executed from WSL.");
|
||||
console.error("Install inside WSL and run there: npx -y @just-every/code@latest");
|
||||
}
|
||||
} else {
|
||||
console.error(err);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Forward common termination signals to the child so that it shuts down
|
||||
// gracefully. In the handler we temporarily disable the default behavior of
|
||||
// exiting immediately; once the child has been signaled we simply wait for
|
||||
// its exit event which will in turn terminate the parent (see below).
|
||||
const forwardSignal = (signal) => {
|
||||
if (child.killed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
child.kill(signal);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => {
|
||||
process.on(sig, () => forwardSignal(sig));
|
||||
});
|
||||
|
||||
// When the child exits, mirror its termination reason in the parent so that
|
||||
// shell scripts and other tooling observe the correct exit status.
|
||||
// Wrap the lifetime of the child process in a Promise so that we can await
|
||||
// its termination in a structured way. The Promise resolves with an object
|
||||
// describing how the child exited: either via exit code or due to a signal.
|
||||
const childResult = await new Promise((resolve) => {
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
resolve({ type: "signal", signal });
|
||||
} else {
|
||||
resolve({ type: "code", exitCode: code ?? 1 });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (childResult.type === "signal") {
|
||||
// Re-emit the same signal so that the parent terminates with the expected
|
||||
// semantics (this also sets the correct exit code of 128 + n).
|
||||
process.kill(process.pid, childResult.signal);
|
||||
} else {
|
||||
process.exit(childResult.exitCode);
|
||||
}
|
||||
Executable
+157
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env node
|
||||
// Unified entry point for the Codex CLI.
|
||||
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
// __dirname equivalent in ESM
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const { platform, arch } = process;
|
||||
|
||||
let targetTriple = null;
|
||||
switch (platform) {
|
||||
case "linux":
|
||||
case "android":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-unknown-linux-musl";
|
||||
break;
|
||||
case "arm64":
|
||||
targetTriple = "aarch64-unknown-linux-musl";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "darwin":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-apple-darwin";
|
||||
break;
|
||||
case "arm64":
|
||||
targetTriple = "aarch64-apple-darwin";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "win32":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-pc-windows-msvc.exe";
|
||||
break;
|
||||
case "arm64":
|
||||
targetTriple = "aarch64-pc-windows-msvc.exe";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (!targetTriple) {
|
||||
throw new Error(`Unsupported platform: ${platform} (${arch})`);
|
||||
}
|
||||
|
||||
const binaryPath = path.join(__dirname, "..", "bin", `codex-${targetTriple}`);
|
||||
|
||||
// Use an asynchronous spawn instead of spawnSync so that Node is able to
|
||||
// respond to signals (e.g. Ctrl-C / SIGINT) while the native binary is
|
||||
// executing. This allows us to forward those signals to the child process
|
||||
// and guarantees that when either the child terminates or the parent
|
||||
// receives a fatal signal, both processes exit in a predictable manner.
|
||||
const { spawn } = await import("child_process");
|
||||
|
||||
async function tryImport(moduleName) {
|
||||
try {
|
||||
// eslint-disable-next-line node/no-unsupported-features/es-syntax
|
||||
return await import(moduleName);
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveRgDir() {
|
||||
const ripgrep = await tryImport("@vscode/ripgrep");
|
||||
if (!ripgrep?.rgPath) {
|
||||
return null;
|
||||
}
|
||||
return path.dirname(ripgrep.rgPath);
|
||||
}
|
||||
|
||||
function getUpdatedPath(newDirs) {
|
||||
const pathSep = process.platform === "win32" ? ";" : ":";
|
||||
const existingPath = process.env.PATH || "";
|
||||
const updatedPath = [
|
||||
...newDirs,
|
||||
...existingPath.split(pathSep).filter(Boolean),
|
||||
].join(pathSep);
|
||||
return updatedPath;
|
||||
}
|
||||
|
||||
const additionalDirs = [];
|
||||
const rgDir = await resolveRgDir();
|
||||
if (rgDir) {
|
||||
additionalDirs.push(rgDir);
|
||||
}
|
||||
const updatedPath = getUpdatedPath(additionalDirs);
|
||||
|
||||
const child = spawn(binaryPath, process.argv.slice(2), {
|
||||
stdio: "inherit",
|
||||
env: { ...process.env, PATH: updatedPath, CODEX_MANAGED_BY_NPM: "1" },
|
||||
});
|
||||
|
||||
child.on("error", (err) => {
|
||||
// Typically triggered when the binary is missing or not executable.
|
||||
// Re-throwing here will terminate the parent with a non-zero exit code
|
||||
// while still printing a helpful stack trace.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Forward common termination signals to the child so that it shuts down
|
||||
// gracefully. In the handler we temporarily disable the default behavior of
|
||||
// exiting immediately; once the child has been signaled we simply wait for
|
||||
// its exit event which will in turn terminate the parent (see below).
|
||||
const forwardSignal = (signal) => {
|
||||
if (child.killed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
child.kill(signal);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => {
|
||||
process.on(sig, () => forwardSignal(sig));
|
||||
});
|
||||
|
||||
// When the child exits, mirror its termination reason in the parent so that
|
||||
// shell scripts and other tooling observe the correct exit status.
|
||||
// Wrap the lifetime of the child process in a Promise so that we can await
|
||||
// its termination in a structured way. The Promise resolves with an object
|
||||
// describing how the child exited: either via exit code or due to a signal.
|
||||
const childResult = await new Promise((resolve) => {
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
resolve({ type: "signal", signal });
|
||||
} else {
|
||||
resolve({ type: "code", exitCode: code ?? 1 });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (childResult.type === "signal") {
|
||||
// Re-emit the same signal so that the parent terminates with the expected
|
||||
// semantics (this also sets the correct exit code of 128 + n).
|
||||
process.kill(process.pid, childResult.signal);
|
||||
} else {
|
||||
process.exit(childResult.exitCode);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@just-every/code",
|
||||
"version": "0.2.131",
|
||||
"license": "Apache-2.0",
|
||||
"description": "Lightweight coding agent that runs in your terminal - fork of OpenAI Codex",
|
||||
"bin": {
|
||||
"coder": "bin/coder.js"
|
||||
},
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"files": [
|
||||
"bin/coder.js",
|
||||
"bin/codex.js",
|
||||
"postinstall.js",
|
||||
"scripts/preinstall.js",
|
||||
"scripts/windows-cleanup.ps1",
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"preinstall": "node scripts/preinstall.js",
|
||||
"postinstall": "node postinstall.js",
|
||||
"prepublishOnly": "node -e \"const fs=require('fs'),path=require('path'); const repoGit=path.join(__dirname,'..','.git'); const inCi=process.env.GITHUB_ACTIONS==='true'||process.env.CI==='true'; if(fs.existsSync(repoGit) && !inCi){ console.error('Refusing to publish from codex-cli. Publishing happens via release.yml.'); process.exit(1);} else { console.log(inCi ? 'CI publish detected.' : 'Publishing staged package...'); }\""
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/just-every/code.git"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"prettier": "^3.3.3"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@just-every/code-darwin-arm64": "0.2.131",
|
||||
"@just-every/code-darwin-x64": "0.2.131",
|
||||
"@just-every/code-linux-x64-musl": "0.2.131",
|
||||
"@just-every/code-linux-arm64-musl": "0.2.131",
|
||||
"@just-every/code-win32-x64": "0.2.131"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,689 @@
|
||||
#!/usr/bin/env node
|
||||
// Non-functional change to trigger release workflow
|
||||
|
||||
import { existsSync, mkdirSync, createWriteStream, chmodSync, readFileSync, readSync, writeFileSync, unlinkSync, statSync, openSync, closeSync, copyFileSync, fsyncSync, renameSync, realpathSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { get } from 'https';
|
||||
import { platform, arch, tmpdir } from 'os';
|
||||
import { execSync } from 'child_process';
|
||||
import { createRequire } from 'module';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// Map Node.js platform/arch to Rust target triples
|
||||
function getTargetTriple() {
|
||||
const platformMap = {
|
||||
'darwin': 'apple-darwin',
|
||||
'linux': 'unknown-linux-musl', // Default to musl for better compatibility
|
||||
'win32': 'pc-windows-msvc'
|
||||
};
|
||||
|
||||
const archMap = {
|
||||
'x64': 'x86_64',
|
||||
'arm64': 'aarch64'
|
||||
};
|
||||
|
||||
const rustArch = archMap[arch()] || arch();
|
||||
const rustPlatform = platformMap[platform()] || platform();
|
||||
|
||||
return `${rustArch}-${rustPlatform}`;
|
||||
}
|
||||
|
||||
// Resolve a persistent user cache directory for binaries so that repeated
|
||||
// npx installs can reuse a previously downloaded artifact and skip work.
|
||||
function getCacheDir(version) {
|
||||
const plt = platform();
|
||||
const home = process.env.HOME || process.env.USERPROFILE || '';
|
||||
let base = '';
|
||||
if (plt === 'win32') {
|
||||
base = process.env.LOCALAPPDATA || join(home, 'AppData', 'Local');
|
||||
} else if (plt === 'darwin') {
|
||||
base = join(home, 'Library', 'Caches');
|
||||
} else {
|
||||
base = process.env.XDG_CACHE_HOME || join(home, '.cache');
|
||||
}
|
||||
const dir = join(base, 'just-every', 'code', version);
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
function getCachedBinaryPath(version, targetTriple, isWindows) {
|
||||
const ext = isWindows ? '.exe' : '';
|
||||
const cacheDir = getCacheDir(version);
|
||||
return join(cacheDir, `code-${targetTriple}${ext}`);
|
||||
}
|
||||
|
||||
function isWSL() {
|
||||
if (platform() !== 'linux') return false;
|
||||
try {
|
||||
const ver = readFileSync('/proc/version', 'utf8').toLowerCase();
|
||||
return ver.includes('microsoft') || !!process.env.WSL_DISTRO_NAME;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
function isPathOnWindowsFs(p) {
|
||||
try {
|
||||
const mounts = readFileSync('/proc/mounts', 'utf8').split(/\n/).filter(Boolean);
|
||||
let best = { mount: '/', type: 'unknown', len: 1 };
|
||||
for (const line of mounts) {
|
||||
const parts = line.split(' ');
|
||||
if (parts.length < 3) continue;
|
||||
const mnt = parts[1];
|
||||
const typ = parts[2];
|
||||
if (p.startsWith(mnt) && mnt.length > best.len) best = { mount: mnt, type: typ, len: mnt.length };
|
||||
}
|
||||
return best.type === 'drvfs' || best.type === 'cifs';
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
async function writeCacheAtomic(srcPath, cachePath) {
|
||||
try {
|
||||
if (existsSync(cachePath)) {
|
||||
const ok = validateDownloadedBinary(cachePath).ok;
|
||||
if (ok) return;
|
||||
}
|
||||
} catch {}
|
||||
const dir = dirname(cachePath);
|
||||
if (!existsSync(dir)) { try { mkdirSync(dir, { recursive: true }); } catch {} }
|
||||
const tmp = cachePath + '.tmp-' + Math.random().toString(36).slice(2, 8);
|
||||
copyFileSync(srcPath, tmp);
|
||||
try { const fd = openSync(tmp, 'r'); try { fsyncSync(fd); } finally { closeSync(fd); } } catch {}
|
||||
// Retry with exponential backoff up to ~1.6s total
|
||||
const delays = [100, 200, 400, 800, 1200, 1600];
|
||||
for (let i = 0; i < delays.length; i++) {
|
||||
try {
|
||||
if (existsSync(cachePath)) { try { unlinkSync(cachePath); } catch {} }
|
||||
renameSync(tmp, cachePath);
|
||||
return;
|
||||
} catch {
|
||||
await new Promise(r => setTimeout(r, delays[i]));
|
||||
}
|
||||
}
|
||||
if (existsSync(cachePath)) { try { unlinkSync(cachePath); } catch {} }
|
||||
renameSync(tmp, cachePath);
|
||||
}
|
||||
|
||||
async function downloadBinary(url, dest, maxRedirects = 5, maxRetries = 3) {
|
||||
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
const doAttempt = () => new Promise((resolve, reject) => {
|
||||
const attempt = (currentUrl, redirectsLeft) => {
|
||||
const req = get(currentUrl, (response) => {
|
||||
const status = response.statusCode || 0;
|
||||
const location = response.headers.location;
|
||||
|
||||
if ((status === 301 || status === 302 || status === 303 || status === 307 || status === 308) && location) {
|
||||
if (redirectsLeft <= 0) {
|
||||
reject(new Error(`Too many redirects while downloading ${currentUrl}`));
|
||||
return;
|
||||
}
|
||||
attempt(location, redirectsLeft - 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (status === 200) {
|
||||
const expected = parseInt(response.headers['content-length'] || '0', 10) || 0;
|
||||
let bytes = 0;
|
||||
let timer;
|
||||
const timeoutMs = 30000; // 30s inactivity timeout
|
||||
|
||||
const resetTimer = () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
req.destroy(new Error('download stalled'));
|
||||
}, timeoutMs);
|
||||
};
|
||||
|
||||
resetTimer();
|
||||
response.on('data', (chunk) => {
|
||||
bytes += chunk.length;
|
||||
resetTimer();
|
||||
});
|
||||
|
||||
const file = createWriteStream(dest);
|
||||
response.pipe(file);
|
||||
file.on('finish', () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
file.close();
|
||||
if (expected && bytes !== expected) {
|
||||
try { unlinkSync(dest); } catch {}
|
||||
reject(new Error(`incomplete download: got ${bytes} of ${expected} bytes`));
|
||||
} else if (bytes === 0) {
|
||||
try { unlinkSync(dest); } catch {}
|
||||
reject(new Error('empty download'));
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
file.on('error', (err) => {
|
||||
if (timer) clearTimeout(timer);
|
||||
try { unlinkSync(dest); } catch {}
|
||||
reject(err);
|
||||
});
|
||||
} else {
|
||||
reject(new Error(`Failed to download: HTTP ${status}`));
|
||||
}
|
||||
});
|
||||
|
||||
req.on('error', (err) => {
|
||||
try { unlinkSync(dest); } catch {}
|
||||
reject(err);
|
||||
});
|
||||
|
||||
// Absolute request timeout to avoid hanging forever
|
||||
req.setTimeout(120000, () => {
|
||||
req.destroy(new Error('download timed out'));
|
||||
});
|
||||
};
|
||||
|
||||
attempt(url, maxRedirects);
|
||||
});
|
||||
|
||||
let attemptNum = 0;
|
||||
while (true) {
|
||||
try {
|
||||
return await doAttempt();
|
||||
} catch (e) {
|
||||
attemptNum += 1;
|
||||
if (attemptNum > maxRetries) throw e;
|
||||
const backoff = Math.min(2000, 200 * attemptNum);
|
||||
await sleep(backoff);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateDownloadedBinary(p) {
|
||||
try {
|
||||
const st = statSync(p);
|
||||
if (!st.isFile() || st.size === 0) {
|
||||
return { ok: false, reason: 'empty or not a regular file' };
|
||||
}
|
||||
const fd = openSync(p, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(4);
|
||||
const n = readSync(fd, buf, 0, 4, 0);
|
||||
if (n < 2) return { ok: false, reason: 'too short' };
|
||||
const plt = platform();
|
||||
if (plt === 'win32') {
|
||||
if (!(buf[0] === 0x4d && buf[1] === 0x5a)) return { ok: false, reason: 'invalid PE header (missing MZ)' };
|
||||
} else if (plt === 'linux' || plt === 'android') {
|
||||
if (!(buf[0] === 0x7f && buf[1] === 0x45 && buf[2] === 0x4c && buf[3] === 0x46)) return { ok: false, reason: 'invalid ELF header' };
|
||||
} else if (plt === 'darwin') {
|
||||
const isMachO = (buf[0] === 0xcf && buf[1] === 0xfa && buf[2] === 0xed && buf[3] === 0xfe) ||
|
||||
(buf[0] === 0xca && buf[1] === 0xfe && buf[2] === 0xba && buf[3] === 0xbe);
|
||||
if (!isMachO) return { ok: false, reason: 'invalid Mach-O header' };
|
||||
}
|
||||
return { ok: true };
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
} catch (e) {
|
||||
return { ok: false, reason: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// Detect potential PATH conflict with an existing `code` command (e.g., VS Code)
|
||||
// Only relevant for global installs; skip for npx/local installs to keep postinstall fast.
|
||||
const ua = process.env.npm_config_user_agent || '';
|
||||
const isNpx = ua.includes('npx');
|
||||
const isGlobal = process.env.npm_config_global === 'true';
|
||||
if (isGlobal && !isNpx) {
|
||||
try {
|
||||
const whichCmd = process.platform === 'win32' ? 'where code' : 'command -v code || which code || true';
|
||||
const resolved = execSync(whichCmd, { stdio: ['ignore', 'pipe', 'ignore'], shell: process.platform !== 'win32' }).toString().split(/\r?\n/).filter(Boolean)[0];
|
||||
if (resolved) {
|
||||
let contents = '';
|
||||
try {
|
||||
contents = readFileSync(resolved, 'utf8');
|
||||
} catch {
|
||||
contents = '';
|
||||
}
|
||||
const looksLikeOurs = contents.includes('@just-every/code') || contents.includes('bin/coder.js');
|
||||
if (!looksLikeOurs) {
|
||||
console.warn('[notice] Found an existing `code` on PATH at:');
|
||||
console.warn(` ${resolved}`);
|
||||
console.warn('[notice] We will still install our CLI, also available as `coder`.');
|
||||
console.warn(' If `code` runs another tool, prefer using: coder');
|
||||
console.warn(' Or run our CLI explicitly via: npx -y @just-every/code');
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore detection failures; proceed with install.
|
||||
}
|
||||
}
|
||||
|
||||
const targetTriple = getTargetTriple();
|
||||
const isWindows = platform() === 'win32';
|
||||
const binaryExt = isWindows ? '.exe' : '';
|
||||
|
||||
const binDir = join(__dirname, 'bin');
|
||||
if (!existsSync(binDir)) {
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Get package version - use readFileSync for compatibility
|
||||
const packageJson = JSON.parse(readFileSync(join(__dirname, 'package.json'), 'utf8'));
|
||||
const version = packageJson.version;
|
||||
|
||||
// Download only the primary binary; we'll create wrappers for legacy names.
|
||||
const binaries = ['code'];
|
||||
|
||||
console.log(`Installing @just-every/code v${version} for ${targetTriple}...`);
|
||||
|
||||
for (const binary of binaries) {
|
||||
const binaryName = `${binary}-${targetTriple}${binaryExt}`;
|
||||
const localPath = join(binDir, binaryName);
|
||||
const cachePath = getCachedBinaryPath(version, targetTriple, isWindows);
|
||||
|
||||
// On Windows we avoid placing the executable inside node_modules to prevent
|
||||
// EBUSY/EPERM during global upgrades when the binary is in use.
|
||||
// We treat the user cache path as the canonical home of the native binary.
|
||||
// For macOS/Linux we keep previous behavior and also place a copy in binDir
|
||||
// for convenience.
|
||||
|
||||
// Fast path: if a valid cached binary exists for this version+triple, reuse it.
|
||||
try {
|
||||
if (existsSync(cachePath)) {
|
||||
const valid = validateDownloadedBinary(cachePath);
|
||||
if (valid.ok) {
|
||||
// Avoid mirroring into node_modules on Windows or WSL-on-NTFS.
|
||||
const wsl = isWSL();
|
||||
const binDirReal = (() => { try { return realpathSync(binDir); } catch { return binDir; } })();
|
||||
const mirrorToLocal = !(isWindows || (wsl && isPathOnWindowsFs(binDirReal)));
|
||||
if (mirrorToLocal) {
|
||||
copyFileSync(cachePath, localPath);
|
||||
try { chmodSync(localPath, 0o755); } catch {}
|
||||
}
|
||||
console.log(`✓ ${binaryName} ready from user cache`);
|
||||
continue; // next binary
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore cache errors and fall through to normal paths
|
||||
}
|
||||
|
||||
// First try platform package via npm optionalDependencies (fast path on npm CDN).
|
||||
const require = createRequire(import.meta.url);
|
||||
const platformPkg = (() => {
|
||||
const name = (() => {
|
||||
if (isWindows) return '@just-every/code-win32-x64';
|
||||
const plt = platform();
|
||||
const cpu = arch();
|
||||
if (plt === 'darwin' && cpu === 'arm64') return '@just-every/code-darwin-arm64';
|
||||
if (plt === 'darwin' && cpu === 'x64') return '@just-every/code-darwin-x64';
|
||||
if (plt === 'linux' && cpu === 'x64') return '@just-every/code-linux-x64-musl';
|
||||
if (plt === 'linux' && cpu === 'arm64') return '@just-every/code-linux-arm64-musl';
|
||||
return null;
|
||||
})();
|
||||
if (!name) return null;
|
||||
try {
|
||||
const pkgJsonPath = require.resolve(`${name}/package.json`);
|
||||
const pkgDir = dirname(pkgJsonPath);
|
||||
return { name, dir: pkgDir };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
if (platformPkg) {
|
||||
try {
|
||||
// Expect binary inside platform package bin directory
|
||||
const src = join(platformPkg.dir, 'bin', binaryName);
|
||||
if (!existsSync(src)) {
|
||||
throw new Error(`platform package missing binary: ${platformPkg.name}`);
|
||||
}
|
||||
// Populate cache first (canonical location) atomically
|
||||
await writeCacheAtomic(src, cachePath);
|
||||
// Mirror into local bin only on Unix-like filesystems (not Windows/WSL-on-NTFS)
|
||||
const wsl = isWSL();
|
||||
const binDirReal = (() => { try { return realpathSync(binDir); } catch { return binDir; } })();
|
||||
const mirrorToLocal = !(isWindows || (wsl && isPathOnWindowsFs(binDirReal)));
|
||||
if (mirrorToLocal) {
|
||||
copyFileSync(cachePath, localPath);
|
||||
try { chmodSync(localPath, 0o755); } catch {}
|
||||
}
|
||||
console.log(`✓ Installed ${binaryName} from ${platformPkg.name} (cached)`);
|
||||
continue; // next binary
|
||||
} catch (e) {
|
||||
console.warn(`⚠ Failed platform package install (${e.message}), falling back to GitHub download`);
|
||||
}
|
||||
}
|
||||
|
||||
// Decide archive format per OS with fallback on macOS/Linux:
|
||||
// - Windows: .zip
|
||||
// - macOS/Linux: prefer .zst if `zstd` CLI is available; otherwise use .tar.gz
|
||||
const isWin = isWindows;
|
||||
const isWSL = (() => {
|
||||
if (platform() !== 'linux') return false;
|
||||
try {
|
||||
const ver = readFileSync('/proc/version', 'utf8').toLowerCase();
|
||||
return ver.includes('microsoft') || !!process.env.WSL_DISTRO_NAME;
|
||||
} catch { return false; }
|
||||
})();
|
||||
const binDirReal = (() => { try { return realpathSync(binDir); } catch { return binDir; } })();
|
||||
const mirrorToLocal = !(isWin || (isWSL && isPathOnWindowsFs(binDirReal)));
|
||||
let useZst = false;
|
||||
if (!isWin) {
|
||||
try {
|
||||
execSync('zstd --version', { stdio: 'ignore', shell: true });
|
||||
useZst = true;
|
||||
} catch {
|
||||
useZst = false;
|
||||
}
|
||||
}
|
||||
const archiveName = isWin ? `${binaryName}.zip` : (useZst ? `${binaryName}.zst` : `${binaryName}.tar.gz`);
|
||||
const downloadUrl = `https://github.com/just-every/code/releases/download/v${version}/${archiveName}`;
|
||||
|
||||
console.log(`Downloading ${archiveName}...`);
|
||||
try {
|
||||
const needsIsolation = isWin || (!isWin && !mirrorToLocal); // Windows or WSL-on-NTFS
|
||||
let safeTempDir = needsIsolation ? join(tmpdir(), 'just-every', 'code', version) : binDir;
|
||||
// Ensure staging dir exists; if tmp fails (permissions/space), fall back to user cache.
|
||||
if (needsIsolation) {
|
||||
try {
|
||||
if (!existsSync(safeTempDir)) mkdirSync(safeTempDir, { recursive: true });
|
||||
} catch {
|
||||
try {
|
||||
safeTempDir = getCacheDir(version);
|
||||
if (!existsSync(safeTempDir)) mkdirSync(safeTempDir, { recursive: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
const tmpPath = join(needsIsolation ? safeTempDir : binDir, `.${archiveName}.part`);
|
||||
await downloadBinary(downloadUrl, tmpPath);
|
||||
|
||||
if (isWin) {
|
||||
// Unzip to a temp directory, then move into the per-user cache.
|
||||
const unzipDest = safeTempDir;
|
||||
try {
|
||||
const sysRoot = process.env.SystemRoot || process.env.windir || 'C:\\Windows';
|
||||
const psFull = join(sysRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
||||
const psCmd = `Expand-Archive -Path '${tmpPath}' -DestinationPath '${unzipDest}' -Force`;
|
||||
let ok = false;
|
||||
// Attempt full-path powershell.exe
|
||||
try { execSync(`"${psFull}" -NoProfile -NonInteractive -Command "${psCmd}"`, { stdio: 'ignore' }); ok = true; } catch {}
|
||||
// Fallback to powershell in PATH
|
||||
if (!ok) { try { execSync(`powershell -NoProfile -NonInteractive -Command "${psCmd}"`, { stdio: 'ignore' }); ok = true; } catch {} }
|
||||
// Fallback to pwsh (PowerShell 7)
|
||||
if (!ok) { try { execSync(`pwsh -NoProfile -NonInteractive -Command "${psCmd}"`, { stdio: 'ignore' }); ok = true; } catch {} }
|
||||
// Final fallback: bsdtar can extract .zip
|
||||
if (!ok) { execSync(`tar -xf "${tmpPath}" -C "${unzipDest}"`, { stdio: 'ignore', shell: true }); }
|
||||
} catch (e) {
|
||||
throw new Error(`failed to unzip archive: ${e.message}`);
|
||||
} finally {
|
||||
try { unlinkSync(tmpPath); } catch {}
|
||||
}
|
||||
// Move the extracted file from temp to cache; do not leave a copy in node_modules
|
||||
try {
|
||||
const extractedPath = join(unzipDest, binaryName);
|
||||
await writeCacheAtomic(extractedPath, cachePath);
|
||||
try { unlinkSync(extractedPath); } catch {}
|
||||
} catch (e) {
|
||||
throw new Error(`failed to move binary to cache: ${e.message}`);
|
||||
}
|
||||
} else {
|
||||
if (useZst) {
|
||||
// Decompress .zst via system zstd
|
||||
try {
|
||||
const outPath = mirrorToLocal ? localPath : join(safeTempDir, binaryName);
|
||||
execSync(`zstd -d '${tmpPath}' -o '${outPath}'`, { stdio: 'ignore', shell: true });
|
||||
} catch (e) {
|
||||
try { unlinkSync(tmpPath); } catch {}
|
||||
throw new Error(`failed to decompress .zst (need zstd CLI): ${e.message}`);
|
||||
}
|
||||
try { unlinkSync(tmpPath); } catch {}
|
||||
} else {
|
||||
// Extract .tar.gz using system tar
|
||||
try {
|
||||
const dest = mirrorToLocal ? binDir : safeTempDir;
|
||||
execSync(`tar -xzf '${tmpPath}' -C '${dest}'`, { stdio: 'ignore', shell: true });
|
||||
} catch (e) {
|
||||
try { unlinkSync(tmpPath); } catch {}
|
||||
throw new Error(`failed to extract .tar.gz: ${e.message}`);
|
||||
}
|
||||
try { unlinkSync(tmpPath); } catch {}
|
||||
}
|
||||
if (!mirrorToLocal) {
|
||||
try {
|
||||
const extractedPath = join(safeTempDir, binaryName);
|
||||
await writeCacheAtomic(extractedPath, cachePath);
|
||||
try { unlinkSync(extractedPath); } catch {}
|
||||
} catch (e) {
|
||||
throw new Error(`failed to move binary to cache: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate header to avoid corrupt binaries causing spawn EFTYPE/ENOEXEC
|
||||
|
||||
const valid = validateDownloadedBinary(isWin ? cachePath : (mirrorToLocal ? localPath : cachePath));
|
||||
if (!valid.ok) {
|
||||
try { (isWin || !mirrorToLocal) ? unlinkSync(cachePath) : unlinkSync(localPath); } catch {}
|
||||
throw new Error(`invalid binary (${valid.reason})`);
|
||||
}
|
||||
|
||||
// Make executable on Unix-like systems
|
||||
if (!isWin && mirrorToLocal) {
|
||||
chmodSync(localPath, 0o755);
|
||||
}
|
||||
|
||||
console.log(`✓ Installed ${binaryName}${(isWin || !mirrorToLocal) ? ' (cached)' : ''}`);
|
||||
// Ensure persistent cache holds the binary (already true for Windows path)
|
||||
if (!isWin && mirrorToLocal) {
|
||||
try { await writeCacheAtomic(localPath, cachePath); } catch {}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`✗ Failed to install ${binaryName}: ${error.message}`);
|
||||
console.error(` Downloaded from: ${downloadUrl}`);
|
||||
// Continue with other binaries even if one fails
|
||||
}
|
||||
}
|
||||
|
||||
// Create platform-specific symlink/copy for main binary
|
||||
const mainBinary = `code-${targetTriple}${binaryExt}`;
|
||||
const mainBinaryPath = join(binDir, mainBinary);
|
||||
|
||||
if (existsSync(mainBinaryPath) || existsSync(getCachedBinaryPath(version, targetTriple, platform() === 'win32'))) {
|
||||
try {
|
||||
const probePath = existsSync(mainBinaryPath) ? mainBinaryPath : getCachedBinaryPath(version, targetTriple, platform() === 'win32');
|
||||
const stats = statSync(probePath);
|
||||
if (!stats.size) throw new Error('binary is empty (download likely failed)');
|
||||
const valid = validateDownloadedBinary(probePath);
|
||||
if (!valid.ok) {
|
||||
console.warn(`⚠ Main code binary appears invalid: ${valid.reason}`);
|
||||
console.warn(' Try reinstalling or check your network/proxy settings.');
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(`⚠ Main code binary appears invalid: ${e.message}`);
|
||||
console.warn(' Try reinstalling or check your network/proxy settings.');
|
||||
}
|
||||
console.log('Setting up main code binary...');
|
||||
|
||||
// On Windows, we can't use symlinks easily, so update the JS wrapper
|
||||
// On Unix, the JS wrapper will find the correct binary
|
||||
console.log('✓ Installation complete!');
|
||||
} else {
|
||||
console.warn('⚠ Main code binary not found. You may need to build from source.');
|
||||
}
|
||||
|
||||
// Handle collisions (e.g., VS Code) and add wrappers. We no longer publish a
|
||||
// `code` bin in package.json. Instead, for global installs we create a `code`
|
||||
// wrapper only when there is no conflicting `code` earlier on PATH. This avoids
|
||||
// hijacking the VS Code CLI while still giving users a friendly name when safe.
|
||||
// For upgrades from older versions that published a `code` bin, we also remove
|
||||
// our old shim if a conflict is detected.
|
||||
if (isGlobal && !isNpx) try {
|
||||
const isTTY = process.stdout && process.stdout.isTTY;
|
||||
const isWindows = platform() === 'win32';
|
||||
const ua = process.env.npm_config_user_agent || '';
|
||||
const isBun = ua.includes('bun') || !!process.env.BUN_INSTALL;
|
||||
|
||||
const installedCmds = new Set(['coder']); // global install always exposes coder via package manager
|
||||
const skippedCmds = [];
|
||||
|
||||
// Helper to resolve all 'code' on PATH
|
||||
const resolveAllOnPath = () => {
|
||||
try {
|
||||
if (isWindows) {
|
||||
const out = execSync('where code', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
|
||||
return out.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
|
||||
}
|
||||
let out = '';
|
||||
try {
|
||||
out = execSync('bash -lc "which -a code 2>/dev/null"', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
|
||||
} catch {
|
||||
try {
|
||||
out = execSync('command -v code || true', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
|
||||
} catch { out = ''; }
|
||||
}
|
||||
return out.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
if (isBun) {
|
||||
// Bun creates shims for every bin; if another 'code' exists elsewhere on PATH, remove Bun's shim
|
||||
let bunBin = '';
|
||||
try {
|
||||
const home = process.env.HOME || process.env.USERPROFILE || '';
|
||||
const bunBase = process.env.BUN_INSTALL || join(home, '.bun');
|
||||
bunBin = join(bunBase, 'bin');
|
||||
} catch {}
|
||||
|
||||
const bunShim = join(bunBin || '', isWindows ? 'code.cmd' : 'code');
|
||||
const candidates = resolveAllOnPath();
|
||||
const other = candidates.find(p => p && (!bunBin || !p.startsWith(bunBin)));
|
||||
if (other && existsSync(bunShim)) {
|
||||
try {
|
||||
unlinkSync(bunShim);
|
||||
console.log(`✓ Skipped global 'code' shim under Bun (existing: ${other})`);
|
||||
skippedCmds.push({ name: 'code', reason: `existing: ${other}` });
|
||||
} catch (e) {
|
||||
console.log(`⚠ Could not remove Bun shim '${bunShim}': ${e.message}`);
|
||||
}
|
||||
} else if (!other) {
|
||||
// No conflict: create a wrapper that forwards to `coder`
|
||||
try {
|
||||
const wrapperPath = bunShim;
|
||||
if (isWindows) {
|
||||
const content = `@echo off\r\n"%~dp0coder" %*\r\n`;
|
||||
writeFileSync(wrapperPath, content);
|
||||
} else {
|
||||
const content = `#!/bin/sh\nexec "$(dirname \"$0\")/coder" "$@"\n`;
|
||||
writeFileSync(wrapperPath, content);
|
||||
chmodSync(wrapperPath, 0o755);
|
||||
}
|
||||
console.log("✓ Created 'code' wrapper -> coder (bun)");
|
||||
installedCmds.add('code');
|
||||
} catch (e) {
|
||||
console.log(`⚠ Failed to create 'code' wrapper (bun): ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Print summary for Bun
|
||||
const list = Array.from(installedCmds).sort().join(', ');
|
||||
console.log(`Commands installed (bun): ${list}`);
|
||||
if (skippedCmds.length) {
|
||||
for (const s of skippedCmds) console.error(`Commands skipped: ${s.name} (${s.reason})`);
|
||||
console.error('→ Use `coder` to run this tool.');
|
||||
}
|
||||
// Final friendly usage hint
|
||||
if (installedCmds.has('code')) {
|
||||
console.log("Use 'code' to launch Code.");
|
||||
} else {
|
||||
console.log("Use 'coder' to launch Code.");
|
||||
}
|
||||
} else {
|
||||
// npm/pnpm/yarn path
|
||||
let globalBin = '';
|
||||
try {
|
||||
globalBin = execSync('npm bin -g', { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
|
||||
} catch {}
|
||||
|
||||
const ourShim = join(globalBin || '', isWindows ? 'code.cmd' : 'code');
|
||||
const candidates = resolveAllOnPath();
|
||||
const others = candidates.filter(p => p && (!ourShim || p !== ourShim));
|
||||
const collision = others.length > 0;
|
||||
|
||||
const ensureWrapper = (name, args) => {
|
||||
if (!globalBin) return;
|
||||
try {
|
||||
const wrapperPath = join(globalBin, isWindows ? `${name}.cmd` : name);
|
||||
if (isWindows) {
|
||||
const content = `@echo off\r\n"%~dp0${collision ? 'coder' : 'code'}" ${args} %*\r\n`;
|
||||
writeFileSync(wrapperPath, content);
|
||||
} else {
|
||||
const content = `#!/bin/sh\nexec "$(dirname \"$0\")/${collision ? 'coder' : 'code'}" ${args} "$@"\n`;
|
||||
writeFileSync(wrapperPath, content);
|
||||
chmodSync(wrapperPath, 0o755);
|
||||
}
|
||||
console.log(`✓ Created wrapper '${name}' -> ${collision ? 'coder' : 'code'} ${args}`);
|
||||
installedCmds.add(name);
|
||||
} catch (e) {
|
||||
console.log(`⚠ Failed to create '${name}' wrapper: ${e.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// Always create legacy wrappers so existing scripts keep working
|
||||
ensureWrapper('code-tui', '');
|
||||
ensureWrapper('code-exec', 'exec');
|
||||
|
||||
if (collision) {
|
||||
console.error('⚠ Detected existing `code` on PATH:');
|
||||
for (const p of others) console.error(` - ${p}`);
|
||||
if (globalBin) {
|
||||
try {
|
||||
if (existsSync(ourShim)) {
|
||||
unlinkSync(ourShim);
|
||||
console.error(`✓ Skipped global 'code' shim (removed ${ourShim})`);
|
||||
skippedCmds.push({ name: 'code', reason: `existing: ${others[0]}` });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`⚠ Could not remove npm shim '${ourShim}': ${e.message}`);
|
||||
}
|
||||
console.error('→ Use `coder` to run this tool.');
|
||||
} else {
|
||||
console.log('Note: could not determine npm global bin; skipping alias creation.');
|
||||
}
|
||||
} else {
|
||||
// No collision; ensure a 'code' wrapper exists forwarding to 'coder'
|
||||
if (globalBin) {
|
||||
try {
|
||||
const content = isWindows
|
||||
? `@echo off\r\n"%~dp0coder" %*\r\n`
|
||||
: `#!/bin/sh\nexec "$(dirname \"$0\")/coder" "$@"\n`;
|
||||
writeFileSync(ourShim, content);
|
||||
if (!isWindows) chmodSync(ourShim, 0o755);
|
||||
console.log("✓ Created 'code' wrapper -> coder");
|
||||
installedCmds.add('code');
|
||||
} catch (e) {
|
||||
console.log(`⚠ Failed to create 'code' wrapper: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Print summary for npm/pnpm/yarn
|
||||
const list = Array.from(installedCmds).sort().join(', ');
|
||||
console.log(`Commands installed: ${list}`);
|
||||
if (skippedCmds.length) {
|
||||
for (const s of skippedCmds) console.log(`Commands skipped: ${s.name} (${s.reason})`);
|
||||
}
|
||||
// Final friendly usage hint
|
||||
if (installedCmds.has('code')) {
|
||||
console.log("Use 'code' to launch Code.");
|
||||
} else {
|
||||
console.log("Use 'coder' to launch Code.");
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// non-fatal
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('Installation failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env node
|
||||
// Windows-friendly preinstall: proactively free file locks from prior installs
|
||||
// so npm/yarn/pnpm can stage the new package. No-ops on non-Windows.
|
||||
|
||||
import { platform } from 'os';
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync, readdirSync, rmSync, readFileSync, statSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
function isWSL() {
|
||||
if (platform() !== 'linux') return false;
|
||||
try {
|
||||
const rel = readFileSync('/proc/version', 'utf8').toLowerCase();
|
||||
return rel.includes('microsoft') || !!process.env.WSL_DISTRO_NAME;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
const isWin = platform() === 'win32';
|
||||
const wsl = isWSL();
|
||||
const isWinLike = isWin || wsl;
|
||||
|
||||
// Scope: only run for global installs, unless explicitly forced. Allow opt-out.
|
||||
const isGlobal = process.env.npm_config_global === 'true';
|
||||
const force = process.env.CODE_FORCE_PREINSTALL === '1';
|
||||
const skip = process.env.CODE_SKIP_PREINSTALL === '1';
|
||||
if (!isWinLike || skip || (!isGlobal && !force)) process.exit(0);
|
||||
|
||||
function tryExec(cmd, opts = {}) {
|
||||
try { execSync(cmd, { stdio: ['ignore', 'ignore', 'ignore'], shell: true, ...opts }); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// 1) Stop our native binary if it is holding locks. Avoid killing unrelated tools.
|
||||
// Only available on native Windows; skip entirely on WSL to avoid noise.
|
||||
if (isWin) {
|
||||
tryExec('taskkill /IM code-x86_64-pc-windows-msvc.exe /F');
|
||||
}
|
||||
|
||||
// 2) Remove stale staging dirs from previous failed installs under the global
|
||||
// @just-every scope, which npm will reuse (e.g., .code-XXXXX). Remove only
|
||||
// old entries and never the current staging or live package.
|
||||
try {
|
||||
let scopeDir = '';
|
||||
try {
|
||||
const root = execSync('npm root -g', { stdio: ['ignore', 'pipe', 'ignore'], shell: true }).toString().trim();
|
||||
scopeDir = path.join(root, '@just-every');
|
||||
} catch {
|
||||
// Fall back to guessing from this script location: <staging>\..\..\
|
||||
const here = path.resolve(path.dirname(fileURLToPath(import.meta.url)));
|
||||
scopeDir = path.resolve(here, '..');
|
||||
}
|
||||
if (existsSync(scopeDir)) {
|
||||
const now = Date.now();
|
||||
const maxAgeMs = 2 * 60 * 60 * 1000; // 2 hours
|
||||
const currentDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
for (const name of readdirSync(scopeDir)) {
|
||||
if (!name.startsWith('.code-')) continue;
|
||||
const p = path.join(scopeDir, name);
|
||||
if (path.resolve(p) === currentDir) continue; // never remove our current dir
|
||||
try {
|
||||
const st = statSync(p);
|
||||
const age = now - st.mtimeMs;
|
||||
if (age > maxAgeMs) rmSync(p, { recursive: true, force: true });
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,32 @@
|
||||
<#
|
||||
Helper to recover from EBUSY/EPERM during global npm upgrades on Windows.
|
||||
Closes running processes and removes stale package folders.
|
||||
|
||||
Usage (PowerShell):
|
||||
Set-ExecutionPolicy -Scope Process Bypass -Force
|
||||
./codex-cli/scripts/windows-cleanup.ps1
|
||||
#>
|
||||
|
||||
$ErrorActionPreference = 'SilentlyContinue'
|
||||
|
||||
Write-Host "Stopping running Code/Coder processes..."
|
||||
taskkill /IM code-x86_64-pc-windows-msvc.exe /F 2>$null | Out-Null
|
||||
taskkill /IM code.exe /F 2>$null | Out-Null
|
||||
taskkill /IM coder.exe /F 2>$null | Out-Null
|
||||
|
||||
Write-Host "Removing old global package (if present)..."
|
||||
$npmRoot = (& npm root -g).Trim()
|
||||
$pkgPath = Join-Path $npmRoot "@just-every\code"
|
||||
if (Test-Path $pkgPath) {
|
||||
try { Remove-Item -LiteralPath $pkgPath -Recurse -Force -ErrorAction Stop } catch {}
|
||||
}
|
||||
|
||||
Write-Host "Removing temp staging directories (if present)..."
|
||||
Get-ChildItem -LiteralPath (Join-Path $npmRoot "@just-every") -Force -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.Name -like '.code-*' } |
|
||||
ForEach-Object {
|
||||
try { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction Stop } catch {}
|
||||
}
|
||||
|
||||
Write-Host "Cleanup complete. You can now run: npm install -g @just-every/code@latest"
|
||||
|
||||
Reference in New Issue
Block a user