antechamber 0.2.3 → 0.2.4

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/CHANGELOG.md CHANGED
@@ -7,6 +7,15 @@ and this project uses [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.4] - 2026-10-15
11
+
12
+ ### Added
13
+
14
+ - feat(cli): `antechamber setup --auto-update` points OpenChamber at a launcher that installs the latest release in the background on every start; it is now the recommended install path
15
+ - feat(cli): `antechamber upgrade` installs the latest release with the package manager that owns the global install, so OpenChamber 2.3.2's Update button now upgrades antechamber
16
+ - feat(api): `POST /global/upgrade` upgrades antechamber itself instead of returning `UnsupportedError`
17
+ - feat(config): `ANTECHAMBER_AUTO_UPDATE=1` enables the post-start background update
18
+
10
19
  ## [0.2.3] - 2026-10-15
11
20
 
12
21
  ### Fixed
package/README.md CHANGED
@@ -73,13 +73,23 @@ Needs Node.js 22+ and OmO's `omo` command on PATH (`bun add -g omo-ai`).
73
73
  npm i -g antechamber
74
74
  # or: bun add -g antechamber
75
75
  antechamber doctor
76
- antechamber setup
76
+ antechamber setup --auto-update
77
77
  ```
78
78
 
79
79
  `setup` updates OpenChamber's `opencodeBinary`, preserves all other settings,
80
80
  and backs up an existing settings file before changing it. Restart OpenChamber
81
81
  after setup. Preview changes with `antechamber setup --dry-run`.
82
82
 
83
+ `--auto-update` keeps antechamber current without any action from you. It
84
+ writes a small launcher, `~/.config/antechamber/opencode-antechamber`, and points
85
+ OpenChamber at it. Each time OpenChamber starts antechamber, the launcher
86
+ checks npm for a newer release once the server is up and installs it with the
87
+ package manager that owns the global install. The new version runs from the
88
+ next start; startup never waits on the network, and an offline start just
89
+ skips the check. It needs a global npm or bun install, so it is refused for
90
+ source checkouts and `npx`. Drop the flag (plain `antechamber setup`) to point
91
+ OpenChamber back at the `antechamber` bin and stop auto-updates.
92
+
83
93
  Optionally, add the bundled [OmO Graph extension](#openchamber-extension-omo-graph):
84
94
  `setup` ends by printing its folder
85
95
  (`$(npm root -g)/antechamber/extensions/omo-dag`). In OpenChamber, open
@@ -131,28 +141,33 @@ antechamber serve --hostname 127.0.0.1 --port 4096
131
141
  | Command | Purpose / options |
132
142
  |---|---|
133
143
  | `antechamber serve` | OpenCode-compatible server; `--hostname`/`--host`, `--port`, `--directory`. Bare `antechamber` also starts the server. |
134
- | `antechamber setup` | Configure OpenChamber; `--settings <file>`, `--profile <dir>`, `--binary <path>`, `--dry-run`, `--systemd [unit]`, `--pi-binary <path>`, `--restart`. |
144
+ | `antechamber setup` | Configure OpenChamber; `--settings <file>`, `--profile <dir>`, `--binary <path>`, `--dry-run`, `--systemd [unit]`, `--pi-binary <path>`, `--restart`, `--auto-update`. |
135
145
  | `antechamber doctor` | Read-only Node, backend, agent/state directories, teardown, OpenChamber and auth checks; `--json`, `--settings <file>`, `--profile <dir>`. Exits 1 on any FAIL; warnings do not fail. |
146
+ | `antechamber upgrade` | Install the latest release over a global npm or bun install, with the package manager that owns it. Refused for source checkouts and `npx`. |
136
147
  | `antechamber version` | Package version plus OpenCode API contract version. `--version`/`-v` deliberately print exactly `opencode v2.0.20` for OpenChamber. |
137
148
  | `antechamber help` | Usage and options; also `--help`/`-h`. |
138
149
 
139
150
  ## Upgrade, uninstall and rollback
140
151
 
152
+ With `setup --auto-update` there is nothing to do: each start installs the
153
+ latest release for the next one. Otherwise:
154
+
141
155
  ```bash
142
- npm update -g antechamber
143
- # or: bun add -g antechamber
156
+ antechamber upgrade
157
+ # equivalent: npm update -g antechamber (or: bun add -g antechamber)
144
158
  ```
145
159
 
146
160
  Restart OpenChamber, or `systemctl --user restart openchamber.service` for a
147
161
  managed service. Run `antechamber doctor` again. If the executable moved,
148
162
  rerun `antechamber setup`.
149
163
 
150
- OpenChamber 2.3.2 may announce a newer OpenCode release. antechamber reports
151
- OpenCode API 2.0.20, the minimum OpenChamber accepts, and OpenChamber offers
152
- no signal that keeps that check while hiding the notice. Dismiss it or turn off
153
- OpenCode update notifications in OpenChamber. Its Update action runs
154
- `opencode-antechamber upgrade`, which refuses; upgrade antechamber with the
155
- commands above.
164
+ OpenChamber 2.3.2 shows an "OpenCode update" notice because antechamber
165
+ reports OpenCode API 2.0.20, the minimum OpenChamber accepts. The notice names
166
+ an OpenCode version, but its **Update** button runs `<opencodeBinary> upgrade`,
167
+ which upgrades antechamber itself (a no-op when it is already current). Click
168
+ **Reload OpenCode** afterwards to restart onto the new version. OpenChamber
169
+ 1.x shows no notice; its `POST /global/upgrade` call upgrades antechamber the
170
+ same way.
156
171
 
157
172
  To roll back wiring, copy the backup printed by setup over the settings file:
158
173
 
@@ -1,7 +1,8 @@
1
1
  #!/bin/sh
2
2
  # OpenChamber launcher: point `settings.opencodeBinary` (or $OPENCODE_BINARY)
3
3
  # at this file. OpenChamber runs `<binary> serve --hostname H --port P` and
4
- # `<binary> --version`; anything else is rejected.
4
+ # `<binary> --version`, and OpenChamber 2.x's Update action runs `<binary> upgrade`;
5
+ # anything else is rejected.
5
6
  # Requires a build (`npm run build`) so that dist/cli.js exists.
6
7
  set -eu
7
8
  SCRIPT_PATH=$0
@@ -22,10 +23,7 @@ fi
22
23
  case "${1:-}" in
23
24
  serve) shift; exec node "$CLI" serve "$@" ;;
24
25
  --version|-v) exec node "$CLI" --version ;;
25
- upgrade)
26
- echo "opencode-antechamber: OpenChamber cannot upgrade antechamber; run 'npm update -g antechamber' (or 'bun add -g antechamber') instead" >&2
27
- exit 1
28
- ;;
26
+ upgrade) exec node "$CLI" upgrade ;;
29
27
  esac
30
- echo "opencode-antechamber: unsupported command '${1:-}' (only 'serve' and '--version' are implemented)" >&2
28
+ echo "opencode-antechamber: unsupported command '${1:-}' (only 'serve', '--version' and 'upgrade' are implemented)" >&2
31
29
  exit 1
package/dist/cli.js CHANGED
@@ -26,6 +26,7 @@ try {
26
26
  systemd: { type: "boolean" },
27
27
  "pi-binary": { type: "string" },
28
28
  restart: { type: "boolean" },
29
+ "auto-update": { type: "boolean" },
29
30
  json: { type: "boolean" },
30
31
  },
31
32
  });
@@ -49,8 +50,15 @@ try {
49
50
  ...(values.systemd ? { systemd: positionals[1] ?? "openchamber.service" } : {}),
50
51
  dryRun: values["dry-run"] ?? false,
51
52
  restart: values.restart ?? false,
53
+ autoUpdate: values["auto-update"] ?? false,
52
54
  });
53
55
  }
56
+ else if (command === "upgrade") {
57
+ if (positionals.length > 1)
58
+ throw new Error("Unexpected upgrade argument");
59
+ const { upgrade } = await import("./commands/upgrade.js");
60
+ await upgrade();
61
+ }
54
62
  else if (command === "doctor") {
55
63
  const { doctor, formatDoctor } = await import("./commands/doctor.js");
56
64
  const report = doctor({
@@ -22,4 +22,8 @@ export interface SettingsOptions {
22
22
  export declare function settingsPath(options: SettingsOptions, ctx: CommandContext): string;
23
23
  export declare function readSettings(path: string, ctx: CommandContext): Record<string, unknown>;
24
24
  export declare function shellQuote(value: string): string;
25
+ /** OpenChamber launcher written by `setup --auto-update`, kept beside the session registry. */
26
+ export declare function autoUpdateLauncherPath(ctx: CommandContext): string;
27
+ export declare function autoUpdateLauncherText(binary: string): string;
28
+ export declare function autoUpdateLauncherTarget(text: string): string | undefined;
25
29
  export declare function isPackageBinary(binary: string, ctx: CommandContext): boolean;
@@ -3,6 +3,7 @@ import * as fs from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { delimiter, isAbsolute, join, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { defaultStateDir, envSetting } from "../config.js";
6
7
  export function createContext(overrides = {}) {
7
8
  const env = overrides.env ?? process.env;
8
9
  const cwd = overrides.cwd ?? process.cwd();
@@ -80,6 +81,24 @@ export function readSettings(path, ctx) {
80
81
  export function shellQuote(value) {
81
82
  return /^[\w./:@=-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
82
83
  }
84
+ /** OpenChamber launcher written by `setup --auto-update`, kept beside the session registry. */
85
+ export function autoUpdateLauncherPath(ctx) {
86
+ return resolve(ctx.cwd, envSetting("STATE_DIR", ctx.env) ?? defaultStateDir(ctx.home, ctx.fs.existsSync), "opencode-antechamber");
87
+ }
88
+ export function autoUpdateLauncherText(binary) {
89
+ return [
90
+ "#!/bin/sh",
91
+ "# Written by `antechamber setup --auto-update`; rerun `antechamber setup` without it to stop auto-updates.",
92
+ "ANTECHAMBER_AUTO_UPDATE=1",
93
+ "export ANTECHAMBER_AUTO_UPDATE",
94
+ `exec '${binary.replaceAll("'", "'\\''")}' "$@"`,
95
+ "",
96
+ ].join("\n");
97
+ }
98
+ export function autoUpdateLauncherTarget(text) {
99
+ const match = /^exec '((?:[^']|'\\'')*)' "\$@"$/m.exec(text);
100
+ return match?.[1]?.replaceAll("'\\''", "'");
101
+ }
83
102
  export function isPackageBinary(binary, ctx) {
84
103
  const resolved = resolveBinary(binary, ctx);
85
104
  if (resolved === undefined)
@@ -3,7 +3,7 @@ import { piAgentDir } from "../agent-dir.js";
3
3
  import { detectAgentName } from "../agent-name.js";
4
4
  import { agentBinary, defaultStateDir, envSetting, isPlainPi } from "../config.js";
5
5
  import { findPidfdPython } from "../pidfd.js";
6
- import { createContext, isPackageBinary, readSettings, resolveBinary, settingsPath, } from "./context.js";
6
+ import { autoUpdateLauncherPath, autoUpdateLauncherTarget, createContext, isPackageBinary, readSettings, resolveBinary, settingsPath, } from "./context.js";
7
7
  /** Checks capabilities with access/stat only, never creating state or config files. */
8
8
  export function doctor(options = {}, ctx = createContext()) {
9
9
  const checks = [];
@@ -75,8 +75,13 @@ export function doctor(options = {}, ctx = createContext()) {
75
75
  else {
76
76
  try {
77
77
  const configured = readSettings(settings, ctx).opencodeBinary;
78
- const matches = typeof configured === "string" && isPackageBinary(configured, ctx);
79
- add("openchamber-settings", matches ? "PASS" : "WARN", `${settings}: opencodeBinary=${JSON.stringify(configured ?? null)}${matches ? "" : "; does not point at this antechamber installation"}`);
78
+ const launcher = autoUpdateLauncherPath(ctx);
79
+ const launcherTarget = configured === launcher && ctx.fs.existsSync(launcher)
80
+ ? autoUpdateLauncherTarget(ctx.fs.readFileSync(launcher, "utf8"))
81
+ : undefined;
82
+ const viaLauncher = launcherTarget !== undefined && isPackageBinary(launcherTarget, ctx);
83
+ const matches = viaLauncher || (typeof configured === "string" && isPackageBinary(configured, ctx));
84
+ add("openchamber-settings", matches ? "PASS" : "WARN", `${settings}: opencodeBinary=${JSON.stringify(configured ?? null)}${viaLauncher ? ` (auto-update launcher for ${launcherTarget})` : matches ? "" : "; does not point at this antechamber installation"}`);
80
85
  }
81
86
  catch (error) {
82
87
  add("openchamber-settings", "WARN", error instanceof Error ? error.message : String(error));
@@ -1 +1 @@
1
- export declare const help = "Usage: antechamber [command] [options]\n\nCommands:\n serve Run the OpenCode-compatible HTTP/SSE server (also the default)\n setup Point OpenChamber at this installation; back up changed files\n doctor Read-only installation and backend checks (exit 1 on FAIL)\n version Print the npm package and OpenCode API versions\n help Show this help (--help, -h)\n\nServe: --port 4096 --host 127.0.0.1 (or --hostname) --directory <path>\n --insecure-no-auth\nSetup: --settings <file> | --profile <dir>\n --binary <path> --dry-run --systemd [unit] --pi-binary <path> --restart\nDoctor: --settings <file> | --profile <dir> --json\nProbe: --version, -v prints the OpenCode compatibility version for OpenChamber";
1
+ export declare const help = "Usage: antechamber [command] [options]\n\nCommands:\n serve Run the OpenCode-compatible HTTP/SSE server (also the default)\n setup Point OpenChamber at this installation; back up changed files\n doctor Read-only installation and backend checks (exit 1 on FAIL)\n upgrade Install the latest release over a global npm or bun install\n version Print the npm package and OpenCode API versions\n help Show this help (--help, -h)\n\nServe: --port 4096 --host 127.0.0.1 (or --hostname) --directory <path>\n --insecure-no-auth\nSetup: --settings <file> | --profile <dir>\n --binary <path> --dry-run --systemd [unit] --pi-binary <path> --restart\n --auto-update (launch through a wrapper that upgrades on each start)\nDoctor: --settings <file> | --profile <dir> --json\nProbe: --version, -v prints the OpenCode compatibility version for OpenChamber";
@@ -4,6 +4,7 @@ Commands:
4
4
  serve Run the OpenCode-compatible HTTP/SSE server (also the default)
5
5
  setup Point OpenChamber at this installation; back up changed files
6
6
  doctor Read-only installation and backend checks (exit 1 on FAIL)
7
+ upgrade Install the latest release over a global npm or bun install
7
8
  version Print the npm package and OpenCode API versions
8
9
  help Show this help (--help, -h)
9
10
 
@@ -11,5 +12,6 @@ Serve: --port 4096 --host 127.0.0.1 (or --hostname) --directory <path>
11
12
  --insecure-no-auth
12
13
  Setup: --settings <file> | --profile <dir>
13
14
  --binary <path> --dry-run --systemd [unit] --pi-binary <path> --restart
15
+ --auto-update (launch through a wrapper that upgrades on each start)
14
16
  Doctor: --settings <file> | --profile <dir> --json
15
17
  Probe: --version, -v prints the OpenCode compatibility version for OpenChamber`;
@@ -1,4 +1,5 @@
1
1
  import { envSetting } from "../config.js";
2
+ import { selfUpdate } from "../self-update.js";
2
3
  import { AdapterServer, isLoopbackHost, serverPassword } from "../server.js";
3
4
  export async function serve(options) {
4
5
  const { port, host, directory, insecureNoAuth, compatible } = options;
@@ -26,4 +27,17 @@ export async function serve(options) {
26
27
  console.log(`antechamber listening on ${server.url}`);
27
28
  console.log(`default directory: ${directory}`);
28
29
  }
30
+ // After the listening line: OpenChamber's startup timeout must not wait on the registry.
31
+ if (envSetting("AUTO_UPDATE") === "1")
32
+ void autoUpdate();
33
+ }
34
+ async function autoUpdate() {
35
+ try {
36
+ const result = await selfUpdate();
37
+ if (result.updated)
38
+ console.error(`antechamber: auto-update installed ${result.to} (running ${result.from}); it starts next time`);
39
+ }
40
+ catch (error) {
41
+ console.error(`antechamber: auto-update skipped: ${error instanceof Error ? error.message : String(error)}`);
42
+ }
29
43
  }
@@ -5,6 +5,7 @@ interface SetupOptions extends SettingsOptions {
5
5
  readonly systemd?: string;
6
6
  readonly piBinary?: string;
7
7
  readonly restart?: boolean;
8
+ readonly autoUpdate?: boolean;
8
9
  /** User-unit root, overridable without touching the real systemd configuration. */
9
10
  readonly systemdDir?: string;
10
11
  }
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { dirname, join, resolve } from "node:path";
3
- import { createContext, isPackageBinary, readSettings, resolveBinary, settingsPath, shellQuote, } from "./context.js";
3
+ import { installMethod, npmBinaryFor } from "../self-update.js";
4
+ import { autoUpdateLauncherPath, autoUpdateLauncherText, createContext, isPackageBinary, readSettings, resolveBinary, settingsPath, shellQuote, } from "./context.js";
4
5
  function systemdValue(value) {
5
6
  if (/[\r\n\0]/.test(value))
6
7
  throw new Error("systemd environment values cannot contain newlines or NUL");
@@ -40,8 +41,24 @@ export function setup(options, ctx = createContext()) {
40
41
  if (binary === ctx.cliPath && !ctx.fs.readFileSync(binary, "utf8").startsWith("#!/usr/bin/env node\n")) {
41
42
  throw new Error(`Package CLI ${binary} is missing its node shebang; run npm run build`);
42
43
  }
43
- const updated = `${JSON.stringify({ ...data, opencodeBinary: binary }, null, 2)}\n`;
44
- const changed = data.opencodeBinary !== binary;
44
+ let launcher;
45
+ let launcherText;
46
+ let oldLauncher;
47
+ if (options.autoUpdate) {
48
+ installMethod({
49
+ packageRoot: resolve(dirname(ctx.cliPath), ".."),
50
+ env: ctx.env,
51
+ home: ctx.home,
52
+ realpath: (path) => ctx.fs.realpathSync(path),
53
+ }, () => ctx.exec(npmBinaryFor(), ["root", "-g"]));
54
+ launcher = autoUpdateLauncherPath(ctx);
55
+ launcherText = autoUpdateLauncherText(binary);
56
+ if (ctx.fs.existsSync(launcher))
57
+ oldLauncher = ctx.fs.readFileSync(launcher, "utf8");
58
+ }
59
+ const configured = launcher ?? binary;
60
+ const updated = `${JSON.stringify({ ...data, opencodeBinary: configured }, null, 2)}\n`;
61
+ const changed = data.opencodeBinary !== configured;
45
62
  let dropIn;
46
63
  let dropInText;
47
64
  let oldDropIn;
@@ -102,10 +119,22 @@ export function setup(options, ctx = createContext()) {
102
119
  report(`Made ${binary} executable`);
103
120
  }
104
121
  }
122
+ if (launcher !== undefined && launcherText !== undefined) {
123
+ if (oldLauncher === launcherText && (ctx.fs.statSync(launcher).mode & 0o111) !== 0)
124
+ report(`Already configured: ${launcher}`);
125
+ else if (options.dryRun)
126
+ report(`Would write auto-update launcher ${launcher} for ${binary}`);
127
+ else {
128
+ ctx.fs.mkdirSync(dirname(launcher), { recursive: true });
129
+ writeAtomically(launcher, launcherText, ctx);
130
+ ctx.fs.chmodSync(launcher, 0o755);
131
+ report(`Wrote auto-update launcher ${launcher} for ${binary}`);
132
+ }
133
+ }
105
134
  if (changed) {
106
135
  report(`${options.dryRun ? "Would update" : "Updating"} ${settings}`);
107
136
  report(`- opencodeBinary: ${JSON.stringify(data.opencodeBinary ?? null)}`);
108
- report(`+ opencodeBinary: ${JSON.stringify(binary)}`);
137
+ report(`+ opencodeBinary: ${JSON.stringify(configured)}`);
109
138
  if (existing)
110
139
  backup(settings);
111
140
  if (!options.dryRun) {
@@ -115,7 +144,7 @@ export function setup(options, ctx = createContext()) {
115
144
  }
116
145
  }
117
146
  else
118
- report(`Already configured: ${settings} points at ${binary}`);
147
+ report(`Already configured: ${settings} points at ${configured}`);
119
148
  if (dropIn !== undefined && dropInText !== undefined) {
120
149
  if (oldDropIn === dropInText)
121
150
  report(`Already configured: ${dropIn}`);
@@ -0,0 +1,2 @@
1
+ import { type SelfUpdateResult } from "../self-update.js";
2
+ export declare function upgrade(update?: () => Promise<SelfUpdateResult>, output?: (line: string) => void): Promise<void>;
@@ -0,0 +1,7 @@
1
+ import { selfUpdate } from "../self-update.js";
2
+ export async function upgrade(update = selfUpdate, output = console.log) {
3
+ const result = await update();
4
+ output(result.updated
5
+ ? `Updated antechamber ${result.from} -> ${result.to} with ${result.method}; restart OpenChamber to use it.`
6
+ : `antechamber ${result.from} is already the latest release.`);
7
+ }
@@ -5,6 +5,7 @@ import type { Catalog } from "./catalog.js";
5
5
  import type { ModelSelection } from "./thinking-levels.js";
6
6
  import type { OCEvent, OCMessageWithParts, OCPromptPart } from "./types.js";
7
7
  import type { TodoUpdated } from "./todo-bridge.js";
8
+ import type { SelfUpdateResult } from "./self-update.js";
8
9
  export interface RouteServices {
9
10
  readonly sessions: SessionManager;
10
11
  readonly defaultDirectory: string;
@@ -12,6 +13,7 @@ export interface RouteServices {
12
13
  readonly body: (req: IncomingMessage) => Promise<unknown>;
13
14
  readonly catalog: () => Promise<Catalog>;
14
15
  readonly broadcast: (directory: string, event: OCEvent | TodoUpdated) => void;
16
+ readonly selfUpdate: () => Promise<SelfUpdateResult>;
15
17
  }
16
18
  export declare const OPENCODE_COMPAT_VERSION: string | null;
17
19
  export declare function numberParam(value: string | null): number | undefined;
package/dist/routes-v1.js CHANGED
@@ -6,6 +6,7 @@ import { miscRoute } from "./misc-routes.js";
6
6
  import { getAgentName } from "./agent-name.js";
7
7
  import { nativePromptInput, parsePromptParts } from "./prompt-parts.js";
8
8
  import { RequestBodyError } from "./http.js";
9
+ import { SelfUpdateUnsupportedError } from "./self-update.js";
9
10
  import { announceSessionError, compactSession, getCommands, unsupportedShare } from "./session-commands.js";
10
11
  import { agentDescriptors, modelRefFromBody, numberParam, OPENCODE_COMPAT_VERSION, promptAsync, runSessionShell, runSessionSlash, sessionDirectory, sessionMetadata, } from "./route-services.js";
11
12
  /**
@@ -19,13 +20,26 @@ function applyArchivedFilter(sessions, archived) {
19
20
  return sessions.filter((s) => s.time.archived === undefined);
20
21
  return sessions;
21
22
  }
22
- function handleV1GlobalRoute(res, path, method) {
23
+ async function handleV1GlobalRoute(services, res, path, method) {
23
24
  if (method === "GET" && path === "/global/health") {
24
25
  json(res, 200, OPENCODE_COMPAT_VERSION === null ? { healthy: true } : { healthy: true, version: OPENCODE_COMPAT_VERSION });
25
26
  return true;
26
27
  }
27
- if ((method === "POST" || method === "GET") && path === "/global/upgrade") {
28
- json(res, 409, errorBody("UnsupportedError", "This endpoint is served by antechamber (a pi adapter), not a real opencode install — there is nothing to upgrade."));
28
+ if (method === "POST" && path === "/global/upgrade") {
29
+ // The requested OpenCode `target` does not apply: this upgrades antechamber itself.
30
+ try {
31
+ const result = await services.selfUpdate();
32
+ json(res, 200, { success: true, version: result.to, updated: result.updated });
33
+ }
34
+ catch (error) {
35
+ if (!(error instanceof SelfUpdateUnsupportedError))
36
+ throw error;
37
+ json(res, 409, errorBody("UnsupportedError", error.message));
38
+ }
39
+ return true;
40
+ }
41
+ if (method === "GET" && path === "/global/upgrade") {
42
+ json(res, 409, errorBody("UnsupportedError", "Upgrade antechamber with POST /global/upgrade."));
29
43
  return true;
30
44
  }
31
45
  return false;
@@ -47,7 +61,7 @@ function parseV1Prompt(body, defaultModel) {
47
61
  return { text, model, parts, delivery: body.delivery ?? "steer" };
48
62
  }
49
63
  export async function handleV1(services, req, res, url, path, method, directory) {
50
- if (handleV1GlobalRoute(res, path, method))
64
+ if (await handleV1GlobalRoute(services, res, path, method))
51
65
  return;
52
66
  // --- sessions ---
53
67
  const misc = await miscRoute(method, path, url, directory);
@@ -0,0 +1,32 @@
1
+ export type InstallMethod = "npm" | "bun";
2
+ export declare class SelfUpdateUnsupportedError extends Error {
3
+ readonly name = "SelfUpdateUnsupportedError";
4
+ }
5
+ export interface InstallLocation {
6
+ readonly packageRoot: string;
7
+ readonly env: NodeJS.ProcessEnv;
8
+ readonly home: string;
9
+ readonly realpath: (path: string) => string;
10
+ }
11
+ export interface SelfUpdateDeps extends InstallLocation {
12
+ readonly npmBinary: string;
13
+ readonly bunBinary: string;
14
+ readonly npmRoot: () => Promise<string>;
15
+ readonly currentVersion: string;
16
+ readonly latestVersion: () => Promise<string>;
17
+ readonly install: (binary: string, args: readonly string[]) => Promise<void>;
18
+ }
19
+ export interface SelfUpdateResult {
20
+ readonly updated: boolean;
21
+ readonly from: string;
22
+ readonly to: string;
23
+ readonly method: InstallMethod;
24
+ }
25
+ export declare function installMethod(location: InstallLocation, npmRoot: () => string): InstallMethod;
26
+ export declare function isNewerVersion(a: string, b: string): boolean;
27
+ export declare function fetchLatestVersion(env?: NodeJS.ProcessEnv): Promise<string>;
28
+ /** Prefers the npm shipped beside the running node: service PATHs often lack the user's tool directories. */
29
+ export declare function npmBinaryFor(execPath?: string): string;
30
+ export declare function defaultSelfUpdateDeps(env?: NodeJS.ProcessEnv, home?: string): SelfUpdateDeps;
31
+ /** Installs the latest release when it is newer; concurrent callers in this process share one attempt. */
32
+ export declare function selfUpdate(deps?: SelfUpdateDeps): Promise<SelfUpdateResult>;
@@ -0,0 +1,188 @@
1
+ /** Upgrades a global npm or bun install of antechamber to the latest published release. */
2
+ import { execFile } from "node:child_process";
3
+ import { existsSync, realpathSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { ADAPTER_VERSION } from "./version.js";
8
+ export class SelfUpdateUnsupportedError extends Error {
9
+ name = "SelfUpdateUnsupportedError";
10
+ }
11
+ const INSTALL_TIMEOUT_MS = 5 * 60_000;
12
+ const VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
13
+ function tryRealpath(path, location) {
14
+ try {
15
+ return location.realpath(path);
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ function bunInstallDir(location) {
22
+ return location.env.BUN_INSTALL ?? join(location.home, ".bun");
23
+ }
24
+ function locate(location) {
25
+ const root = tryRealpath(location.packageRoot, location) ?? location.packageRoot;
26
+ if (basename(root) !== "antechamber" || basename(dirname(root)) !== "node_modules")
27
+ throw notGlobal(root);
28
+ const bunPackage = join(bunInstallDir(location), "install", "global", "node_modules", "antechamber");
29
+ return { root, bun: tryRealpath(bunPackage, location) === root };
30
+ }
31
+ function notGlobal(root) {
32
+ return new SelfUpdateUnsupportedError(`${root} is not a global npm or bun install of antechamber; update it the way it was installed (source checkout: git pull && npm ci && npm run build)`);
33
+ }
34
+ function npmOwns(location, root, npmGlobal) {
35
+ const global = npmGlobal.trim();
36
+ if (global !== "" && tryRealpath(join(global, "antechamber"), location) === root)
37
+ return "npm";
38
+ throw notGlobal(root);
39
+ }
40
+ function npmUnavailable(error) {
41
+ const reason = error instanceof Error ? error.message : String(error);
42
+ return new SelfUpdateUnsupportedError(`cannot run npm root -g to confirm a global npm install (${reason})`);
43
+ }
44
+ export function installMethod(location, npmRoot) {
45
+ const { root, bun } = locate(location);
46
+ if (bun)
47
+ return "bun";
48
+ let global;
49
+ try {
50
+ global = npmRoot();
51
+ }
52
+ catch (error) {
53
+ throw npmUnavailable(error);
54
+ }
55
+ return npmOwns(location, root, global);
56
+ }
57
+ async function installMethodAsync(deps) {
58
+ const { root, bun } = locate(deps);
59
+ if (bun)
60
+ return "bun";
61
+ let global;
62
+ try {
63
+ global = await deps.npmRoot();
64
+ }
65
+ catch (error) {
66
+ throw npmUnavailable(error);
67
+ }
68
+ return npmOwns(deps, root, global);
69
+ }
70
+ export function isNewerVersion(a, b) {
71
+ const left = VERSION_PATTERN.exec(a);
72
+ const right = VERSION_PATTERN.exec(b);
73
+ if (left === null || right === null)
74
+ return false;
75
+ for (let index = 1; index <= 3; index += 1) {
76
+ const diff = Number(left[index]) - Number(right[index]);
77
+ if (diff !== 0)
78
+ return diff > 0;
79
+ }
80
+ if (left[4] === right[4])
81
+ return false;
82
+ if (left[4] === undefined)
83
+ return true;
84
+ if (right[4] === undefined)
85
+ return false;
86
+ const leftParts = left[4].split(".");
87
+ const rightParts = right[4].split(".");
88
+ for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
89
+ const l = leftParts[index];
90
+ const r = rightParts[index];
91
+ if (l === undefined)
92
+ return false;
93
+ if (r === undefined)
94
+ return true;
95
+ if (l === r)
96
+ continue;
97
+ const ln = /^\d+$/.test(l) ? Number(l) : undefined;
98
+ const rn = /^\d+$/.test(r) ? Number(r) : undefined;
99
+ if (ln !== undefined && rn !== undefined)
100
+ return ln > rn;
101
+ if (ln !== undefined)
102
+ return false;
103
+ if (rn !== undefined)
104
+ return true;
105
+ return l > r;
106
+ }
107
+ return false;
108
+ }
109
+ export async function fetchLatestVersion(env = process.env) {
110
+ const url = new URL(`${(env.npm_config_registry ?? "https://registry.npmjs.org").replace(/\/+$/, "")}/antechamber/latest`);
111
+ // Registry URLs can embed a token; fetch rejects them and its error would echo the URL.
112
+ url.username = "";
113
+ url.password = "";
114
+ let response;
115
+ try {
116
+ response = await fetch(url, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(10_000) });
117
+ }
118
+ catch {
119
+ throw new Error(`cannot reach the npm registry at ${url.host}`);
120
+ }
121
+ if (!response.ok)
122
+ throw new Error(`npm registry at ${url.host} answered ${response.status} for antechamber`);
123
+ const payload = await response.json().catch(() => undefined);
124
+ const version = typeof payload === "object" && payload !== null && "version" in payload ? String(payload.version) : "";
125
+ if (!VERSION_PATTERN.test(version))
126
+ throw new Error("npm registry returned no valid antechamber version");
127
+ return version;
128
+ }
129
+ function run(binary, args, env, timeout) {
130
+ return new Promise((resolve, reject) => {
131
+ const child = execFile(binary, [...args], { env, timeout, maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => {
132
+ // Installer output can contain registry credentials, so it is never echoed.
133
+ if (error)
134
+ reject(new Error(`${basename(binary)} ${args.join(" ")} failed; run it in a terminal for details`));
135
+ else
136
+ resolve(stdout);
137
+ });
138
+ // Package managers must see EOF instead of waiting for interactive input.
139
+ child.stdin?.end();
140
+ });
141
+ }
142
+ /** Prefers the npm shipped beside the running node: service PATHs often lack the user's tool directories. */
143
+ export function npmBinaryFor(execPath = process.execPath) {
144
+ const sibling = join(dirname(execPath), process.platform === "win32" ? "npm.cmd" : "npm");
145
+ return existsSync(sibling) ? sibling : "npm";
146
+ }
147
+ function bunBinaryFor(env, home) {
148
+ const installed = join(bunInstallDir({ env, home }), "bin", "bun");
149
+ return existsSync(installed) ? installed : "bun";
150
+ }
151
+ export function defaultSelfUpdateDeps(env = process.env, home = homedir()) {
152
+ const npmBinary = npmBinaryFor();
153
+ return {
154
+ // src/self-update.ts (tsx) and dist/self-update.js both sit one level below the package root.
155
+ packageRoot: fileURLToPath(new URL("..", import.meta.url)),
156
+ env,
157
+ home,
158
+ realpath: realpathSync,
159
+ npmBinary,
160
+ bunBinary: bunBinaryFor(env, home),
161
+ npmRoot: () => run(npmBinary, ["root", "-g"], env, 10_000),
162
+ currentVersion: ADAPTER_VERSION,
163
+ latestVersion: () => fetchLatestVersion(env),
164
+ install: async (binary, args) => {
165
+ await run(binary, args, env, INSTALL_TIMEOUT_MS);
166
+ },
167
+ };
168
+ }
169
+ let inFlight;
170
+ /** Installs the latest release when it is newer; concurrent callers in this process share one attempt. */
171
+ export function selfUpdate(deps = defaultSelfUpdateDeps()) {
172
+ inFlight ??= (async () => {
173
+ const method = await installMethodAsync(deps);
174
+ const latest = await deps.latestVersion();
175
+ const from = deps.currentVersion;
176
+ if (!isNewerVersion(latest, from))
177
+ return { updated: false, from, to: from, method };
178
+ const spec = `antechamber@${latest}`;
179
+ if (method === "npm")
180
+ await deps.install(deps.npmBinary, ["install", "-g", spec]);
181
+ else
182
+ await deps.install(deps.bunBinary, ["add", "-g", spec]);
183
+ return { updated: true, from, to: latest, method };
184
+ })().finally(() => {
185
+ inFlight = undefined;
186
+ });
187
+ return inFlight;
188
+ }
package/dist/server.d.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  /** HTTP/SSE composition root for the OpenCode API backed by pi. */
2
+ import { type SelfUpdateResult } from "./self-update.js";
2
3
  export { isLoopbackHost, serverPassword } from "./http.js";
3
4
  interface AdapterServerOptions {
4
5
  port: number;
5
6
  host: string;
6
7
  /** Fallback directory when requests carry no ?directory= param. */
7
8
  defaultDirectory: string;
9
+ /** Replaces the npm self-update behind POST /global/upgrade (tests). */
10
+ selfUpdate?: () => Promise<SelfUpdateResult>;
8
11
  }
9
12
  export declare class AdapterServer {
10
13
  private options;
package/dist/server.js CHANGED
@@ -8,6 +8,7 @@ import { Http } from "./http.js";
8
8
  import { SSE } from "./sse.js";
9
9
  import { handleV1 } from "./routes-v1.js";
10
10
  import { handleV2 } from "./routes-v2.js";
11
+ import { selfUpdate } from "./self-update.js";
11
12
  export { isLoopbackHost, serverPassword } from "./http.js";
12
13
  export class AdapterServer {
13
14
  options;
@@ -203,6 +204,7 @@ export class AdapterServer {
203
204
  body: (request) => this.http.body(request),
204
205
  catalog: () => this.catalog(),
205
206
  broadcast: (dir, event) => this.broadcast(dir, event),
207
+ selfUpdate: this.options.selfUpdate ?? (() => selfUpdate()),
206
208
  };
207
209
  if (path === "/api" || path.startsWith("/api/")) {
208
210
  await handleV2(services, req, res, url, path, method, directory);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "antechamber-omo-graph",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "OpenChamber extension: live, interactive graph of the OmO sub-agents behind the current session",
5
5
  "private": true,
6
6
  "type": "module",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "antechamber",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "OpenCode-compatible HTTP/SSE server that lets OpenChamber drive the pi coding agent (and OmO) over RPC",
5
5
  "type": "module",
6
6
  "license": "MIT",