onepatch 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,13 +2,16 @@
2
2
 
3
3
  The [OnePatch](https://onepatch.dev) CLI. Query your telemetry, read and reply to agent chats, and inspect incidents from a terminal or from a coding agent. It speaks to the same MCP endpoint the product serves at `/mcp`, so it has exact functional parity with connecting an MCP client.
4
4
 
5
- Requires [Bun](https://bun.sh).
6
-
7
5
  ```sh
8
- bun install -g onepatch # or: npm install -g onepatch
6
+ npm install -g onepatch # needs Node
7
+ # or, without Node:
8
+ curl -fsSL https://releases.onepatch.dev/install.sh | sh
9
+
9
10
  onepatch login
10
11
  ```
11
12
 
13
+ The CLI is a single self-contained binary (compiled with Bun, so Bun is not needed). `npm install -g onepatch` installs a small Node launcher that fetches the binary for your platform from `https://releases.onepatch.dev/v<version>/` and verifies its SHA-256 against the checksum shipped inside the package; the installer script does the same without Node. Releases carry binaries for macOS (arm64, x64), Linux (x64, arm64), and Windows (x64).
14
+
12
15
  `login` uses a device flow: it prints a URL, you approve in the browser, and credentials land in `~/.config/onepatch/credentials.json` (0600). Tokens refresh automatically.
13
16
 
14
17
  ## Commands
@@ -39,7 +42,7 @@ Pass `-` to read SQL or message text from stdin. `--json` prints raw MCP content
39
42
 
40
43
  ## Updates
41
44
 
42
- The CLI keeps itself current. Once a day, in a detached background process, it asks the npm registry for the latest version; when one exists it reinstalls itself through whichever package manager owns the copy (bun or npm) and prints a one-line notice to stderr. The command you typed is never delayed and never fails because of update machinery. Set `ONEPATCH_NO_UPDATE=1` to disable it, or run `onepatch update` to update on demand. Running from a source checkout never auto-updates.
45
+ The CLI keeps itself current. Once a day, in a detached background process, it asks the npm registry for the latest version; when one exists it either reinstalls itself through the package manager that owns the copy (npm or bun) or, for a standalone binary, downloads the new release, verifies it, and swaps it in place. It prints a one-line notice to stderr. The command you typed is never delayed and never fails because of update machinery. Set `ONEPATCH_NO_UPDATE=1` to disable it, or run `onepatch update` to update on demand. Running from a source checkout never auto-updates. Self-update of a standalone binary isn't available on Windows yet; re-run the installer there.
43
46
 
44
47
  ## Programmatic use
45
48
 
@@ -53,4 +56,4 @@ const digest = await op.chats.start("investigate the p95 spike on /checkout");
53
56
  await op.close();
54
57
  ```
55
58
 
56
- All methods return the same plain-text digests the MCP tools produce. `op.call(name, args)` reaches any tool directly.
59
+ All methods return the same plain-text digests the MCP tools produce. `op.call(name, args)` reaches any tool directly. The programmatic API runs under Bun (it imports the TypeScript sources shipped in the package) and needs `@modelcontextprotocol/sdk` installed alongside; the CLI itself has no dependencies.
@@ -0,0 +1,203 @@
1
+ #!/usr/bin/env node
2
+ // The npm package's entry point. It is a launcher, not the CLI: it finds (or
3
+ // fetches) the prebuilt onepatch binary for this machine and hands over to
4
+ // it. Plain Node, no dependencies, so `npm install -g onepatch` needs nothing
5
+ // but Node. The binary is downloaded from the release host
6
+ // (https://releases.onepatch.dev/v<version>/) that matches this package's
7
+ // version and verified against the SHA-256 recorded in checksums.json at
8
+ // publish time, so npm's integrity check on this package extends to the
9
+ // binary it fetches.
10
+ "use strict";
11
+
12
+ const { spawnSync, spawn } = require("node:child_process");
13
+ const crypto = require("node:crypto");
14
+ const fs = require("node:fs");
15
+ const os = require("node:os");
16
+ const path = require("node:path");
17
+
18
+ const root = path.join(__dirname, "..");
19
+ const pkg = require(path.join(root, "package.json"));
20
+ const RELEASE_BASE = process.env.ONEPATCH_RELEASE_BASE || "https://releases.onepatch.dev";
21
+
22
+ function releaseTarget(platform = process.platform, arch = process.arch) {
23
+ const osName =
24
+ platform === "darwin"
25
+ ? "darwin"
26
+ : platform === "linux"
27
+ ? "linux"
28
+ : platform === "win32"
29
+ ? "windows"
30
+ : null;
31
+ if (osName === null || (arch !== "x64" && arch !== "arm64")) return null;
32
+ if (osName === "windows" && arch !== "x64") return null;
33
+ return `${osName}-${arch}`;
34
+ }
35
+
36
+ function assetName(target) {
37
+ return `onepatch-${target}.tar.gz`;
38
+ }
39
+
40
+ function assetUrl(version, target, base = RELEASE_BASE) {
41
+ return `${base}/v${version}/${assetName(target)}`;
42
+ }
43
+
44
+ function binaryName(target) {
45
+ return target.startsWith("windows") ? "onepatch.exe" : "onepatch";
46
+ }
47
+
48
+ function sha256(buffer) {
49
+ return crypto.createHash("sha256").update(buffer).digest("hex");
50
+ }
51
+
52
+ function readChecksums() {
53
+ try {
54
+ return JSON.parse(fs.readFileSync(path.join(root, "checksums.json"), "utf8"));
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ // Where the binary lives once fetched. The package's own vendor/ directory is
61
+ // preferred (postinstall fills it, uninstall removes it); a per-user cache is
62
+ // the fallback when the package directory isn't writable at run time.
63
+ function vendorDir() {
64
+ return path.join(root, "vendor");
65
+ }
66
+ function cacheDir() {
67
+ const base = process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache");
68
+ return path.join(base, "onepatch", "bin", pkg.version);
69
+ }
70
+
71
+ function findBinary(target) {
72
+ if (process.env.ONEPATCH_BIN) return process.env.ONEPATCH_BIN;
73
+ for (const dir of [vendorDir(), cacheDir()]) {
74
+ const candidate = path.join(dir, binaryName(target));
75
+ if (fs.existsSync(candidate)) return candidate;
76
+ }
77
+ return null;
78
+ }
79
+
80
+ async function download(url) {
81
+ const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(120_000) });
82
+ if (!res.ok) throw new Error(`${url} answered ${res.status}`);
83
+ return Buffer.from(await res.arrayBuffer());
84
+ }
85
+
86
+ // Fetch, verify, and unpack the binary into `dir`. Staged in a sibling
87
+ // directory and renamed in, so a concurrent launcher never sees a half-written
88
+ // file.
89
+ async function fetchBinary(target, dir, { quiet } = {}) {
90
+ const checksums = readChecksums();
91
+ const expected = checksums?.[target];
92
+ if (!expected) {
93
+ throw new Error(
94
+ `this onepatch package carries no checksum for ${target}; refusing to download`,
95
+ );
96
+ }
97
+ if (!quiet) process.stderr.write(`Downloading onepatch ${pkg.version} for ${target}…\n`);
98
+ const tarball = await download(assetUrl(pkg.version, target));
99
+ const actual = sha256(tarball);
100
+ if (actual !== expected) {
101
+ throw new Error(
102
+ `checksum mismatch for ${assetName(target)}: expected ${expected}, got ${actual}`,
103
+ );
104
+ }
105
+ fs.mkdirSync(dir, { recursive: true });
106
+ const stage = fs.mkdtempSync(path.join(dir, ".stage-"));
107
+ try {
108
+ const archive = path.join(stage, assetName(target));
109
+ fs.writeFileSync(archive, tarball);
110
+ const tar = spawnSync("tar", ["-xzf", archive, "-C", stage], { stdio: "ignore" });
111
+ if (tar.status !== 0) throw new Error("tar failed to extract the onepatch archive");
112
+ const bin = path.join(stage, binaryName(target));
113
+ fs.chmodSync(bin, 0o755);
114
+ fs.renameSync(bin, path.join(dir, binaryName(target)));
115
+ } finally {
116
+ fs.rmSync(stage, { recursive: true, force: true });
117
+ }
118
+ return path.join(dir, binaryName(target));
119
+ }
120
+
121
+ async function ensureBinary(target, opts) {
122
+ const found = findBinary(target);
123
+ if (found) return found;
124
+ try {
125
+ return await fetchBinary(target, vendorDir(), opts);
126
+ } catch (err) {
127
+ if (err && err.code !== "EACCES" && err.code !== "EPERM" && err.code !== "EROFS") throw err;
128
+ return await fetchBinary(target, cacheDir(), opts);
129
+ }
130
+ }
131
+
132
+ function isSourceCheckout() {
133
+ return (
134
+ fs.existsSync(path.join(root, "src", "cli.ts")) &&
135
+ !fs.existsSync(path.join(root, "checksums.json"))
136
+ );
137
+ }
138
+
139
+ async function main(argv) {
140
+ const args = argv.slice(2);
141
+
142
+ // npm's postinstall: prefetch so the first real invocation is instant.
143
+ // Never fail the install over it — the launcher fetches on demand anyway.
144
+ if (args[0] === "--postinstall") {
145
+ if (isSourceCheckout()) return 0;
146
+ const target = releaseTarget();
147
+ if (target === null) return 0;
148
+ try {
149
+ await ensureBinary(target, { quiet: true });
150
+ } catch (err) {
151
+ process.stderr.write(
152
+ `onepatch: could not prefetch the binary (${err.message}); it will download on first use.\n`,
153
+ );
154
+ }
155
+ return 0;
156
+ }
157
+
158
+ // A developer's checkout: run the sources under Bun, like before.
159
+ if (isSourceCheckout()) {
160
+ const run = spawnSync("bun", [path.join(root, "src", "cli.ts"), ...args], { stdio: "inherit" });
161
+ return run.status === null ? 1 : run.status;
162
+ }
163
+
164
+ const target = releaseTarget();
165
+ if (target === null) {
166
+ process.stderr.write(`onepatch: no prebuilt binary for ${process.platform}/${process.arch}.\n`);
167
+ return 1;
168
+ }
169
+
170
+ let bin = findBinary(target);
171
+ if (bin === null) {
172
+ // Hooks run on every agent prompt and must never wait on a download:
173
+ // fetch in the background and inject nothing this time.
174
+ if (args[0] === "hook") {
175
+ spawn(process.execPath, [__filename, "--postinstall"], {
176
+ detached: true,
177
+ stdio: "ignore",
178
+ }).unref();
179
+ return 0;
180
+ }
181
+ bin = await ensureBinary(target);
182
+ }
183
+
184
+ const run = spawnSync(bin, args, { stdio: "inherit" });
185
+ if (run.error) throw run.error;
186
+ if (run.signal) {
187
+ process.kill(process.pid, run.signal);
188
+ return 1;
189
+ }
190
+ return run.status === null ? 1 : run.status;
191
+ }
192
+
193
+ module.exports = { releaseTarget, assetName, assetUrl, binaryName, sha256 };
194
+
195
+ if (require.main === module) {
196
+ main(process.argv).then(
197
+ (code) => process.exit(code),
198
+ (err) => {
199
+ process.stderr.write(`onepatch: ${err?.message ?? err}\n`);
200
+ process.exit(1);
201
+ },
202
+ );
203
+ }
package/checksums.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "darwin-arm64": "f53d824326e0e26746d65e63ebaf300c730841da8b7ebedc3b487af8160d9ae7",
3
+ "darwin-x64": "1779984fb3a998cd5de26b2ffd6c0cac0c9733f7670e1dc488059f53f5a95ecc",
4
+ "linux-arm64": "51e22bb3b290e47482efdbdc0ad3aabd79218c6858dc552c49d3e67ea787114c",
5
+ "linux-x64": "4c963f164f1929fe5e475c4d59614179faa43566d42088875554025b32ce58cf",
6
+ "windows-x64": "e6d62ea9e99ef951fedacd75987605486a8ff04fa76d7b176c7df45d700b76ec"
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "onepatch",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "OnePatch CLI: query your telemetry, chats, and incidents from a terminal or a coding agent",
5
5
  "license": "MIT",
6
6
  "homepage": "https://onepatch.dev",
@@ -11,34 +11,58 @@
11
11
  "bugs": {
12
12
  "url": "https://github.com/1patch/cli/issues"
13
13
  },
14
- "keywords": ["onepatch", "observability", "sre", "cli", "mcp", "opentelemetry"],
14
+ "keywords": [
15
+ "onepatch",
16
+ "observability",
17
+ "sre",
18
+ "cli",
19
+ "mcp",
20
+ "opentelemetry"
21
+ ],
15
22
  "type": "module",
16
23
  "bin": {
17
- "onepatch": "./src/cli.ts"
24
+ "onepatch": "./bin/onepatch.cjs"
18
25
  },
19
26
  "exports": {
20
27
  ".": "./src/index.ts"
21
28
  },
22
- "files": ["src", "README.md", "LICENSE"],
29
+ "files": [
30
+ "bin",
31
+ "src",
32
+ "!src/*.test.ts",
33
+ "checksums.json",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
23
37
  "engines": {
24
- "bun": ">=1.1.0"
38
+ "node": ">=18"
25
39
  },
26
40
  "publishConfig": {
27
41
  "access": "public"
28
42
  },
29
43
  "scripts": {
44
+ "postinstall": "node bin/onepatch.cjs --postinstall",
45
+ "build": "scripts/build-binaries.sh",
46
+ "mirror": "scripts/mirror-plugins.sh",
30
47
  "typecheck": "tsgo --noEmit -p tsconfig.json",
31
48
  "test": "bun test",
32
49
  "fmt": "biome check --write .",
33
- "check": "biome ci . && bun run typecheck && bun test"
34
- },
35
- "dependencies": {
36
- "@modelcontextprotocol/sdk": "^1.29.0"
50
+ "check": "biome ci . && bun run typecheck && bun test",
51
+ "mirror": "scripts/mirror-plugins.sh"
37
52
  },
38
53
  "devDependencies": {
39
54
  "@biomejs/biome": "^2.5.8",
40
55
  "@types/bun": "^1.3.14",
41
56
  "@typescript/native-preview": "^7.0.0-dev.20260506.1",
42
- "typescript": "^5.5.0"
57
+ "typescript": "^5.5.0",
58
+ "@modelcontextprotocol/sdk": "^1.29.0"
59
+ },
60
+ "peerDependencies": {
61
+ "@modelcontextprotocol/sdk": "^1.29.0"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "@modelcontextprotocol/sdk": {
65
+ "optional": true
66
+ }
43
67
  }
44
68
  }
package/src/hook.ts CHANGED
@@ -8,6 +8,7 @@ import { readFileSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { OnepatchClient } from "./client";
10
10
  import { configDir, ensureConfigDir, loadCredentials } from "./credentials";
11
+ import { selfCommand } from "./runtime";
11
12
 
12
13
  export const HOOK_CACHE_TTL_MS = 5 * 60 * 1000;
13
14
  // A refresh normally lands in seconds; this only bounds how long a failed one
@@ -97,7 +98,7 @@ export async function runHook(api: string, event: string | undefined, refresh: b
97
98
  if (action.refresh) {
98
99
  writeHookCache({ ...readHookCache(), refreshStartedAt: Date.now() });
99
100
  Bun.spawn({
100
- cmd: [process.execPath, join(import.meta.dir, "cli.ts"), "hook", "--refresh", "--api", api],
101
+ cmd: selfCommand(["hook", "--refresh", "--api", api]),
101
102
  stdin: "ignore",
102
103
  stdout: "ignore",
103
104
  stderr: "ignore",
package/src/runtime.ts ADDED
@@ -0,0 +1,35 @@
1
+ // Where this process's code lives and how to re-invoke it. The CLI ships two
2
+ // ways: as a compiled Bun executable (the binary users actually run) and as
3
+ // TypeScript sources under Bun (development, and the programmatic API). Every
4
+ // place that needs "this program again" or "this program's version" asks here
5
+ // instead of assuming a file layout.
6
+ import { realpathSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import pkg from "../package.json" with { type: "json" };
9
+
10
+ export const VERSION: string = pkg.version;
11
+
12
+ // Bun compiled executables mount their bundled sources on a virtual filesystem
13
+ // (`/$bunfs/` on POSIX, `B:\~BUN\` on Windows); nothing else ever lives there.
14
+ export function isCompiled(dir: string = import.meta.dir): boolean {
15
+ return dir.startsWith("/$bunfs/") || dir.includes("~BUN");
16
+ }
17
+
18
+ // The argv that re-runs this program with `args`, detached or not.
19
+ export function selfCommand(args: string[], compiled: boolean = isCompiled()): string[] {
20
+ return compiled
21
+ ? [process.execPath, ...args]
22
+ : [process.execPath, join(import.meta.dir, "cli.ts"), ...args];
23
+ }
24
+
25
+ // The path that decides who owns this install: the binary itself when
26
+ // compiled, otherwise the package directory the sources live in. Symlinks
27
+ // (bin shims, ~/.local/bin links) are resolved so the answer is physical.
28
+ export function installRoot(): string {
29
+ const raw = isCompiled() ? process.execPath : join(import.meta.dir, "..");
30
+ try {
31
+ return realpathSync(raw);
32
+ } catch {
33
+ return raw;
34
+ }
35
+ }
package/src/update.ts CHANGED
@@ -2,35 +2,34 @@
2
2
  // actually typed never waits on update machinery. Each invocation reads one
3
3
  // small cached JSON file; a stale cache spawns a detached background process
4
4
  // to refresh it from the npm registry, and a cache that already names a newer
5
- // version spawns a detached reinstall via whichever package manager owns this
6
- // copy. Either way the foreground command proceeds immediately, and the next
7
- // invocation runs the new code.
8
- import { readFileSync, realpathSync, writeFileSync } from "node:fs";
5
+ // version spawns a detached update. Either way the foreground command proceeds
6
+ // immediately, and the next invocation runs the new code.
7
+ //
8
+ // How the update lands depends on who owns this copy: a package manager (bun
9
+ // or npm) reinstalls the package, which fetches the matching binary; a
10
+ // standalone binary (curl installer, or a copied file) replaces itself in
11
+ // place from the release host, after checking the tarball's SHA-256.
12
+ //
13
+ // The release host (https://releases.onepatch.dev) is the one source of
14
+ // truth for "what is released": `latest` is written last by the publish job,
15
+ // after both the binaries and the npm package exist, so a version it names
16
+ // is always fully installable by every kind.
17
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
9
18
  import { homedir } from "node:os";
10
- import { join, sep } from "node:path";
19
+ import { dirname, join, sep } from "node:path";
11
20
  import { configDir, ensureConfigDir } from "./credentials";
21
+ import { installRoot, isCompiled, selfCommand, VERSION } from "./runtime";
12
22
 
13
23
  export const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
14
24
  // A spawned install normally lands in seconds; this only bounds how long a
15
25
  // *failed* install suppresses retries (and dogpiles from parallel invocations).
16
26
  export const INSTALL_RETRY_MS = 15 * 60 * 1000;
17
27
 
18
- const packageRoot = (() => {
19
- // The bin shim is a symlink into the installed package; resolve it so the
20
- // path we inspect is where the package physically lives.
21
- const raw = join(import.meta.dir, "..");
22
- try {
23
- return realpathSync(raw);
24
- } catch {
25
- return raw;
26
- }
27
- })();
28
+ // Overridable so a release can be rehearsed end-to-end against a local server.
29
+ export const RELEASE_BASE = process.env.ONEPATCH_RELEASE_BASE ?? "https://releases.onepatch.dev";
28
30
 
29
31
  export function currentVersion(): string {
30
- const pkg = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8")) as {
31
- version?: unknown;
32
- };
33
- return typeof pkg.version === "string" ? pkg.version : "0.0.0";
32
+ return VERSION;
34
33
  }
35
34
 
36
35
  // Plain x.y.z compare; a prerelease suffix sorts below its release.
@@ -53,24 +52,65 @@ export function compareVersions(a: string, b: string): number {
53
52
  return pa.pre < pb.pre ? -1 : 1;
54
53
  }
55
54
 
56
- export type InstallKind = "bun" | "npm";
55
+ export type InstallKind = "bun" | "npm" | "binary";
57
56
 
58
- // Which package manager owns this copy — decided from where the package
59
- // physically lives, because that's also the only place the answer is honest.
60
- // null means a source checkout (dev), where auto-update must stay away.
61
- export function detectInstallKind(root: string = packageRoot): InstallKind | null {
57
+ // Who owns this copy — decided from where it physically lives, because that's
58
+ // also the only place the answer is honest. A package-manager path wins even
59
+ // for a compiled binary (the launcher's vendored copy), so the manager stays
60
+ // in charge of it. null means a source checkout (dev), where auto-update must
61
+ // stay away.
62
+ export function detectInstallKind(
63
+ root: string = installRoot(),
64
+ compiled: boolean = isCompiled(),
65
+ ): InstallKind | null {
62
66
  const bunInstall = process.env.BUN_INSTALL ?? join(homedir(), ".bun");
63
67
  if (root.startsWith(bunInstall + sep) || root.split(sep).includes(".bun")) return "bun";
64
68
  if (root.split(sep).includes("node_modules")) return "npm";
65
- return null;
69
+ return compiled ? "binary" : null;
66
70
  }
67
71
 
68
- export function installCommand(kind: InstallKind, version: string): string[] {
72
+ export function installCommand(kind: "bun" | "npm", version: string): string[] {
69
73
  return kind === "bun"
70
74
  ? ["bun", "add", "-g", `onepatch@${version}`]
71
75
  : ["npm", "install", "-g", `onepatch@${version}`];
72
76
  }
73
77
 
78
+ // The `<os>-<arch>` suffix of the release asset built for this machine; null
79
+ // when no prebuilt binary exists for it.
80
+ export function releaseTarget(
81
+ platform: string = process.platform,
82
+ arch: string = process.arch,
83
+ ): string | null {
84
+ const os =
85
+ platform === "darwin"
86
+ ? "darwin"
87
+ : platform === "linux"
88
+ ? "linux"
89
+ : platform === "win32"
90
+ ? "windows"
91
+ : null;
92
+ if (os === null || (arch !== "x64" && arch !== "arm64")) return null;
93
+ if (os === "windows" && arch !== "x64") return null;
94
+ return `${os}-${arch}`;
95
+ }
96
+
97
+ export function assetName(target: string): string {
98
+ return `onepatch-${target}.tar.gz`;
99
+ }
100
+
101
+ export function assetUrl(version: string, target: string, base: string = RELEASE_BASE): string {
102
+ return `${base}/v${version}/${assetName(target)}`;
103
+ }
104
+
105
+ // The hex digest recorded for `filename` in a `sha256sum`-style listing.
106
+ export function parseSha256Sums(listing: string, filename: string): string | null {
107
+ for (const line of listing.split("\n")) {
108
+ const m = /^([0-9a-f]{64})\s+\*?(.+)$/.exec(line.trim());
109
+ if (m && m[2] === filename) return m[1] ?? null;
110
+ }
111
+ return null;
112
+ }
113
+
74
114
  export type UpdateState = {
75
115
  checkedAt?: number;
76
116
  latest?: string;
@@ -113,18 +153,62 @@ export function decideUpdateAction(state: UpdateState, current: string, now: num
113
153
  }
114
154
 
115
155
  export async function fetchLatestVersion(fetchImpl: typeof fetch = fetch): Promise<string> {
116
- const res = await fetchImpl("https://registry.npmjs.org/onepatch/latest", {
156
+ const res = await fetchImpl(`${RELEASE_BASE}/latest`, {
117
157
  headers: { accept: "application/json" },
118
158
  signal: AbortSignal.timeout(10_000),
119
159
  });
120
- if (!res.ok) throw new Error(`npm registry answered ${res.status} for onepatch@latest`);
160
+ if (!res.ok) throw new Error(`release host answered ${res.status} for latest`);
121
161
  const doc = (await res.json()) as { version?: unknown };
122
162
  if (typeof doc.version !== "string") {
123
- throw new Error("npm registry returned a manifest without a version");
163
+ throw new Error("release host returned a latest document without a version");
124
164
  }
125
165
  return doc.version;
126
166
  }
127
167
 
168
+ async function fetchOk(url: string): Promise<Response> {
169
+ const res = await fetch(url, { signal: AbortSignal.timeout(120_000) });
170
+ if (!res.ok) throw new Error(`${url} answered ${res.status}`);
171
+ return res;
172
+ }
173
+
174
+ // Replace the running standalone binary with the released `version`. The
175
+ // tarball is checked against the release's SHA256SUMS before anything on disk
176
+ // changes, staged next to the binary (same filesystem, so the final rename is
177
+ // atomic), and swapped in with one rename. A process already running keeps
178
+ // its old inode; the next invocation gets the new file.
179
+ export async function replaceBinary(version: string): Promise<void> {
180
+ const target = releaseTarget();
181
+ if (target === null) {
182
+ throw new Error(`no prebuilt onepatch binary for ${process.platform}/${process.arch}`);
183
+ }
184
+ if (target.startsWith("windows")) {
185
+ throw new Error("self-update isn't available on Windows yet; re-run the installer instead");
186
+ }
187
+ const sums = await (await fetchOk(`${RELEASE_BASE}/v${version}/SHA256SUMS`)).text();
188
+ const expected = parseSha256Sums(sums, assetName(target));
189
+ if (expected === null) throw new Error(`release v${version} has no checksum for ${target}`);
190
+ const tarball = new Uint8Array(await (await fetchOk(assetUrl(version, target))).arrayBuffer());
191
+ const actual = new Bun.CryptoHasher("sha256").update(tarball).digest("hex");
192
+ if (actual !== expected) {
193
+ throw new Error(
194
+ `checksum mismatch for ${assetName(target)}: expected ${expected}, got ${actual}`,
195
+ );
196
+ }
197
+ const real = installRoot();
198
+ const stage = join(dirname(real), `.onepatch-update-${process.pid}`);
199
+ mkdirSync(stage, { recursive: true });
200
+ try {
201
+ const archive = join(stage, assetName(target));
202
+ writeFileSync(archive, tarball);
203
+ const tar = Bun.spawn({ cmd: ["tar", "-xzf", archive, "-C", stage], stdout: "ignore" });
204
+ if ((await tar.exited) !== 0) throw new Error("tar failed to extract the release archive");
205
+ chmodSync(join(stage, "onepatch"), 0o755);
206
+ renameSync(join(stage, "onepatch"), real);
207
+ } finally {
208
+ rmSync(stage, { recursive: true, force: true });
209
+ }
210
+ }
211
+
128
212
  function spawnDetached(cmd: string[]): void {
129
213
  Bun.spawn({ cmd, stdin: "ignore", stdout: "ignore", stderr: "ignore" }).unref();
130
214
  }
@@ -141,7 +225,9 @@ export function maybeAutoUpdate(): void {
141
225
  if (action.kind === "install") {
142
226
  // Stamp before spawning so parallel invocations don't dogpile.
143
227
  writeUpdateState({ ...state, installStartedAt: Date.now() });
144
- spawnDetached(installCommand(kind, action.latest));
228
+ spawnDetached(
229
+ kind === "binary" ? selfCommand(["update"]) : installCommand(kind, action.latest),
230
+ );
145
231
  console.error(
146
232
  `onepatch ${currentVersion()} → ${action.latest} is installing in the background ` +
147
233
  "(ONEPATCH_NO_UPDATE=1 disables this).",
@@ -149,7 +235,7 @@ export function maybeAutoUpdate(): void {
149
235
  } else if (action.kind === "check") {
150
236
  // Refresh the cache off-process: `onepatch update --check` fetches the
151
237
  // registry and writes the state file, costing this invocation nothing.
152
- spawnDetached([process.execPath, join(packageRoot, "src", "cli.ts"), "update", "--check"]);
238
+ spawnDetached(selfCommand(["update", "--check"]));
153
239
  }
154
240
  } catch {
155
241
  // Auto-update is strictly best-effort; the user's command always wins.
@@ -177,11 +263,16 @@ export async function runUpdate(opts: { checkOnly: boolean }): Promise<void> {
177
263
  );
178
264
  return;
179
265
  }
180
- const cmd = installCommand(kind, latest);
181
- console.log(`Updating onepatch ${current} → ${latest} (${cmd.join(" ")})…`);
182
- const proc = Bun.spawn({ cmd, stdin: "ignore", stdout: "inherit", stderr: "inherit" });
183
- const code = await proc.exited;
184
- if (code !== 0) throw new Error(`${cmd[0]} exited with code ${code}`);
266
+ if (kind === "binary") {
267
+ console.log(`Updating onepatch ${current} → ${latest} (${installRoot()})…`);
268
+ await replaceBinary(latest);
269
+ } else {
270
+ const cmd = installCommand(kind, latest);
271
+ console.log(`Updating onepatch ${current} → ${latest} (${cmd.join(" ")})…`);
272
+ const proc = Bun.spawn({ cmd, stdin: "ignore", stdout: "inherit", stderr: "inherit" });
273
+ const code = await proc.exited;
274
+ if (code !== 0) throw new Error(`${cmd[0]} exited with code ${code}`);
275
+ }
185
276
  writeUpdateState({ checkedAt: Date.now(), latest });
186
277
  console.log(`onepatch ${latest} installed.`);
187
278
  }
@@ -1,49 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
- import { mkdtempSync, rmSync, statSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import {
6
- credentialsPath,
7
- deleteCredentials,
8
- loadCredentials,
9
- saveCredentials,
10
- } from "./credentials";
11
-
12
- const CREDS = {
13
- clientId: "client_01TEST",
14
- accessToken: "at",
15
- refreshToken: "rt",
16
- email: "dev@example.com",
17
- };
18
-
19
- let dir: string;
20
-
21
- beforeEach(() => {
22
- dir = mkdtempSync(join(tmpdir(), "onepatch-cli-test-"));
23
- process.env.ONEPATCH_CONFIG_DIR = dir;
24
- });
25
-
26
- afterEach(() => {
27
- delete process.env.ONEPATCH_CONFIG_DIR;
28
- rmSync(dir, { recursive: true, force: true });
29
- });
30
-
31
- describe("credential store", () => {
32
- test("round-trips per API base and deletes cleanly", () => {
33
- expect(loadCredentials("https://a.example")).toBeNull();
34
- saveCredentials("https://a.example", CREDS);
35
- saveCredentials("https://b.example", { ...CREDS, email: "other@example.com" });
36
- expect(loadCredentials("https://a.example")?.email).toBe("dev@example.com");
37
- expect(loadCredentials("https://b.example")?.email).toBe("other@example.com");
38
- expect(deleteCredentials("https://a.example")).toBe(true);
39
- expect(loadCredentials("https://a.example")).toBeNull();
40
- expect(loadCredentials("https://b.example")?.email).toBe("other@example.com");
41
- expect(deleteCredentials("https://a.example")).toBe(false);
42
- });
43
-
44
- test("credential file is written 0600", () => {
45
- saveCredentials("https://a.example", CREDS);
46
- const mode = statSync(credentialsPath()).mode & 0o777;
47
- expect(mode).toBe(0o600);
48
- });
49
- });
package/src/hook.test.ts DELETED
@@ -1,67 +0,0 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { buildContextLine, decideHookAction, HOOK_CACHE_TTL_MS } from "./hook";
3
-
4
- // Verbatim shape of the CLI's list_incidents digest.
5
- const DIGEST = `86 open incidents · newest activity first
6
- 115 closed/folded incidents hidden — scope: "all" lists them
7
- showing the newest 5 — raise limit for older
8
-
9
- INC-193 · unjudged · waiting on time · false alarm · A stale staging deploy failure is still flagged · updated 2026-09-01T15:04Z
10
- INC-183 · unjudged · waiting on human · Search intermittently degraded · updated 2026-09-01T14:58Z
11
- INC-192 · P3 · waiting on human · false alarm · Stale boot-time probe · updated 2026-09-01T12:51Z
12
- incident-3de5a4e4 · no incident document yet (read_chat incident-3de5a4e4) · updated 2026-08-30T05:26Z`;
13
-
14
- describe("buildContextLine", () => {
15
- test("keeps the count and the two newest INC rows, drops timestamps", () => {
16
- const line = buildContextLine(DIGEST);
17
- expect(line).toContain("86 open incidents");
18
- expect(line).toContain(
19
- "INC-193 · unjudged · waiting on time · false alarm · A stale staging deploy failure is still flagged",
20
- );
21
- expect(line).toContain("INC-183");
22
- expect(line).not.toContain("INC-192");
23
- expect(line).not.toContain("updated 2026");
24
- expect(line).not.toContain("incident-3de5a4e4");
25
- expect(line.split("\n")).toHaveLength(1);
26
- });
27
-
28
- test("injects nothing when no incidents are open", () => {
29
- expect(buildContextLine("0 open incidents · newest activity first\n")).toBe("");
30
- expect(buildContextLine("")).toBe("");
31
- });
32
-
33
- test("singularizes a lone incident", () => {
34
- const line = buildContextLine(
35
- "1 open incident · newest\n\nINC-7 · P1 · waiting on agent · x · updated now",
36
- );
37
- expect(line).toContain("1 open incident —");
38
- });
39
- });
40
-
41
- describe("decideHookAction", () => {
42
- const now = 1_000_000_000_000;
43
-
44
- test("fresh cache: emit, no refresh", () => {
45
- const a = decideHookAction({ fetchedAt: now - 1000, line: "[onepatch] hi" }, now);
46
- expect(a).toEqual({ emit: "[onepatch] hi", refresh: false });
47
- });
48
-
49
- test("stale cache: emit the stale line AND refresh", () => {
50
- const a = decideHookAction({ fetchedAt: now - HOOK_CACHE_TTL_MS - 1, line: "old" }, now);
51
- expect(a).toEqual({ emit: "old", refresh: true });
52
- });
53
-
54
- test("empty cache: emit nothing, refresh", () => {
55
- expect(decideHookAction({}, now)).toEqual({ emit: "", refresh: true });
56
- });
57
-
58
- test("refresh already in flight is not re-spawned", () => {
59
- const a = decideHookAction({ refreshStartedAt: now - 1000 }, now);
60
- expect(a.refresh).toBe(false);
61
- });
62
-
63
- test("a stuck refresh stops suppressing after the retry window", () => {
64
- const a = decideHookAction({ refreshStartedAt: now - 10 * 60 * 1000 }, now);
65
- expect(a.refresh).toBe(true);
66
- });
67
- });
@@ -1,67 +0,0 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { ensureCodexMcpServer, ensureCursorMcpServer } from "./install";
3
-
4
- const URL = "https://app.onepatch.dev/mcp";
5
-
6
- describe("ensureCodexMcpServer", () => {
7
- test("appends a block to an empty config", () => {
8
- const r = ensureCodexMcpServer("", URL);
9
- expect(r.changed).toBe(true);
10
- expect(r.text).toBe(`[mcp_servers.onepatch]\nurl = "${URL}"\n`);
11
- });
12
-
13
- test("separates the block from existing content with a blank line", () => {
14
- const r = ensureCodexMcpServer('model = "gpt-5"\n', URL);
15
- expect(r.changed).toBe(true);
16
- expect(r.text).toBe(`model = "gpt-5"\n\n[mcp_servers.onepatch]\nurl = "${URL}"\n`);
17
- });
18
-
19
- test("adds a newline when the file lacks a trailing one", () => {
20
- const r = ensureCodexMcpServer('model = "gpt-5"', URL);
21
- expect(r.text.startsWith('model = "gpt-5"\n\n[')).toBe(true);
22
- });
23
-
24
- test("is idempotent", () => {
25
- const once = ensureCodexMcpServer("", URL);
26
- const twice = ensureCodexMcpServer(once.text, URL);
27
- expect(twice.changed).toBe(false);
28
- expect(twice.text).toBe(once.text);
29
- });
30
-
31
- test("respects an existing block even with different settings", () => {
32
- const existing = '[mcp_servers.onepatch]\nurl = "https://elsewhere.example/mcp"\n';
33
- expect(ensureCodexMcpServer(existing, URL).changed).toBe(false);
34
- });
35
-
36
- test("does not match other servers or commented blocks", () => {
37
- const other = '[mcp_servers.other]\nurl = "x"\n# [mcp_servers.onepatch] disabled\n';
38
- expect(ensureCodexMcpServer(other, URL).changed).toBe(true);
39
- });
40
- });
41
-
42
- describe("ensureCursorMcpServer", () => {
43
- test("creates the document when the file is missing", () => {
44
- const r = ensureCursorMcpServer(null, URL);
45
- expect(r.changed).toBe(true);
46
- expect(JSON.parse(r.text)).toEqual({ mcpServers: { onepatch: { url: URL } } });
47
- });
48
-
49
- test("preserves existing servers and unknown top-level keys", () => {
50
- const existing = JSON.stringify({ mcpServers: { foo: { command: "foo" } }, other: 1 });
51
- const r = ensureCursorMcpServer(existing, URL);
52
- expect(r.changed).toBe(true);
53
- expect(JSON.parse(r.text)).toEqual({
54
- mcpServers: { foo: { command: "foo" }, onepatch: { url: URL } },
55
- other: 1,
56
- });
57
- });
58
-
59
- test("is idempotent, even against a user-customized entry", () => {
60
- const existing = JSON.stringify({ mcpServers: { onepatch: { url: "https://custom/mcp" } } });
61
- expect(ensureCursorMcpServer(existing, URL).changed).toBe(false);
62
- });
63
-
64
- test("refuses to clobber an unparseable file", () => {
65
- expect(() => ensureCursorMcpServer("{not json", URL)).toThrow(/not valid JSON/);
66
- });
67
- });
@@ -1,128 +0,0 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import {
5
- CHECK_INTERVAL_MS,
6
- compareVersions,
7
- decideUpdateAction,
8
- detectInstallKind,
9
- fetchLatestVersion,
10
- INSTALL_RETRY_MS,
11
- installCommand,
12
- } from "./update";
13
-
14
- describe("compareVersions", () => {
15
- test("orders plain versions", () => {
16
- expect(compareVersions("0.2.0", "0.3.0")).toBeLessThan(0);
17
- expect(compareVersions("0.3.0", "0.2.9")).toBeGreaterThan(0);
18
- expect(compareVersions("1.0.0", "0.99.99")).toBeGreaterThan(0);
19
- expect(compareVersions("0.2.0", "0.2.0")).toBe(0);
20
- });
21
-
22
- test("compares numerically, not lexically", () => {
23
- expect(compareVersions("0.10.0", "0.9.0")).toBeGreaterThan(0);
24
- });
25
-
26
- test("prerelease sorts below its release", () => {
27
- expect(compareVersions("1.0.0-beta.1", "1.0.0")).toBeLessThan(0);
28
- expect(compareVersions("1.0.0", "1.0.0-rc.2")).toBeGreaterThan(0);
29
- });
30
-
31
- test("tolerates short versions", () => {
32
- expect(compareVersions("1.0", "1.0.0")).toBe(0);
33
- expect(compareVersions("1", "1.0.1")).toBeLessThan(0);
34
- });
35
- });
36
-
37
- describe("decideUpdateAction", () => {
38
- const now = 1_700_000_000_000;
39
-
40
- test("empty state asks for a background check", () => {
41
- expect(decideUpdateAction({}, "0.2.0", now)).toEqual({ kind: "check" });
42
- });
43
-
44
- test("fresh state with no newer version does nothing", () => {
45
- expect(decideUpdateAction({ checkedAt: now - 1000, latest: "0.2.0" }, "0.2.0", now)).toEqual({
46
- kind: "none",
47
- });
48
- });
49
-
50
- test("stale state asks for a background check", () => {
51
- expect(
52
- decideUpdateAction({ checkedAt: now - CHECK_INTERVAL_MS - 1, latest: "0.2.0" }, "0.2.0", now),
53
- ).toEqual({ kind: "check" });
54
- });
55
-
56
- test("known newer version installs", () => {
57
- expect(decideUpdateAction({ checkedAt: now, latest: "0.3.0" }, "0.2.0", now)).toEqual({
58
- kind: "install",
59
- latest: "0.3.0",
60
- });
61
- });
62
-
63
- test("an in-flight install suppresses re-spawning", () => {
64
- expect(
65
- decideUpdateAction(
66
- { checkedAt: now, latest: "0.3.0", installStartedAt: now - 1000 },
67
- "0.2.0",
68
- now,
69
- ),
70
- ).toEqual({ kind: "none" });
71
- });
72
-
73
- test("a failed install retries after the guard window", () => {
74
- expect(
75
- decideUpdateAction(
76
- { checkedAt: now, latest: "0.3.0", installStartedAt: now - INSTALL_RETRY_MS - 1 },
77
- "0.2.0",
78
- now,
79
- ),
80
- ).toEqual({ kind: "install", latest: "0.3.0" });
81
- });
82
-
83
- test("a cached latest older than current never installs", () => {
84
- expect(decideUpdateAction({ checkedAt: now, latest: "0.1.0" }, "0.2.0", now)).toEqual({
85
- kind: "none",
86
- });
87
- });
88
- });
89
-
90
- describe("detectInstallKind", () => {
91
- test("bun global install", () => {
92
- expect(
93
- detectInstallKind(join(homedir(), ".bun", "install", "global", "node_modules", "onepatch")),
94
- ).toBe("bun");
95
- });
96
-
97
- test("npm global install", () => {
98
- expect(detectInstallKind("/usr/local/lib/node_modules/onepatch")).toBe("npm");
99
- });
100
-
101
- test("source checkout is not updatable", () => {
102
- expect(detectInstallKind("/Users/someone/dev/onepatch-cli")).toBeNull();
103
- });
104
- });
105
-
106
- describe("installCommand", () => {
107
- test("pins the discovered version, not the latest tag", () => {
108
- expect(installCommand("bun", "0.3.0")).toEqual(["bun", "add", "-g", "onepatch@0.3.0"]);
109
- expect(installCommand("npm", "0.3.0")).toEqual(["npm", "install", "-g", "onepatch@0.3.0"]);
110
- });
111
- });
112
-
113
- describe("fetchLatestVersion", () => {
114
- test("reads the version from the registry manifest", async () => {
115
- const fake = (async () => Response.json({ version: "0.4.2" })) as unknown as typeof fetch;
116
- expect(await fetchLatestVersion(fake)).toBe("0.4.2");
117
- });
118
-
119
- test("rejects a manifest without a version", async () => {
120
- const fake = (async () => Response.json({})) as unknown as typeof fetch;
121
- await expect(fetchLatestVersion(fake)).rejects.toThrow("without a version");
122
- });
123
-
124
- test("rejects a non-2xx answer", async () => {
125
- const fake = (async () => new Response("nope", { status: 503 })) as unknown as typeof fetch;
126
- await expect(fetchLatestVersion(fake)).rejects.toThrow("503");
127
- });
128
- });
@@ -1,87 +0,0 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { type DeviceAuthorization, pollForDeviceToken, refreshTokens } from "./workos";
3
-
4
- const DEVICE: DeviceAuthorization = {
5
- device_code: "dev_123",
6
- user_code: "ABCD-1234",
7
- verification_uri: "https://auth.example/device",
8
- verification_uri_complete: "https://auth.example/device?code=ABCD-1234",
9
- expires_in: 300,
10
- interval: 5,
11
- };
12
-
13
- // A fetch stub that answers the authenticate endpoint from a scripted queue.
14
- function scriptedFetch(responses: Array<{ status: number; body: unknown }>): {
15
- fetchImpl: typeof fetch;
16
- requests: URLSearchParams[];
17
- } {
18
- const requests: URLSearchParams[] = [];
19
- const fetchImpl = (async (_url: string | URL | Request, init?: RequestInit) => {
20
- requests.push(new URLSearchParams(String(init?.body ?? "")));
21
- const next = responses.shift();
22
- if (!next) throw new Error("scripted fetch exhausted");
23
- return Response.json(next.body, { status: next.status });
24
- }) as typeof fetch;
25
- return { fetchImpl, requests };
26
- }
27
-
28
- const TOKENS = {
29
- access_token: "at_new",
30
- refresh_token: "rt_new",
31
- user: { id: "user_1", email: "dev@example.com" },
32
- organization_id: "org_1",
33
- };
34
-
35
- describe("pollForDeviceToken", () => {
36
- test("keeps polling through authorization_pending, widens on slow_down, then succeeds", async () => {
37
- const sleeps: number[] = [];
38
- const { fetchImpl, requests } = scriptedFetch([
39
- { status: 400, body: { error: "authorization_pending" } },
40
- { status: 400, body: { error: "slow_down" } },
41
- { status: 200, body: TOKENS },
42
- ]);
43
- const result = await pollForDeviceToken("client_01TEST", DEVICE, {
44
- fetchImpl,
45
- sleep: async (ms) => {
46
- sleeps.push(ms);
47
- },
48
- });
49
- expect(result.accessToken).toBe("at_new");
50
- expect(result.refreshToken).toBe("rt_new");
51
- expect(result.user?.email).toBe("dev@example.com");
52
- expect(result.organizationId).toBe("org_1");
53
- // 5s while pending, then 5+5=10s after slow_down.
54
- expect(sleeps).toEqual([5000, 10000]);
55
- expect(requests[0]?.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:device_code");
56
- expect(requests[0]?.get("device_code")).toBe("dev_123");
57
- });
58
-
59
- test("access_denied stops with a clear error", async () => {
60
- const { fetchImpl } = scriptedFetch([{ status: 400, body: { error: "access_denied" } }]);
61
- await expect(
62
- pollForDeviceToken("client_01TEST", DEVICE, { fetchImpl, sleep: async () => {} }),
63
- ).rejects.toThrow(/denied/);
64
- });
65
-
66
- test("expired_token tells the user to log in again", async () => {
67
- const { fetchImpl } = scriptedFetch([{ status: 400, body: { error: "expired_token" } }]);
68
- await expect(
69
- pollForDeviceToken("client_01TEST", DEVICE, { fetchImpl, sleep: async () => {} }),
70
- ).rejects.toThrow(/login/);
71
- });
72
- });
73
-
74
- describe("refreshTokens", () => {
75
- test("sends the refresh grant and parses rotated tokens", async () => {
76
- const { fetchImpl, requests } = scriptedFetch([{ status: 200, body: TOKENS }]);
77
- const result = await refreshTokens("client_01TEST", "rt_old", fetchImpl);
78
- expect(result.refreshToken).toBe("rt_new");
79
- expect(requests[0]?.get("grant_type")).toBe("refresh_token");
80
- expect(requests[0]?.get("refresh_token")).toBe("rt_old");
81
- });
82
-
83
- test("a rejected refresh surfaces as a re-login prompt", async () => {
84
- const { fetchImpl } = scriptedFetch([{ status: 400, body: { error: "invalid_grant" } }]);
85
- await expect(refreshTokens("client_01TEST", "rt_old", fetchImpl)).rejects.toThrow(/login/);
86
- });
87
- });