Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(platform): update check over HTTPS; ~ via os.homedir(); install.sh helper order + smoke test
Salman Qureshi72d656189d91
diff --git a/scripts/install.sh b/scripts/install.shindex 24ffb3b7..c71e96e2 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -24,6 +24,20 @@ REPO="cosmicstack-labs/mercury-agent"GITHUB_API="https://api.github.com/repos/${REPO}"GITHUB_DL="https://github.com/${REPO}/releases/download"+# ----- helpers ---------------------------------------------------------------++c_red() { printf '\033[31m%s\033[0m' "$1"; }+c_green() { printf '\033[32m%s\033[0m' "$1"; }+c_yellow() { printf '\033[33m%s\033[0m' "$1"; }+c_bold() { printf '\033[1m%s\033[0m' "$1"; }++info() { printf '%s %s\n' "$(c_green '→')" "$1"; }+warn() { printf '%s %s\n' "$(c_yellow '!')" "$1" >&2; }+err() { printf '%s %s\n' "$(c_red 'x')" "$1" >&2; }+die() { err "$1"; exit 1; }++have() { command -v "$1" >/dev/null 2>&1; }+# ----- channel ---------------------------------------------------------------## Stable is the default distribution channel — it resolves the numbered@@ -51,20 +65,6 @@ case "$CHANNEL" in;;esac-# ----- helpers -----------------------------------------------------------------c_red() { printf '\033[31m%s\033[0m' "$1"; }-c_green() { printf '\033[32m%s\033[0m' "$1"; }-c_yellow() { printf '\033[33m%s\033[0m' "$1"; }-c_bold() { printf '\033[1m%s\033[0m' "$1"; }--info() { printf '%s %s\n' "$(c_green '→')" "$1"; }-warn() { printf '%s %s\n' "$(c_yellow '!')" "$1" >&2; }-err() { printf '%s %s\n' "$(c_red 'x')" "$1" >&2; }-die() { err "$1"; exit 1; }--have() { command -v "$1" >/dev/null 2>&1; }-# Detect OS in Mercury's release naming (macos | linux).detect_os() {uname_s=$(uname -s 2>/dev/null || echo unknown)@@ -289,6 +289,17 @@ Install the supported Node.js package instead:info "Installed to $bin_path"+ # Post-install smoke: the binary must at least report its version. A+ # wrong-arch download, a glibc mismatch or a quarantined binary fails+ # here with a readable message instead of at first use.+ if smoke_out=$("$bin_path" --version 2>&1); then+ info "Smoke test passed: $BIN_NAME --version → $smoke_out"+ else+ err "The installed binary failed to run: $bin_path --version"+ printf '%s\n' "$smoke_out" | sed 's/^/ /' >&2+ die "Mercury ${version_label} is installed but not runnable on ${os}-${arch}. Please report this at https://github.com/${REPO}/issues (include the lines above)."+ fi+rm -rf "$tmp_dir"trap - EXIT INT TERMdiff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex b19a2725..12690b0c 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1,5 +1,6 @@import { refinePersona } from './persona-template.js';import { randomUUID } from 'node:crypto';+import { homedir } from 'node:os';import { basename, extname, isAbsolute, relative, resolve, join } from 'node:path';import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from 'node:fs';import type { Tool } from 'ai';@@ -1408,7 +1409,7 @@ export class BotManager {*/deliver(botId: string, filePath: string, rename?: string): { accepted: boolean; path?: string; reasonCode?: string } {if (!this.store.get(botId)) return { accepted: false, reasonCode: 'target_unknown' };- const candidate = resolve(filePath.replace(/^~(?=$|\/|\\)/, process.env.HOME || '~'));+ const candidate = resolve(filePath.replace(/^~(?=$|\/|\\)/, homedir()));const allowedBases = [this.store.sharedSandboxDir(), this.store.sandboxDir(botId)];const inside = allowedBases.some((base) => {const rel = relative(resolve(base), candidate);diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 872133f3..db7300b2 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -3,6 +3,7 @@ import { EventEmitter } from 'node:events';import { render } from 'ink';import fs from 'node:fs';import path from 'node:path';+import { homedir } from 'node:os';import { execSync, execFile, execFileSync } from 'node:child_process';import type { ChannelMessage } from '../types/channel.js';import { BaseChannel, type PermissionMode } from './base.js';@@ -2072,7 +2073,7 @@ export class CLIChannel extends BaseChannel {* capture wheel/drag events and break both.*/enterMercuryCode(dir: string, version: string): { ok: boolean; message: string } {- const target = path.resolve(dir.replace(/^~(?=$|\/)/, process.env.HOME || '~'));+ const target = path.resolve(dir.replace(/^~(?=$|\/|\\)/, homedir()));if (!fs.existsSync(target)) return { ok: false, message: `Directory does not exist: ${target}` };if (!fs.statSync(target).isDirectory()) return { ok: false, message: `Not a directory: ${target}` };@@ -2228,7 +2229,7 @@ export class CLIChannel extends BaseChannel {}openWorkspace(rawPath: string): { ok: boolean; message: string } {- const target = path.resolve(rawPath.replace(/^~(?=$|\/)/, process.env.HOME || '~'));+ const target = path.resolve(rawPath.replace(/^~(?=$|\/|\\)/, homedir()));if (!fs.existsSync(target)) return { ok: false, message: `Workspace path does not exist: ${target}` };if (!fs.statSync(target).isDirectory()) return { ok: false, message: `Workspace path is not a directory: ${target}` };diff --git a/src/cli/update-notice.test.ts b/src/cli/update-notice.test.tsindex 6725eb84..a393e075 100644--- a/src/cli/update-notice.test.ts+++ b/src/cli/update-notice.test.ts@@ -1,8 +1,9 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { mkdirSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import {+ fetchLatestFromRegistry,isNewerVersion,latestSeenUpdate,markWhatsNewHintShown,@@ -105,4 +106,46 @@ describe('/whatsnew content', () => {function shouldShowHelper(v: string): boolean {return shouldShowWhatsNewHint(v);-}\ No newline at end of file+}++/**+ * The remote look-up goes to the npm registry over HTTPS first: no npm+ * binary involved, so Windows (where `execFile('npm')` without a shell fails+ * with EINVAL on npm.cmd) finally sees updates. `fetch` is mocked — never+ * the network.+ */+describe('update check over HTTPS (registry.npmjs.org)', () => {+ afterEach(() => vi.unstubAllGlobals());++ function fetchMock(status: number, body: unknown) {+ return vi.fn(async (_url: string | URL | Request, _init?: RequestInit) =>+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }));+ }++ it('reads dist-tags/latest from the registry document', async () => {+ const f = fetchMock(200, { name: '@cosmicstack/mercury-agent', version: '9.9.9' });+ expect(await fetchLatestFromRegistry('@cosmicstack/mercury-agent', 1_000, f as unknown as typeof fetch)).toBe('9.9.9');+ expect(f).toHaveBeenCalledOnce();+ expect(String(f.mock.calls[0][0])).toBe('https://registry.npmjs.org/@cosmicstack/mercury-agent/latest');+ expect((f.mock.calls[0][1] as RequestInit).signal).toBeInstanceOf(AbortSignal);+ });++ it('returns null on a non-2xx, a malformed document, or a network error (never throws)', async () => {+ expect(await fetchLatestFromRegistry('x', 1_000, fetchMock(404, { error: 'not found' }) as unknown as typeof fetch)).toBeNull();+ expect(await fetchLatestFromRegistry('x', 1_000, fetchMock(200, { version: 42 }) as unknown as typeof fetch)).toBeNull();+ const failing = vi.fn(async () => { throw new TypeError('fetch failed'); });+ expect(await fetchLatestFromRegistry('x', 1_000, failing as unknown as typeof fetch)).toBeNull();+ });++ it('maybeCheckForUpdate uses the HTTPS route (global fetch) and persists what it saw', async () => {+ const f = fetchMock(200, { version: '3.0.0' });+ vi.stubGlobal('fetch', f);+ expect(await maybeCheckForUpdate('1.2.9')).toBe('3.0.0');+ expect(f).toHaveBeenCalledOnce();+ const { loadUpdateState } = await import('./update-notice.js');+ expect(loadUpdateState().latestSeen).toBe('3.0.0');+ // Throttled: a second call within the window does not hit the network again.+ expect(await maybeCheckForUpdate('1.2.9')).toBe('3.0.0');+ expect(f).toHaveBeenCalledOnce();+ });+});diff --git a/src/cli/update-notice.ts b/src/cli/update-notice.tsindex 40a801e2..6a7273fb 100644--- a/src/cli/update-notice.ts+++ b/src/cli/update-notice.ts@@ -90,15 +90,50 @@ export function ignoreUpdateVersion(latestVersion: string): void {saveUpdateState(state);}-/** Async `npm view` with a hard timeout — must never stall a boot. */-function fetchLatestNpmVersion(packageName: string, timeoutMs = 8_000): Promise<string | null> {- return new Promise((resolve) => {- execFile('npm', ['view', packageName, 'version'], { timeout: timeoutMs, encoding: 'utf-8' }, (err, stdout) => {- resolve(err ? null : String(stdout).trim() || null);+/**+ * Latest published version straight from the npm registry over HTTPS —+ * the preferred route: no npm binary needed, and no `npm.cmd` shell issue+ * on Windows (`execFile('npm')` without a shell fails there with EINVAL,+ * which the old code silently swallowed, so Windows never saw updates).+ */+export async function fetchLatestFromRegistry(+ packageName: string,+ timeoutMs = 8_000,+ fetchImpl: typeof fetch = fetch,+): Promise<string | null> {+ try {+ const res = await fetchImpl(`https://registry.npmjs.org/${packageName}/latest`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(timeoutMs),});+ if (!res.ok) return null;+ const data = await res.json() as { version?: unknown };+ return typeof data?.version === 'string' && data.version.trim() ? data.version.trim() : null;+ } catch (err) {+ logger.debug({ err }, 'update-notice: registry lookup failed');+ return null;+ }+}++/** Async `npm view` with a hard timeout — fallback when the registry is unreachable. */+function fetchLatestViaNpm(packageName: string, timeoutMs = 8_000): Promise<string | null> {+ return new Promise((resolve) => {+ execFile(+ 'npm',+ ['view', packageName, 'version'],+ // npm is `npm.cmd` on Windows: it needs a shell to spawn.+ { timeout: timeoutMs, encoding: 'utf-8', shell: process.platform === 'win32' },+ (err, stdout) => {+ resolve(err ? null : String(stdout).trim() || null);+ },+ );});}+async function fetchLatestNpmVersion(packageName: string, timeoutMs = 8_000): Promise<string | null> {+ return (await fetchLatestFromRegistry(packageName, timeoutMs)) ?? fetchLatestViaNpm(packageName, timeoutMs);+}+/*** Background update check. Throttled (one remote look-up per CHECK_INTERVAL_MS* across ALL boots), fully async, silent on failure. Returns the latest