@taco-ai/cli 0.1.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/LICENSE +21 -0
- package/README.md +27 -0
- package/bin/taco.cjs +56 -0
- package/dist/taco.mjs +104 -0
- package/lib/index.ts +102 -0
- package/lib/install.ts +85 -0
- package/lib/installHelpers.ts +140 -0
- package/lib/installId.ts +75 -0
- package/lib/installLaunchd.ts +194 -0
- package/lib/installSchtasks.ts +127 -0
- package/lib/paths.ts +100 -0
- package/lib/sidecarLauncher.ts +179 -0
- package/lib/start.ts +381 -0
- package/lib/startLock.ts +109 -0
- package/lib/status.ts +74 -0
- package/lib/stop.ts +108 -0
- package/lib/uninstall.ts +25 -0
- package/lib/uninstallLaunchd.ts +36 -0
- package/lib/uninstallSchtasks.ts +25 -0
- package/lib/upgrade.ts +254 -0
- package/lib/upgradeApply.ts +178 -0
- package/lib/upgradeLogger.ts +32 -0
- package/lib/upgradeMarker.ts +69 -0
- package/lib/upgradePlatform.ts +37 -0
- package/lib/upgradeTypes.ts +40 -0
- package/package.json +39 -0
package/lib/startLock.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
// READY_TIMEOUT_MS is 5s and a failed waitForSocket kills the child, so a healthy
|
|
5
|
+
// holder releases in ≲6s; 15s is 2.5× headroom for cold starts on slow disks while
|
|
6
|
+
// still reclaiming a kill -9'd holder inside the window a human would spend retrying.
|
|
7
|
+
export const START_LOCK_TTL_MS = 15_000;
|
|
8
|
+
|
|
9
|
+
interface LockState {
|
|
10
|
+
pid: number;
|
|
11
|
+
acquiredAt: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface StartLockHandle {
|
|
15
|
+
readonly path: string;
|
|
16
|
+
release(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function readStartLock(path: string): Promise<LockState | null> {
|
|
20
|
+
try {
|
|
21
|
+
const content = await readFile(path, "utf8");
|
|
22
|
+
const parsed = JSON.parse(content);
|
|
23
|
+
if (
|
|
24
|
+
typeof parsed === "object" &&
|
|
25
|
+
parsed !== null &&
|
|
26
|
+
typeof parsed.pid === "number" &&
|
|
27
|
+
typeof parsed.acquiredAt === "number"
|
|
28
|
+
) {
|
|
29
|
+
return parsed;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
} catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function acquireStartLock(
|
|
38
|
+
runDir: string,
|
|
39
|
+
now: () => number = Date.now,
|
|
40
|
+
): Promise<StartLockHandle | null> {
|
|
41
|
+
const lockPath = join(runDir, "start.lock");
|
|
42
|
+
|
|
43
|
+
// Ensure the directory exists
|
|
44
|
+
await mkdir(runDir, { recursive: true });
|
|
45
|
+
|
|
46
|
+
const lockData = { pid: process.pid, acquiredAt: now() };
|
|
47
|
+
const lockContent = JSON.stringify(lockData);
|
|
48
|
+
|
|
49
|
+
// Attempt to write with exclusive flag
|
|
50
|
+
let acquired = false;
|
|
51
|
+
try {
|
|
52
|
+
await writeFile(lockPath, lockContent, { flag: "wx", encoding: "utf8" });
|
|
53
|
+
acquired = true;
|
|
54
|
+
} catch (err) {
|
|
55
|
+
// If file already exists, check if it's stale
|
|
56
|
+
if ((err as NodeJS.ErrnoException).code === "EEXIST") {
|
|
57
|
+
const existing = await readStartLock(lockPath);
|
|
58
|
+
|
|
59
|
+
// Determine if the lock is stale
|
|
60
|
+
const isStale = existing === null || now() - existing.acquiredAt > START_LOCK_TTL_MS;
|
|
61
|
+
|
|
62
|
+
if (isStale) {
|
|
63
|
+
// Try to reclaim: unlink and retry once
|
|
64
|
+
try {
|
|
65
|
+
await unlink(lockPath);
|
|
66
|
+
} catch {
|
|
67
|
+
// If unlink fails, someone else may have already reclaimed it
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
await writeFile(lockPath, lockContent, {
|
|
72
|
+
flag: "wx",
|
|
73
|
+
encoding: "utf8",
|
|
74
|
+
});
|
|
75
|
+
acquired = true;
|
|
76
|
+
} catch (retryErr) {
|
|
77
|
+
// If retry also fails with EEXIST, we lost the race
|
|
78
|
+
if ((retryErr as NodeJS.ErrnoException).code === "EEXIST") {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
throw retryErr;
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
// Lock is not stale, so we cannot acquire it
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
throw err;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (!acquired) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
path: lockPath,
|
|
98
|
+
async release(): Promise<void> {
|
|
99
|
+
try {
|
|
100
|
+
await unlink(lockPath);
|
|
101
|
+
} catch (err) {
|
|
102
|
+
// Swallow ENOENT errors; idempotent release
|
|
103
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
104
|
+
throw err;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
package/lib/status.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `taco status` — query the running daemon via the control socket.
|
|
3
|
+
*
|
|
4
|
+
* Sends a single `control.ping` JSON-RPC request and prints the daemon's
|
|
5
|
+
* version / protocol / uptime / pid reply as JSON. Useful for liveness checks
|
|
6
|
+
* from shell scripts (`taco status >/dev/null || taco start`) and for human
|
|
7
|
+
* diagnosis of "is the daemon actually up?".
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { connect, type Socket } from "node:net";
|
|
11
|
+
import { controlSocketPath } from "./paths.ts";
|
|
12
|
+
|
|
13
|
+
const PING_TIMEOUT_MS = 2_000;
|
|
14
|
+
|
|
15
|
+
interface ControlReplyOk {
|
|
16
|
+
result: unknown;
|
|
17
|
+
id: number;
|
|
18
|
+
}
|
|
19
|
+
interface ControlReplyErr {
|
|
20
|
+
error: { code: string; message: string };
|
|
21
|
+
id: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sendControlRequest(socketPath: string, method: string): Promise<unknown> {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const sock: Socket = connect(socketPath);
|
|
27
|
+
let buf = "";
|
|
28
|
+
let done = false;
|
|
29
|
+
const finish = (fn: () => void) => {
|
|
30
|
+
if (done) return;
|
|
31
|
+
done = true;
|
|
32
|
+
sock.destroy();
|
|
33
|
+
fn();
|
|
34
|
+
};
|
|
35
|
+
const timer = setTimeout(() => {
|
|
36
|
+
finish(() => reject(new Error(`${method} timed out after ${PING_TIMEOUT_MS}ms`)));
|
|
37
|
+
}, PING_TIMEOUT_MS);
|
|
38
|
+
|
|
39
|
+
sock.once("error", (err) => {
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
finish(() => reject(new Error(`${method}: ${err.message}`)));
|
|
42
|
+
});
|
|
43
|
+
sock.once("connect", () => {
|
|
44
|
+
sock.write(`${JSON.stringify({ method, id: 1 })}\n`);
|
|
45
|
+
});
|
|
46
|
+
sock.on("data", (chunk) => {
|
|
47
|
+
buf += chunk.toString("utf8");
|
|
48
|
+
const nl = buf.indexOf("\n");
|
|
49
|
+
if (nl < 0) return;
|
|
50
|
+
const line = buf.slice(0, nl);
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
try {
|
|
53
|
+
const reply = JSON.parse(line) as ControlReplyOk | ControlReplyErr;
|
|
54
|
+
if ("error" in reply) {
|
|
55
|
+
finish(() => reject(new Error(`${reply.error.code}: ${reply.error.message}`)));
|
|
56
|
+
} else {
|
|
57
|
+
finish(() => resolve(reply.result));
|
|
58
|
+
}
|
|
59
|
+
} catch (err) {
|
|
60
|
+
finish(() => reject(new Error(`malformed reply: ${String(err)}`)));
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
sock.on("close", () => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
if (!done) finish(() => reject(new Error("socket closed before reply")));
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function statusCommand(): Promise<void> {
|
|
71
|
+
const control = controlSocketPath();
|
|
72
|
+
const result = await sendControlRequest(control, "control.ping");
|
|
73
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
74
|
+
}
|
package/lib/stop.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `taco stop` — ask the running daemon to shut down via the control socket.
|
|
3
|
+
*
|
|
4
|
+
* Sends a single `control.shutdown` JSON-RPC request and waits for the
|
|
5
|
+
* `{result: {ok: true}}` reply (the daemon flushes the reply before exiting,
|
|
6
|
+
* so a successful read here means the shutdown ack was accepted). Then we
|
|
7
|
+
* wait up to 3s for the NDJSON socket file to disappear (the daemon
|
|
8
|
+
* unlinks both sockets on its way out — see `unlinkSocketSync` in
|
|
9
|
+
* packages/sidecar/src/index.ts). If it lingers past the deadline, we
|
|
10
|
+
* report that the daemon accepted shutdown but the cleanup is taking longer
|
|
11
|
+
* than expected — operator-visible rather than silently broken.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { connect, type Socket } from "node:net";
|
|
15
|
+
import { controlSocketPath } from "./paths.ts";
|
|
16
|
+
|
|
17
|
+
const SHUTDOWN_ACK_TIMEOUT_MS = 3_000;
|
|
18
|
+
const SOCKET_GONE_TIMEOUT_MS = 3_000;
|
|
19
|
+
|
|
20
|
+
interface ControlReplyOk {
|
|
21
|
+
result: unknown;
|
|
22
|
+
id: number;
|
|
23
|
+
}
|
|
24
|
+
interface ControlReplyErr {
|
|
25
|
+
error: { code: string; message: string };
|
|
26
|
+
id: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sendControlRequest(socketPath: string, method: string): Promise<unknown> {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const sock: Socket = connect(socketPath);
|
|
32
|
+
let buf = "";
|
|
33
|
+
let done = false;
|
|
34
|
+
const finish = (fn: () => void) => {
|
|
35
|
+
if (done) return;
|
|
36
|
+
done = true;
|
|
37
|
+
sock.destroy();
|
|
38
|
+
fn();
|
|
39
|
+
};
|
|
40
|
+
const timer = setTimeout(() => {
|
|
41
|
+
finish(() =>
|
|
42
|
+
reject(new Error(`${method} timed out after ${SHUTDOWN_ACK_TIMEOUT_MS}ms`)),
|
|
43
|
+
);
|
|
44
|
+
}, SHUTDOWN_ACK_TIMEOUT_MS);
|
|
45
|
+
|
|
46
|
+
sock.once("error", (err) => {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
finish(() => reject(new Error(`${method}: ${err.message}`)));
|
|
49
|
+
});
|
|
50
|
+
sock.once("connect", () => {
|
|
51
|
+
sock.write(`${JSON.stringify({ method, id: 1 })}\n`);
|
|
52
|
+
});
|
|
53
|
+
sock.on("data", (chunk) => {
|
|
54
|
+
buf += chunk.toString("utf8");
|
|
55
|
+
const nl = buf.indexOf("\n");
|
|
56
|
+
if (nl < 0) return;
|
|
57
|
+
const line = buf.slice(0, nl);
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
try {
|
|
60
|
+
const reply = JSON.parse(line) as ControlReplyOk | ControlReplyErr;
|
|
61
|
+
if ("error" in reply) {
|
|
62
|
+
finish(() =>
|
|
63
|
+
reject(new Error(`${method}: ${reply.error.code} ${reply.error.message}`)),
|
|
64
|
+
);
|
|
65
|
+
} else {
|
|
66
|
+
finish(() => resolve(reply.result));
|
|
67
|
+
}
|
|
68
|
+
} catch (err) {
|
|
69
|
+
finish(() => reject(new Error(`${method}: malformed reply: ${String(err)}`)));
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
sock.on("close", () => {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
if (!done) {
|
|
75
|
+
finish(() => reject(new Error(`${method}: socket closed before reply`)));
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function waitForSocketGone(path: string): Promise<void> {
|
|
82
|
+
const start = Date.now();
|
|
83
|
+
while (Date.now() - start < SOCKET_GONE_TIMEOUT_MS) {
|
|
84
|
+
// On Unix, stat the file; on Windows, named pipes don't leave
|
|
85
|
+
// filesystem entries so we treat the absence as already gone.
|
|
86
|
+
if (process.platform === "win32") return;
|
|
87
|
+
// existsSync throws if path is unreadable; treat that as "gone" too —
|
|
88
|
+
// the listener has shut down so subsequent connect attempts will fail.
|
|
89
|
+
let exists = true;
|
|
90
|
+
try {
|
|
91
|
+
exists = (await import("node:fs")).existsSync(path);
|
|
92
|
+
} catch {
|
|
93
|
+
exists = false;
|
|
94
|
+
}
|
|
95
|
+
if (!exists) return;
|
|
96
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
97
|
+
}
|
|
98
|
+
throw new Error(`socket ${path} still present after ${SOCKET_GONE_TIMEOUT_MS}ms`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function stopCommand(): Promise<void> {
|
|
102
|
+
const control = controlSocketPath();
|
|
103
|
+
const result = await sendControlRequest(control, "control.shutdown");
|
|
104
|
+
// Daemon flushes the reply, then unlinks + exits. Give it a moment to
|
|
105
|
+
// actually disappear from the filesystem before declaring success.
|
|
106
|
+
await waitForSocketGone(control);
|
|
107
|
+
process.stdout.write(`${JSON.stringify(result ?? { ok: true })}\n`);
|
|
108
|
+
}
|
package/lib/uninstall.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Remove the host service registration without deleting runtime files. */
|
|
2
|
+
|
|
3
|
+
import { uninstallLaunchd as runUninstallLaunchd } from "./uninstallLaunchd.ts";
|
|
4
|
+
import { uninstallSchtasks as runUninstallSchtasks } from "./uninstallSchtasks.ts";
|
|
5
|
+
|
|
6
|
+
export interface UninstallOptions {
|
|
7
|
+
/** Override $TACO_HOME (defaults to env / ~/.taco). */
|
|
8
|
+
tacoHome?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface UninstallResult {
|
|
12
|
+
/** Service manager that was asked to drop the daemon. */
|
|
13
|
+
serviceManager: "launchd" | "schtasks" | "none";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Top-level entry point for `taco uninstall`. */
|
|
17
|
+
export async function uninstallCommand(): Promise<UninstallResult> {
|
|
18
|
+
if (process.platform === "darwin") {
|
|
19
|
+
return runUninstallLaunchd();
|
|
20
|
+
}
|
|
21
|
+
if (process.platform === "win32") {
|
|
22
|
+
return runUninstallSchtasks();
|
|
23
|
+
}
|
|
24
|
+
return { serviceManager: "none" };
|
|
25
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* macOS launchd uninstall path for `taco uninstall`.
|
|
3
|
+
*
|
|
4
|
+
* Reverses `installLaunchd`:
|
|
5
|
+
* 1. `launchctl unload` the plist (ignore non-zero — the agent may
|
|
6
|
+
* already be unloaded after a reboot, and that's fine).
|
|
7
|
+
* 2. `rm -f` the plist file. The wrapper under $TACO_HOME/bin/ stays
|
|
8
|
+
* in place: re-running `taco install` reuses it.
|
|
9
|
+
*
|
|
10
|
+
* Neither the platform pkg under node_modules nor the daemon binary are
|
|
11
|
+
* touched — operators who want a fully clean slate rm them manually.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { existsSync, unlinkSync } from "node:fs";
|
|
15
|
+
import { execFile } from "./installHelpers.ts";
|
|
16
|
+
import { launchdPlistPath } from "./installLaunchd.ts";
|
|
17
|
+
import type { UninstallResult } from "./uninstall.ts";
|
|
18
|
+
|
|
19
|
+
export async function uninstallLaunchd(): Promise<UninstallResult> {
|
|
20
|
+
const plistPath = launchdPlistPath();
|
|
21
|
+
|
|
22
|
+
// `launchctl unload` returns non-zero when the agent isn't currently
|
|
23
|
+
// loaded (e.g. user rebooted, then ran uninstall before any session
|
|
24
|
+
// started). That's the desired end state — don't surface it as an error.
|
|
25
|
+
if (existsSync(plistPath)) {
|
|
26
|
+
await execFile("launchctl", ["unload", plistPath], { allowFailure: true });
|
|
27
|
+
try {
|
|
28
|
+
unlinkSync(plistPath);
|
|
29
|
+
} catch {
|
|
30
|
+
// The file was removed between the existsSync check and unlink;
|
|
31
|
+
// another process (or `taco install` racing) cleaned up. Fine.
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return { serviceManager: "launchd" };
|
|
36
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows schtasks uninstall path for `taco uninstall`.
|
|
3
|
+
*
|
|
4
|
+
* Reverses `installSchtasks`:
|
|
5
|
+
* 1. `schtasks /Delete /TN TacoSidecar /F` — ignore non-zero (the task
|
|
6
|
+
* may already be gone after a manual cleanup).
|
|
7
|
+
* 2. Wrapper script under $TACO_HOME\bin\ stays in place: re-running
|
|
8
|
+
* `taco install` reuses it.
|
|
9
|
+
*
|
|
10
|
+
* Neither the platform pkg under node_modules nor the daemon binary are
|
|
11
|
+
* touched — operators who want a fully clean slate rm them manually.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { execFile } from "./installHelpers.ts";
|
|
15
|
+
import { SCHTASKS_NAME } from "./installSchtasks.ts";
|
|
16
|
+
import type { UninstallResult } from "./uninstall.ts";
|
|
17
|
+
|
|
18
|
+
export async function uninstallSchtasks(): Promise<UninstallResult> {
|
|
19
|
+
// `schtasks /Delete` returns non-zero when the task doesn't exist
|
|
20
|
+
// (e.g. user never ran `taco install`, or already cleaned up). That's
|
|
21
|
+
// the desired end state — don't surface it as an error.
|
|
22
|
+
await execFile("schtasks", ["/Delete", "/TN", SCHTASKS_NAME, "/F"], { allowFailure: true });
|
|
23
|
+
|
|
24
|
+
return { serviceManager: "schtasks" };
|
|
25
|
+
}
|
package/lib/upgrade.ts
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `taco upgrade` — fetch the latest sidecar bundle for the current
|
|
3
|
+
* platform from the npm registry, verify integrity, extract to staging,
|
|
4
|
+
* and write the upgrade marker so the daemon's orchestrator can shut
|
|
5
|
+
* itself down on its next recheck.
|
|
6
|
+
*
|
|
7
|
+
* Why npm registry (not GitHub Releases):
|
|
8
|
+
* release-sidecar.yml publishes platform pkgs to `@taco-ai/sidecar-<plat>`
|
|
9
|
+
* on npm; GitHub Releases aren't part of the v0.1.0 pipeline. The npm
|
|
10
|
+
* registry is the source of truth, supports anonymous GETs, and ships
|
|
11
|
+
* an `integrity` (sha512-base64) field we verify against the
|
|
12
|
+
* downloaded bytes.
|
|
13
|
+
*
|
|
14
|
+
* Layout on disk after a successful run:
|
|
15
|
+
* $TACO_HOME/cache/sidecar/<platform>-<version>.tgz downloaded tarball
|
|
16
|
+
* $TACO_HOME/staging/sidecar-<platform>-<version>/ extracted bundle
|
|
17
|
+
* $TACO_HOME/upgrade-marker.json the marker
|
|
18
|
+
*
|
|
19
|
+
* The daemon's UpgradeOrchestrator reads the marker on its 6h recheck,
|
|
20
|
+
* sees the staging dir exists, and asks the host to shut down. The UI's
|
|
21
|
+
* reconnect loop then runs `taco upgrade --apply` (commit 6's companion)
|
|
22
|
+
* which swaps staging into live and restarts.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { createHash } from "node:crypto";
|
|
26
|
+
import { createReadStream } from "node:fs";
|
|
27
|
+
import { mkdir, open, rm, stat } from "node:fs/promises";
|
|
28
|
+
import { dirname, join } from "node:path";
|
|
29
|
+
import { extract } from "tar";
|
|
30
|
+
import { TACO_HOME } from "./paths.ts";
|
|
31
|
+
import { createLogger } from "./upgradeLogger.ts";
|
|
32
|
+
import { writeUpgradeMarker } from "./upgradeMarker.ts";
|
|
33
|
+
import { currentPlatformPkg } from "./upgradePlatform.ts";
|
|
34
|
+
import type { PackageMetadata, UpgradeMarker, UpgradeResult } from "./upgradeTypes.ts";
|
|
35
|
+
|
|
36
|
+
const log = createLogger("taco.cli.upgrade");
|
|
37
|
+
|
|
38
|
+
const NPM_REGISTRY = "https://registry.npmjs.org";
|
|
39
|
+
const FETCH_TIMEOUT_MS = 30_000;
|
|
40
|
+
|
|
41
|
+
/** Test/CLI seam — replace `fetch` to inject canned responses. */
|
|
42
|
+
export type Fetcher = typeof fetch;
|
|
43
|
+
|
|
44
|
+
export interface UpgradeOptions {
|
|
45
|
+
/** Override `fetch` (tests inject a fake here). */
|
|
46
|
+
fetcher?: Fetcher;
|
|
47
|
+
/** Override `$TACO_HOME` (defaults to env / ~/.taco). */
|
|
48
|
+
tacoHome?: string;
|
|
49
|
+
/** Override version (`"latest"` by default; tests pin a specific version). */
|
|
50
|
+
version?: string;
|
|
51
|
+
/** Override platform key (tests pin to `darwin-arm64` etc.). */
|
|
52
|
+
platformKey?: string;
|
|
53
|
+
/** Override the npm registry URL (for tests + private registries). */
|
|
54
|
+
registry?: string;
|
|
55
|
+
/** Override the current install's pkgDir (tests pin to a tmpdir). */
|
|
56
|
+
liveDirOverride?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Fetch the npm metadata doc for `pkg@version`. */
|
|
60
|
+
async function fetchMetadata(
|
|
61
|
+
registry: string,
|
|
62
|
+
pkg: string,
|
|
63
|
+
version: string,
|
|
64
|
+
fetcher: Fetcher,
|
|
65
|
+
): Promise<PackageMetadata> {
|
|
66
|
+
const url =
|
|
67
|
+
version === "latest" ? `${registry}/${pkg}/latest` : `${registry}/${pkg}/${version}`;
|
|
68
|
+
const controller = new AbortController();
|
|
69
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
70
|
+
try {
|
|
71
|
+
const res = await fetcher(url, { signal: controller.signal });
|
|
72
|
+
if (!res.ok) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`registry returned ${res.status} ${res.statusText} for ${pkg}@${version}`,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
return (await res.json()) as PackageMetadata;
|
|
78
|
+
} finally {
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Stream a URL into `dest` and return the total bytes written. Throws
|
|
84
|
+
* on non-2xx; the caller decides whether to retry. */
|
|
85
|
+
async function downloadToFile(url: string, dest: string, fetcher: Fetcher): Promise<number> {
|
|
86
|
+
const controller = new AbortController();
|
|
87
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
88
|
+
try {
|
|
89
|
+
const res = await fetcher(url, { signal: controller.signal });
|
|
90
|
+
if (!res.ok) {
|
|
91
|
+
throw new Error(`tarball download ${res.status} ${res.statusText} for ${url}`);
|
|
92
|
+
}
|
|
93
|
+
if (!res.body) throw new Error(`tarball response had no body for ${url}`);
|
|
94
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
95
|
+
const file = await open(dest, "w");
|
|
96
|
+
try {
|
|
97
|
+
let total = 0;
|
|
98
|
+
const reader = res.body.getReader();
|
|
99
|
+
while (true) {
|
|
100
|
+
const { done, value } = await reader.read();
|
|
101
|
+
if (done) break;
|
|
102
|
+
await file.write(value);
|
|
103
|
+
total += value.byteLength;
|
|
104
|
+
}
|
|
105
|
+
return total;
|
|
106
|
+
} finally {
|
|
107
|
+
await file.close();
|
|
108
|
+
}
|
|
109
|
+
} finally {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Verify the downloaded file against `sha512-<base64>`. Throws on mismatch. */
|
|
115
|
+
async function verifyIntegrity(filePath: string, integrity: string): Promise<void> {
|
|
116
|
+
const [algo, expected] = integrity.split("-");
|
|
117
|
+
if (algo !== "sha512") {
|
|
118
|
+
throw new Error(`unsupported integrity algorithm: ${algo}`);
|
|
119
|
+
}
|
|
120
|
+
const hash = createHash("sha512");
|
|
121
|
+
await new Promise<void>((resolve, reject) => {
|
|
122
|
+
const stream = createReadStream(filePath);
|
|
123
|
+
stream.on("data", (chunk) => hash.update(chunk));
|
|
124
|
+
stream.on("end", () => resolve());
|
|
125
|
+
stream.on("error", reject);
|
|
126
|
+
});
|
|
127
|
+
const actual = hash.digest("base64");
|
|
128
|
+
if (actual !== expected) {
|
|
129
|
+
throw new Error(`integrity mismatch: expected ${expected}, got ${actual}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Top-level entry point for `taco upgrade`. Throws on any failure; the
|
|
134
|
+
* CLI dispatcher's `.catch` surfaces the message + exits non-zero. */
|
|
135
|
+
export async function upgradeCommand(opts: UpgradeOptions = {}): Promise<UpgradeResult> {
|
|
136
|
+
const fetcher: Fetcher = opts.fetcher ?? globalThis.fetch;
|
|
137
|
+
if (typeof fetcher !== "function") {
|
|
138
|
+
throw new Error("global fetch is not available; pass opts.fetcher explicitly");
|
|
139
|
+
}
|
|
140
|
+
const tacoHome = opts.tacoHome ?? TACO_HOME;
|
|
141
|
+
const registry = opts.registry ?? NPM_REGISTRY;
|
|
142
|
+
const platform = opts.platformKey
|
|
143
|
+
? {
|
|
144
|
+
key: opts.platformKey as ReturnType<typeof currentPlatformPkg>["key"],
|
|
145
|
+
pkg: `@taco-ai/sidecar-${opts.platformKey}`,
|
|
146
|
+
}
|
|
147
|
+
: currentPlatformPkg();
|
|
148
|
+
const version = opts.version ?? "latest";
|
|
149
|
+
|
|
150
|
+
log.info(`fetching metadata for ${platform.pkg}@${version}`);
|
|
151
|
+
const metadata = await fetchMetadata(registry, platform.pkg, version, fetcher);
|
|
152
|
+
if (!metadata.dist?.tarball || !metadata.dist?.integrity) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
`registry response missing dist.tarball/integrity for ${platform.pkg}@${version}`,
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Use the resolved version (not "latest") for the on-disk layout so
|
|
159
|
+
// re-running upgrade picks up the same staging dir rather than racing.
|
|
160
|
+
const resolvedVersion = metadata.version;
|
|
161
|
+
const resolvedStagingDir = join(
|
|
162
|
+
tacoHome,
|
|
163
|
+
"staging",
|
|
164
|
+
`sidecar-${platform.key}-${resolvedVersion}`,
|
|
165
|
+
);
|
|
166
|
+
const tarballPath = join(
|
|
167
|
+
tacoHome,
|
|
168
|
+
"cache",
|
|
169
|
+
"sidecar",
|
|
170
|
+
`sidecar-${platform.key}-${resolvedVersion}.tgz`,
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
log.info(`downloading tarball → ${tarballPath}`);
|
|
174
|
+
await mkdir(dirname(tarballPath), { recursive: true });
|
|
175
|
+
await downloadToFile(metadata.dist.tarball, tarballPath, fetcher);
|
|
176
|
+
|
|
177
|
+
log.info("verifying integrity");
|
|
178
|
+
await verifyIntegrity(tarballPath, metadata.dist.integrity);
|
|
179
|
+
|
|
180
|
+
// Wipe any prior staging dir for this version (interrupted prior run).
|
|
181
|
+
await rm(resolvedStagingDir, { recursive: true, force: true });
|
|
182
|
+
await mkdir(resolvedStagingDir, { recursive: true });
|
|
183
|
+
|
|
184
|
+
log.info(`extracting → ${resolvedStagingDir}`);
|
|
185
|
+
await extract({
|
|
186
|
+
file: tarballPath,
|
|
187
|
+
cwd: resolvedStagingDir,
|
|
188
|
+
// npm tarballs wrap everything in a single `package/` top-level dir;
|
|
189
|
+
// strip it so the staging layout matches the platform pkg's expected
|
|
190
|
+
// shape (manifest.json + bin/ + lib/).
|
|
191
|
+
strip: 1,
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
// Sanity-check the extracted dir has the bundle's expected files; a
|
|
195
|
+
// tarball that extracted but is missing manifest.json would be an
|
|
196
|
+
// operator-confusing silent failure downstream.
|
|
197
|
+
await assertBundleShape(resolvedStagingDir);
|
|
198
|
+
|
|
199
|
+
const liveDir = opts.liveDirOverride ?? (await resolveLiveDir(platform.key));
|
|
200
|
+
if (!liveDir) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`no current @taco-ai/sidecar-${platform.key} install found; run 'taco install' first`,
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const marker: UpgradeMarker = {
|
|
207
|
+
version: resolvedVersion,
|
|
208
|
+
staging_dir: resolvedStagingDir,
|
|
209
|
+
live_dir: liveDir,
|
|
210
|
+
written_at: new Date().toISOString(),
|
|
211
|
+
};
|
|
212
|
+
const markerPath = join(tacoHome, "upgrade-marker.json");
|
|
213
|
+
await writeUpgradeMarker(markerPath, marker);
|
|
214
|
+
|
|
215
|
+
log.info(`upgrade staged → version=${resolvedVersion}, marker=${markerPath}`);
|
|
216
|
+
return {
|
|
217
|
+
version: resolvedVersion,
|
|
218
|
+
stagingDir: resolvedStagingDir,
|
|
219
|
+
liveDir,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function assertBundleShape(stagingDir: string): Promise<void> {
|
|
224
|
+
for (const relative of ["manifest.json", "bin", "lib"]) {
|
|
225
|
+
const target = join(stagingDir, relative);
|
|
226
|
+
try {
|
|
227
|
+
await stat(target);
|
|
228
|
+
} catch {
|
|
229
|
+
throw new Error(`staged bundle missing ${relative} at ${target}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Resolve the current install's pkgDir for `platformKey`. Mirrors
|
|
235
|
+
* `installHelpers.findPlatformPkg` but for the CLI side; we re-resolve
|
|
236
|
+
* here because the staging flow doesn't have access to the sidecar's
|
|
237
|
+
* installed tree state. */
|
|
238
|
+
async function resolveLiveDir(platformKey: string): Promise<string | null> {
|
|
239
|
+
// createRequire from this module's URL so the CLI package's own
|
|
240
|
+
// node_modules tree is consulted — that's where the platform pkg
|
|
241
|
+
// resolves (the CLI depends on `@taco-ai/sidecar` which hoists
|
|
242
|
+
// its optional deps into the same workspace).
|
|
243
|
+
const { createRequire } = await import("node:module");
|
|
244
|
+
const req = createRequire(import.meta.url);
|
|
245
|
+
try {
|
|
246
|
+
const pkgJsonPath = req.resolve(`@taco-ai/sidecar-${platformKey}/package.json`);
|
|
247
|
+
const idx = pkgJsonPath.lastIndexOf("/package.json");
|
|
248
|
+
return idx < 0 ? pkgJsonPath : pkgJsonPath.slice(0, idx);
|
|
249
|
+
} catch {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// (no exports below — every constant this module needs is already imported)
|