Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import {
} from "./cli/remove-plan.js";
import { portFlagSuffix } from "./cli/ready-hint.js";
import { embeddingStatusLabel } from "./cli/embedding-status.js";
import { expectedIiiSha256, iiiManualInstallCommand, installIiiArchive } from "./cli/engine-install.js";
import { expectedIiiSha256, iiiManualInstallCommand, installIiiArchive, installIiiZip } from "./cli/engine-install.js";
import {
runtimeConfigPath,
redactCredentialUrls,
Expand Down Expand Up @@ -959,12 +959,30 @@ async function runIiiInstaller(): Promise<{ ok: boolean; binPath: string | null
}

if (IS_WINDOWS || isZipAsset) {
p.log.info(
`Auto-install unavailable on ${platform()} — ${asset} isn't tar-compatible. Install manually:\n` +
const binDir = agentmemoryBinDir();
const binPath = privateIiiPath();
const label = `Installing iii-engine v${IIPINNED_VERSION} (pinned)`;
const spinner = p.spinner();
spinner.start(label);
const outcome = await installIiiZip({
releaseUrl,
version: IIPINNED_VERSION,
asset: asset ?? "",
binDir,
binPath,
});
if (outcome.ok) {
spinner.stop(`${label} ${pc.green("✓")}`);
iiiProbeScan?.delete(binPath);
return { ok: true, binPath };
}
spinner.stop(`${label} ${pc.red("✗")}`);
p.log.warn(
`iii-engine auto-install failed: ${outcome.detail.slice(0, 300)}\n` +
`Install it manually, then re-run agentmemory:\n` +
` 1. Download ${releaseUrl}\n` +
` Its SHA-256 must be ${expectedIiiSha256(IIPINNED_VERSION, asset ?? "") ?? `the value in ${releaseUrl.replace(/\.zip$/, ".sha256")}`}\n` +
` 2. Extract iii.exe and place it on PATH (e.g. %USERPROFILE%\\.local\\bin)\n` +
`Install the pinned iii binary from ${releaseUrl}`,
` 2. Extract iii.exe into ${binDir}`,
);
return { ok: false, binPath: null };
}
Expand Down Expand Up @@ -1483,7 +1501,7 @@ function installInstructions(): string[] {
` 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv${IIPINNED_VERSION}`,
` 2. Download iii-x86_64-pc-windows-msvc.zip (or iii-aarch64-pc-windows-msvc.zip on ARM)`,
verify,
" 3. Extract iii.exe to %USERPROFILE%\\.local\\bin\\iii.exe (or add to PATH)",
" 3. Extract iii.exe to %USERPROFILE%\\.agentmemory\\bin\\iii.exe (or add to PATH)",
" 4. Re-run: npx @agentmemory/agentmemory",
"",
"Or skip the engine entirely (standalone MCP): npx @agentmemory/agentmemory mcp",
Expand Down
245 changes: 241 additions & 4 deletions src/cli/engine-install.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { basename, join } from "node:path";

export const III_INSTALL_CONNECT_TIMEOUT_S = 15;
export const III_INSTALL_MAX_TIME_S = 300;
Expand Down Expand Up @@ -140,3 +140,240 @@ export function installIiiArchive(opts: {
}
return { ok: true };
}

export type ZipRunResult = {
status: number | null;
stdout?: string | null;
stderr?: string | null;
error?: Error & { code?: string };
signal?: NodeJS.Signals | null;
};

export type ZipCommandRunner = (command: string, args: string[]) => ZipRunResult | Promise<ZipRunResult>;

export type ZipDownloader = (url: string, dest: string) => Promise<void>;

export function iiiZipArchivePath(binDir: string): string {
return join(binDir, `.iii-download-${process.pid}-${randomBytes(4).toString("hex")}.zip`);
}

function removeQuietly(path: string): void {
try {
rmSync(path, { force: true, recursive: true });
} catch {}
}
Comment thread
rohitg00 marked this conversation as resolved.
Resolved

export const STALE_INSTALL_FILE_MS = 15 * 60 * 1000;

export function removeStaleInstallFiles(binDir: string, now: number = Date.now()): string[] {
const removed: string[] = [];
let entries: string[];
try {
entries = readdirSync(binDir);
} catch {
return removed;
}
for (const name of entries) {
if (!name.startsWith(".iii-download-") && !name.startsWith(".iii-staging-")) continue;
const path = join(binDir, name);
try {
if (now - statSync(path).mtimeMs < STALE_INSTALL_FILE_MS) continue;
} catch {
continue;
}
removeQuietly(path);
if (!existsSync(path)) removed.push(name);
}
return removed;
}

const PROXY_ENV_KEYS = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"];

export function proxyConfigured(env: NodeJS.ProcessEnv): boolean {
return PROXY_ENV_KEYS.some((key) => Boolean(env[key]?.trim()));
}

export function windowsCurlDownloadCommand(
url: string,
dest: string,
env: NodeJS.ProcessEnv = process.env,
): { command: string; args: string[] } {
const systemRoot = env["SystemRoot"] || env["SYSTEMROOT"] || "C:\\Windows";
return {
command: join(systemRoot, "System32", "curl.exe"),
args: [
"-fsSL",
"--connect-timeout",
String(III_INSTALL_CONNECT_TIMEOUT_S),
"--max-time",
String(III_INSTALL_MAX_TIME_S),
"-o",
dest,
url,
],
};
}

export function powershellLiteral(value: string): string {
return `'${value.replace(/'/g, "''")}'`;
}

export function windowsZipExtractCommands(
archive: string,
binDir: string,
env: NodeJS.ProcessEnv = process.env,
): { command: string; args: string[] }[] {
const systemRoot = env["SystemRoot"] || env["SYSTEMROOT"] || "C:\\Windows";
const system32 = join(systemRoot, "System32");
return [
{ command: join(system32, "tar.exe"), args: ["-xf", archive, "-C", binDir] },
{
command: join(system32, "WindowsPowerShell", "v1.0", "powershell.exe"),
args: [
"-NoProfile",
"-NonInteractive",
"-Command",
`Expand-Archive -LiteralPath ${powershellLiteral(archive)} -DestinationPath ${powershellLiteral(binDir)} -Force`,
],
},
];
}

export async function downloadToFile(
url: string,
dest: string,
env: NodeJS.ProcessEnv = process.env,
run: ZipCommandRunner = runInstallCommand,
): Promise<void> {
if (proxyConfigured(env)) {
const step = windowsCurlDownloadCommand(url, dest, env);
const result = await run(step.command, step.args);
if (result.status !== 0) throw new Error(describeInstallFailure(result));
return;
}
const res = await fetch(url, {
redirect: "follow",
signal: AbortSignal.timeout(III_INSTALL_MAX_TIME_S * 1000),
});
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
if (!res.ok) throw new Error(`download failed with HTTP ${res.status} ${res.statusText}`.trim());
writeFileSync(dest, Buffer.from(await res.arrayBuffer()));
}

export function runInstallCommand(command: string, args: string[]): Promise<ZipRunResult> {
return new Promise((done) => {
let stdout = "";
let stderr = "";
let timedOut = false;
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, shell: false });
const killOnExit = () => {
try {
child.kill();
} catch {}
};
process.once("exit", killOnExit);
const timer = setTimeout(() => {
timedOut = true;
child.kill();
}, III_INSTALL_SPAWN_TIMEOUT_MS);
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
child.stdout?.on("data", (chunk) => { stdout += chunk; });
child.stderr?.on("data", (chunk) => { stderr += chunk; });
let spawnError: (Error & { code?: string }) | undefined;
child.on("error", (error: Error & { code?: string }) => {
spawnError = error;
if (child.pid !== undefined) return;
clearTimeout(timer);
process.off("exit", killOnExit);
done({ status: null, stdout, stderr, error });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
child.on("close", (status, signal) => {
clearTimeout(timer);
process.off("exit", killOnExit);
if (spawnError && status === null && !timedOut) {
done({ status: null, stdout, stderr, signal, error: spawnError });
return;
}
if (timedOut) {
done({ status: null, stdout, stderr, signal, error: Object.assign(new Error("timed out"), { code: "ETIMEDOUT" }) });
return;
}
done({ status, stdout, stderr, signal });
});
});
}

export async function installIiiZip(opts: {
releaseUrl: string;
version: string;
asset: string;
binDir: string;
binPath: string;
env?: NodeJS.ProcessEnv;
checksums?: ChecksumTable;
download?: ZipDownloader;
run?: ZipCommandRunner;
}): Promise<IiiInstallOutcome> {
const expected = expectedIiiSha256(opts.version, opts.asset, opts.checksums);
if (!expected) {
return {
ok: false,
reason: "no-checksum",
detail: `no pinned SHA-256 for ${opts.asset} in iii v${opts.version}, so the download cannot be verified`,
};
}
const run = opts.run ?? runInstallCommand;
const download = opts.download ?? ((url: string, dest: string) => downloadToFile(url, dest, opts.env ?? process.env, run));
const archive = iiiZipArchivePath(opts.binDir);

try {
mkdirSync(opts.binDir, { recursive: true });
removeStaleInstallFiles(opts.binDir);
await download(opts.releaseUrl, archive);
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
} catch (err) {
removeQuietly(archive);
return { ok: false, reason: "download", detail: err instanceof Error ? err.message : String(err) };
}

let actual: string;
try {
actual = sha256File(archive);
} catch (err) {
removeQuietly(archive);
return { ok: false, reason: "download", detail: err instanceof Error ? err.message : String(err) };
}
if (actual !== expected) {
removeQuietly(archive);
return {
ok: false,
reason: "checksum",
detail: `SHA-256 mismatch for ${opts.asset}: expected ${expected}, got ${actual}. The download was deleted and nothing was installed`,
};
}

const staging = join(opts.binDir, `.iii-staging-${process.pid}-${randomBytes(4).toString("hex")}`);
const staged = join(staging, basename(opts.binPath));
const failures: string[] = [];
try {
for (const step of windowsZipExtractCommands(archive, staging, opts.env)) {
removeQuietly(staging);
mkdirSync(staging, { recursive: true });
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
const result = await run(step.command, step.args);
if (result.status === 0 && existsSync(staged)) {
try {
renameSync(staged, opts.binPath);
return { ok: true };
} catch (err) {
failures.push(`could not move ${staged} to ${opts.binPath}: ${err instanceof Error ? err.message : String(err)}`);
break;
}
}
failures.push(`${step.command}: ${result.status === 0 ? `finished but ${basename(opts.binPath)} is missing from the archive` : describeInstallFailure(result)}`);
}
return { ok: false, reason: "extract", detail: failures.join("; ") };
} catch (err) {
failures.push(err instanceof Error ? err.message : String(err));
return { ok: false, reason: "extract", detail: failures.join("; ") };
} finally {
removeQuietly(staging);
removeQuietly(archive);
}
}
Loading
Loading