Skip to content
TypeScript

bye npm (#20148)

Julius Marminge6b450c75b5db
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 201312f589c..972b85c8477 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -689,11 +689,8 @@ jobs:
resource_key: win32-arm64
cli_archive: true
- # npm gets the same bytes as the GitHub Release: the launcher plus one
- # package per CLI archive. Preview publishes too, under the `preview`
- # dist-tag, which nothing resolves unless asked for by name.
- publish_cli:
- name: Publish CLI to npm
+ release:
+ name: Publish GitHub Release
needs:
[
preflight,
@@ -702,74 +699,13 @@ jobs:
test,
test_server,
desktop_mac_arm64,
- desktop_linux_x64,
- desktop_linux_arm64,
- desktop_win_x64,
- desktop_win_arm64,
- ]
- if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.quality.result == 'success' && needs.test.result == 'success' && needs.test_server.result == 'success' && needs.desktop_mac_arm64.result == 'success' && needs.desktop_linux_x64.result == 'success' && needs.desktop_linux_arm64.result == 'success' && needs.desktop_win_x64.result == 'success' && needs.desktop_win_arm64.result == 'success' }}
- runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
- timeout-minutes: 15
- permissions:
- contents: read
- id-token: write
- steps:
- - name: Checkout
- uses: actions/checkout@v6
- with:
- ref: ${{ needs.preflight.outputs.ref }}
- sparse-checkout: |
- /*
- !/.repos/
- sparse-checkout-cone-mode: false
-
- - name: Setup Vite+
- uses: voidzero-dev/setup-vp@v1
- with:
- node-version-file: package.json
- cache: true
- run-install: |
- args:
- - --filter=t3...
- - --filter=@t3tools/scripts...
-
- - name: Download all CLI archives
- uses: actions/download-artifact@v8
- with:
- pattern: cli-*
- merge-multiple: true
- path: release-cli
-
- - name: Build npm packages from CLI archives
- run: node scripts/build-npm-platform-packages.ts --archives-dir release-cli --version "${{ needs.preflight.outputs.version }}" --output-dir npm-packages
-
- # A dry run of every package first: an auth or scope error here (the
- # @t3code org missing, a package without a trusted publisher) fails
- # before anything is live, instead of after some platforms already are.
- - name: Check npm publish access (dry run)
- run: |
- if ! node apps/server/scripts/cli.ts publish --packages-dir npm-packages --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --provenance --dry-run --verbose; then
- echo "::error::npm publish --dry-run failed. Make sure the @t3code npm org exists and that t3 and every @t3code/t3-<platform> package has a trusted publisher registered for .github/workflows/release.yml (see docs/operations/release.md)." >&2
- exit 1
- fi
-
- - name: Publish CLI packages
- run: node apps/server/scripts/cli.ts publish --packages-dir npm-packages --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --provenance --verbose
-
- release:
- name: Publish GitHub Release
- needs:
- [
- preflight,
- desktop_mac_arm64,
desktop_mac_x64,
desktop_linux_x64,
desktop_linux_arm64,
desktop_win_x64,
desktop_win_arm64,
- publish_cli,
]
- if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.desktop_mac_arm64.result == 'success' && needs.desktop_mac_x64.result == 'success' && needs.desktop_linux_x64.result == 'success' && needs.desktop_linux_arm64.result == 'success' && needs.desktop_win_x64.result == 'success' && needs.desktop_win_arm64.result == 'success' && needs.publish_cli.result == 'success' }}
+ if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.quality.result == 'success' && needs.test.result == 'success' && needs.test_server.result == 'success' && needs.desktop_mac_arm64.result == 'success' && needs.desktop_mac_x64.result == 'success' && needs.desktop_linux_x64.result == 'success' && needs.desktop_linux_arm64.result == 'success' && needs.desktop_win_x64.result == 'success' && needs.desktop_win_arm64.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 30
permissions:
@@ -957,6 +893,49 @@ jobs:
fail_on_unmatched_files: true
token: ${{ github.token }}
+ # The `t3` npm package is a launcher that downloads this version's CLI
+ # archive from the GitHub Release, so it publishes only once that release
+ # exists. Preview publishes too, under the `preview` dist-tag, which
+ # nothing resolves unless asked for by name.
+ publish_cli:
+ name: Publish CLI to npm
+ needs: [preflight, release]
+ if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
+ runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
+ timeout-minutes: 15
+ permissions:
+ contents: read
+ id-token: write
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+ with:
+ ref: ${{ needs.preflight.outputs.ref }}
+ sparse-checkout: |
+ /*
+ !/.repos/
+ sparse-checkout-cone-mode: false
+
+ - name: Setup Vite+
+ uses: voidzero-dev/setup-vp@v1
+ with:
+ node-version-file: package.json
+ cache: true
+ run-install: |
+ args:
+ - --filter=t3...
+ - --filter=@t3tools/scripts...
+
+ - name: Build the npm launcher
+ run: node scripts/build-npm-launcher.ts --version "${{ needs.preflight.outputs.version }}" --output-dir npm-packages
+
+ - name: Publish the npm launcher
+ run: |
+ if ! node apps/server/scripts/cli.ts publish --packages-dir npm-packages --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --provenance --verbose; then
+ echo "::error::npm publish failed. Make sure package t3 has a trusted publisher registered for .github/workflows/release.yml (see docs/operations/release.md)." >&2
+ exit 1
+ fi
+
publish_aur:
name: Publish AUR package
needs: [preflight, release]
@@ -1074,8 +1053,8 @@ jobs:
deploy_web:
name: Deploy hosted web app
- needs: [preflight, build_web, release]
- if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build_web.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel != 'preview' }}
+ needs: [preflight, build_web, release, publish_cli]
+ if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build_web.result == 'success' && needs.release.result == 'success' && needs.publish_cli.result == 'success' && needs.preflight.outputs.release_channel != 'preview' }}
runs-on: blacksmith-2vcpu-ubuntu-2404
timeout-minutes: 10
env:
diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.ts
index 81d618aca81..fca0adeb690 100644
--- a/apps/server/scripts/cli.ts
+++ b/apps/server/scripts/cli.ts
@@ -19,7 +19,6 @@ import {
ServerCliDevelopmentIconTargetMissingError,
ServerCliExecutableImportError,
} from "./cliErrors.ts";
-import { publishPlatformsThenLauncher } from "./publishOrder.ts";
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
@@ -155,17 +154,15 @@ const buildExeCmd = Command.make(
);
/**
- * Publishes the tarballs scripts/build-npm-platform-packages.ts produced:
- * every `@t3code/t3-<platform>.tgz` first, `t3.tgz` (the launcher) last, so
- * the launcher is never installable before the executables it depends on.
- * Tarballs rather than directories because `npm publish <dir>` strips the
- * `node_modules/` the executable loads its native addons from.
+ * Publishes the `t3.tgz` launcher scripts/build-npm-launcher.ts produced. The
+ * launcher downloads its executable from the GitHub Release, so the release
+ * workflow runs this only after that release is published.
*/
const publishCmd = Command.make(
"publish",
{
packagesDir: Flag.String("packages-dir").pipe(
- Flag.withDescription("Output dir of scripts/build-npm-platform-packages.ts."),
+ Flag.withDescription("Output dir of scripts/build-npm-launcher.ts."),
),
tag: Flag.String("tag").pipe(Flag.withDefault("latest")),
access: Flag.String("access").pipe(Flag.withDefault("public")),
@@ -178,19 +175,7 @@ const publishCmd = Command.make(
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const packagesDir = path.resolve(config.packagesDir);
- const scopeDir = path.join(packagesDir, "@t3code");
const launcherTarball = path.join(packagesDir, "t3.tgz");
- const platformTarballs = (yield* fs
- .readDirectory(scopeDir)
- .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => [])))
- .filter((entry) => entry.startsWith("t3-") && entry.endsWith(".tgz"))
- .sort()
- .map((entry) => path.join(scopeDir, entry));
- if (platformTarballs.length === 0) {
- return yield* new ServerCliBuildAssetMissingError({
- assetPath: path.join(scopeDir, "t3-<platform>.tgz"),
- });
- }
if (!(yield* fs.exists(launcherTarball))) {
return yield* new ServerCliBuildAssetMissingError({ assetPath: launcherTarball });
}
@@ -198,27 +183,18 @@ const publishCmd = Command.make(
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
-
- const publish = Effect.fn("publish")(function* (tarball: string) {
- const spawnCommand = yield* resolveSpawnCommand("npm", [...args, tarball]);
- yield* Effect.log(`[cli] npm ${args.join(" ")} ${path.basename(tarball)}`);
- yield* runCommand(
- ChildProcess.make(spawnCommand.command, spawnCommand.args, {
- cwd: packagesDir,
- stdout: config.verbose ? "inherit" : "ignore",
- stderr: "inherit",
- shell: spawnCommand.shell,
- }),
- );
- });
-
- yield* publishPlatformsThenLauncher({ platformTarballs, launcherTarball, publish });
+ const spawnCommand = yield* resolveSpawnCommand("npm", [...args, launcherTarball]);
+ yield* Effect.log(`[cli] npm ${args.join(" ")} t3.tgz`);
+ yield* runCommand(
+ ChildProcess.make(spawnCommand.command, spawnCommand.args, {
+ cwd: packagesDir,
+ stdout: config.verbose ? "inherit" : "ignore",
+ stderr: "inherit",
+ shell: spawnCommand.shell,
+ }),
+ );
}),
-).pipe(
- Command.withDescription(
- "Publish the @t3code/t3-<platform> tarballs and then the t3 launcher to npm.",
- ),
-);
+).pipe(Command.withDescription("Publish the t3 launcher to npm."));
const cli = Command.make("cli").pipe(
Command.withDescription("T3 server build & publish CLI."),
diff --git a/apps/server/scripts/publishOrder.test.ts b/apps/server/scripts/publishOrder.test.ts
deleted file mode 100644
index aedc6e152df..00000000000
--- a/apps/server/scripts/publishOrder.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { assert, it } from "@effect/vitest";
-import * as Effect from "effect/Effect";
-import * as Exit from "effect/Exit";
-import * as Latch from "effect/Latch";
-
-import { publishPlatformsThenLauncher } from "./publishOrder.ts";
-
-const platformTarballs = ["a.tgz", "b.tgz", "c.tgz"];
-const launcherTarball = "t3.tgz";
-
-const fakePublish = Effect.fn("fakePublish")(function* (failing?: string) {
- const events: Array<string> = [];
- const allStarted = yield* Latch.make();
- let started = 0;
- const publish = (tarball: string) =>
- Effect.gen(function* () {
- events.push(`start ${tarball}`);
- if (tarball === launcherTarball) return;
- started += 1;
- if (started === platformTarballs.length) yield* allStarted.open;
- if (tarball === failing) return yield* Effect.fail(`${tarball} failed`);
- yield* allStarted.await;
- events.push(`end ${tarball}`);
- });
- return { events, publish };
-});
-
-it.effect("publishes the platform packages at once and the launcher last", () =>
- Effect.gen(function* () {
- const { events, publish } = yield* fakePublish();
-
- yield* publishPlatformsThenLauncher({ platformTarballs, launcherTarball, publish });
-
- assert.deepStrictEqual(events.slice(0, 3).toSorted(), [
- "start a.tgz",
- "start b.tgz",
- "start c.tgz",
- ]);
- assert.strictEqual(events.at(-1), `start ${launcherTarball}`);
- }),
-);
-
-it.effect("finishes the other uploads and skips the launcher when one fails", () =>
- Effect.gen(function* () {
- const { events, publish } = yield* fakePublish("b.tgz");
-
- const exit = yield* Effect.exit(
- publishPlatformsThenLauncher({ platformTarballs, launcherTarball, publish }),
- );
-
- assert.deepStrictEqual(exit, Exit.fail("b.tgz failed"));
- assert.includeMembers(events, ["end a.tgz", "end c.tgz"]);
- assert.notInclude(events, `start ${launcherTarball}`);
- }),
-);
diff --git a/apps/server/scripts/publishOrder.ts b/apps/server/scripts/publishOrder.ts
deleted file mode 100644
index eedf8970983..00000000000
--- a/apps/server/scripts/publishOrder.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import * as Effect from "effect/Effect";
-import * as Result from "effect/Result";
-
-/**
- * Publishes every platform package at once, then the launcher, which must never
- * be installable before the executables it points to. When one platform fails,
- * the other uploads still finish rather than being interrupted: npm never
- * accepts the same version twice, and an interrupted upload may already be
- * live.
- */
-export const publishPlatformsThenLauncher = <E, R>(input: {
- readonly platformTarballs: ReadonlyArray<string>;
- readonly launcherTarball: string;
- readonly publish: (tarball: string) => Effect.Effect<void, E, R>;
-}) =>
- Effect.gen(function* () {
- const results = yield* Effect.all(input.platformTarballs.map(input.publish), {
- concurrency: "unbounded",
- mode: "result",
- });
- const failed = results.find(Result.isFailure);
- if (failed) {
- return yield* Effect.fail(failed.failure);
- }
- yield* input.publish(input.launcherTarball);
- });
diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts
index d765378152a..54b5124feb0 100644
--- a/apps/server/src/cli/invocation.test.ts
+++ b/apps/server/src/cli/invocation.test.ts
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
+import packageJson from "../../package.json" with { type: "json" };
import {
formatCliCommand,
resolveHostCliCommand,
@@ -226,24 +227,36 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => {
});
it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
- it.effect("recognizes runner caches for both script and executable packages", () =>
+ it.effect("recognizes runner caches for script packages and the npm launcher", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped();
+ const executable = path.join(root, ".t3/runtime/versions/1.0.0/t3");
+ yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
+ yield* fs.writeFileString(executable, "");
for (const [relative, kind] of [
["npm/_npx/hash/node_modules/t3/dist/bin.mjs", "npx"],
- ["npm/_npx/hash/node_modules/@t3code/t3-linux-x64/t3", "npx"],
+ ["npm/_npx/hash/node_modules/t3/bin/t3.mjs", "npx"],
["pnpm/dlx/hash/node_modules/t3/dist/bin.mjs", "pnpm-dlx"],
[".bun/install/cache/t3/dist/bin.mjs", "bunx"],
] as const) {
const entry = path.join(root, relative);
yield* fs.makeDirectory(path.dirname(entry), { recursive: true });
yield* fs.writeFileString(entry, "");
+ yield* fs.writeFileString(
+ path.join(path.dirname(entry), "../package.json"),
+ `{"name":"t3","version":"${packageJson.version}","bin":{"t3":"./bin/t3.mjs"}}`,
+ );
+ const launchedBy = entry.endsWith("t3.mjs");
const installation = yield* resolveServerInstallation.pipe(
- Effect.provideService(HostProcess.Arguments, ["node", entry]),
- Effect.provideService(HostProcess.ExecutablePath, entry),
- Effect.provideService(HostProcess.IsExecutable, entry.endsWith("/t3")),
+ Effect.provideService(HostProcess.Arguments, [launchedBy ? executable : "node", entry]),
+ Effect.provideService(HostProcess.ExecutablePath, executable),
+ Effect.provideService(HostProcess.IsExecutable, launchedBy),
+ Effect.provideService(
+ HostProcess.Environment,
+ launchedBy ? { T3CODE_NPM_LAUNCHER_PATH: entry } : {},
+ ),
);
expect(installation).toEqual({ kind });
}
@@ -281,37 +294,37 @@ it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
}),
);
- it.effect("proves the native executable belongs to the npm launcher", () =>
+ it.effect("proves the downloaded executable was started by a global npm launcher", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped();
const prefix = path.join(root, "bunx-tools");
const packageRoot = path.join(prefix, "lib/node_modules/t3");
- const launcher = path.join(packageRoot, "bin/t3.js");
- const entry = path.join(packageRoot, "node_modules/@t3code/t3-linux-x64/t3");
+ const launcher = path.join(packageRoot, "bin/t3.mjs");
+ const executable = path.join(root, ".t3/runtime/versions/1.0.0/t3");
yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
- yield* fs.makeDirectory(path.dirname(entry), { recursive: true });
+ yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
yield* fs.makeDirectory(path.join(prefix, "bin"));
yield* fs.writeFileString(launcher, "");
- yield* fs.writeFileString(entry, "");
- yield* fs.writeFileString(
- path.join(packageRoot, "package.json"),
- '{"name":"t3","version":"0.0.45","bin":{"t3":"./bin/t3.js"},"optionalDependencies":{"@t3code/t3-linux-x64":"0.0.45"}}',
- );
+ yield* fs.writeFileString(executable, "");
yield* fs.symlink(launcher, path.join(prefix, "bin/t3"));
const resolve = resolveServerInstallation.pipe(
- Effect.provideService(HostProcess.ExecutablePath, entry),
+ Effect.provideService(HostProcess.ExecutablePath, executable),
+ Effect.provideService(HostProcess.Arguments, [executable, executable]),
Effect.provideService(HostProcess.IsExecutable, true),
Effect.provideService(HostProcess.Platform, "linux"),
+ Effect.provideService(HostProcess.Environment, { T3CODE_NPM_LAUNCHER_PATH: launcher }),
);
+ // A launcher for another version is some other `t3` the server spawned
+ // (the variable is inherited), not the install this executable runs from.
for (const [version, expected] of [
- ["0.0.44", null],
- ["0.0.45", { kind: "npm-global", prefix }],
- ]) {
+ ["0.0.1", null],
+ [packageJson.version, { kind: "npm-global", prefix }],
+ ] as const) {
yield* fs.writeFileString(
- path.join(path.dirname(entry), "package.json"),
- `{"name":"@t3code/t3-linux-x64","version":"${version}"}`,
+ path.join(packageRoot, "package.json"),
+ `{"name":"t3","version":"${version}","bin":{"t3":"./bin/t3.mjs"}}`,
);
expect(yield* resolve).toEqual(expected);
}
diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts
index 5134f2110f0..6fe0304307b 100644
--- a/apps/server/src/cli/invocation.ts
+++ b/apps/server/src/cli/invocation.ts
@@ -35,22 +35,45 @@ const InstallManifest = Schema.Struct({
name: Schema.String,
version: Schema.String,
bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })),
- optionalDependencies: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
});
const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest));
+/**
+ * The script this CLI was started through: the `t3` npm launcher that
+ * downloaded and ran this executable (it names itself in
+ * `T3CODE_NPM_LAUNCHER_PATH`), or the Node entry script of a build run from
+ * source. A standalone executable has none and reports its own path.
+ *
+ * The variable is inherited by everything the server spawns, so a launcher
+ * counts only when its package is this exact version: a different `t3` run
+ * from an agent's shell must not claim to be the npm install.
+ */
+const resolveEntryPath = Effect.gen(function* () {
+ const npmLauncher = (yield* HostProcess.Environment).T3CODE_NPM_LAUNCHER_PATH?.trim();
+ if (npmLauncher) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const manifest = yield* fs
+ .readFileString(path.join(path.dirname(npmLauncher), "../package.json"))
+ .pipe(Effect.flatMap(decodeInstallManifest), Effect.option);
+ if (
+ Option.isSome(manifest) &&
+ manifest.value.name === "t3" &&
+ manifest.value.version === packageJson.version
+ ) {
+ return npmLauncher;
+ }
+ }
+ if (yield* HostProcess.IsExecutable) return yield* HostProcess.ExecutablePath;
+ return (yield* HostProcess.Arguments)[1] ?? "";
+});
+
export const resolveServerInstallation = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
- const args = yield* HostProcess.Arguments;
- const executable = yield* HostProcess.IsExecutable;
- const executablePath = yield* HostProcess.ExecutablePath;
const platform = yield* HostProcess.Platform;
- const entry = yield* fs.realPath(executable ? executablePath : (args[1] ?? ""));
- const match =
- /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.js|node_modules\/@t3code\/t3-[^/]+\/t3)$/.exec(
- entry,
- );
+ const entry = yield* fs.realPath(yield* resolveEntryPath);
+ const match = /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.mjs)$/.exec(entry);
if (!match) {
const runner = detectCliRunner(entry);
return runner === null
@@ -73,20 +96,7 @@ export const resolveServerInstallation = Effect.gen(function* () {
if (manifest.name !== "t3" || !manifest.bin) return null;
const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3));
const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3"));
- if (globalBin !== bin) return null;
- if (executable) {
- const nativeManifest = yield* fs
- .readFileString(path.join(path.dirname(entry), "package.json"))
- .pipe(Effect.flatMap(decodeInstallManifest));
- if (
- manifest.bin.t3 !== "./bin/t3.js" ||
- manifest.optionalDependencies?.[nativeManifest.name] !== nativeManifest.version ||
- nativeManifest.version !== manifest.version
- )
- return null;
- } else if (bin !== entry) {
- return null;
- }
+ if (globalBin !== bin || bin !== entry) return null;
return { kind: "npm-global", prefix } satisfies ServerInstallation;
}).pipe(Effect.orElseSucceed(() => null));
@@ -113,12 +123,8 @@ export function formatCliCommand(input: {
}
export const resolveCliCommand = (subcommand: string) =>
- Effect.map(HostProcess.Arguments, (processArguments) =>
- formatCliCommand({
- subcommand,
- entryPath: processArguments[1] ?? "",
- version: packageJson.version,
- }),
+ Effect.map(resolveEntryPath, (entryPath) =>
+ formatCliCommand({ subcommand, entryPath, version: packageJson.version }),
);
const shellWord = (value: string) =>
diff --git a/docs/operations/release.md b/docs/operations/release.md
index c85ce8ee847..87622f1d9be 100644
--- a/docs/operations/release.md
+++ b/docs/operations/release.md
@@ -43,15 +43,15 @@ the version.
- Automatically generated release notes are pinned to the previous tag in the same channel, so stable compares to the previous stable tag and nightly compares to the previous nightly tag.
- Includes Electron auto-update metadata (for example `latest*.yml`, `nightly*.yml`, and `*.blockmap`) in release assets.
- Builds a self-contained CLI archive per platform (`t3-<version>-<platform>-<arch>.tar.gz`, `.zip` on Windows) in the same job as that target's desktop artifact and attaches them to the GitHub Release with a `SHA256SUMS` file, on every channel, for five targets: macOS arm64, Linux x64 and arm64, Windows x64 and arm64. Every archive is built, signed, and smoke-tested on hardware of its own architecture. There is no macOS x64 archive: Node single-executables are unsupported on x64 macOS (the SEA docs list macOS as arm64 only) and the binary segfaults on start; the x64 desktop app is Electron and unaffected.
- - The archive holds the server as a Node single-executable (`scripts/build-cli-archive.ts`), so unpacking it needs neither Node, npm, nor a compiler. It is the only form in which T3 Code manages a runtime: the desktop's SSH environments, the boot service, `t3 update`, and the install scripts all download and verify this archive against `SHA256SUMS`. The npm packages exist for people who run `npx t3` or `npm install -g t3` themselves and carry the same archive contents; nothing in the product installs from npm. The `curl | sh` installers are `scripts/install.sh` and `scripts/install.ps1`; the marketing site copies them into its `public/` at build time (`apps/marketing/scripts/stage-install-scripts.mjs`) and serves them at `t3.codes/install.sh` and `/install.ps1`.
+ - The archive holds the server as a Node single-executable (`scripts/build-cli-archive.ts`), so unpacking it needs neither Node, npm, nor a compiler. It is the only form in which T3 Code manages a runtime: the desktop's SSH environments, the boot service, `t3 update`, and the install scripts all download and verify this archive against `SHA256SUMS`. The `t3` npm package exists for people who run `npx t3` or `npm install -g t3` themselves, and it downloads this same archive too; nothing in the product installs from npm. The `curl | sh` installers are `scripts/install.sh` and `scripts/install.ps1`; the marketing site copies them into its `public/` at build time (`apps/marketing/scripts/stage-install-scripts.mjs`) and serves them at `t3.codes/install.sh` and `/install.ps1`.
- The executable is built with a Node that supports `--build-sea` (`VP_NODE_VERSION=26.8.2`, kept in step with `SEA_NODE_VERSION` in `apps/server/vite.config.ts`), while the repo stays on `engines.node`.
- macOS archives are signed with the Developer ID certificate and notarized when the Apple secrets are present (ad hoc otherwise, which still runs from `curl`/`tar` installs). Windows executables use the same Azure Trusted Signing setup as the installer. Every native addon in the macOS archive is signed too, since the hardened runtime refuses unsigned libraries.
- Each archive is extracted and executed on its build runner (`scripts/smoke-cli-archive.ts`) before it is uploaded.
-- Publishes the CLI to npm with OIDC trusted publishing from the same workflow file, as the same bytes the GitHub Release carries: `scripts/build-npm-platform-packages.ts` unpacks the five CLI archives into `@t3code/t3-<platform>-<arch>` packages (each with `os`/`cpu` set so npm installs only the matching one) and generates the `t3` launcher, whose `bin/t3.js` lists them as `optionalDependencies` and execs the installed executable. `npx t3` therefore needs Node only to run the launcher, never to run the server. `node apps/server/scripts/cli.ts publish` publishes the platform packages first and the launcher last, after a `--dry-run` pass over all of them so an auth or scope error fails before anything is live.
+- After the GitHub Release is published, publishes the `t3` npm package with OIDC trusted publishing from the same workflow file. It is only a launcher (`scripts/npm-launcher/t3.mjs`): on first run it downloads its exact version's CLI archive from the GitHub Release, verifies it against `SHA256SUMS`, and unpacks it into `<T3 home>/runtime/versions/<version>`, the layout the install scripts and `t3 update` share. The executables are not on npm. They used to be, as `@t3code/t3-<platform>-<arch>` optional dependencies, but npm's publish-time scanning held those 80-250 MB packages back for up to an hour after the launcher was live, and every install in that window got a launcher with no executable. Those packages stay on npm at their old versions and get no new ones. Because the launcher reads from the release, `publish_cli` runs after `release`, never before.
- stable releases publish npm dist-tag `latest`
- nightly releases publish npm dist-tag `nightly`
- preview releases publish npm dist-tag `preview`, which nothing resolves unless asked for by name
- - one-time setup: the `@t3code` npm scope (org) must exist, and `t3` and each `@t3code/t3-<platform>-<arch>` package needs a trusted publisher registered for this workflow file (see below).
+ - one-time setup: package `t3` needs a trusted publisher registered for this workflow file (see below).
- Builds the hosted web app on Vercel while the desktop jobs run, and makes it live only after a release is published:
- stable releases are aliased to the `latest` hosted app channel
- nightly releases are aliased to the `nightly` hosted app channel
@@ -408,25 +408,31 @@ One-time Vercel dashboard setup:
- `make_latest` is always `false`
- Uses the next stable patch version as the nightly base. For example, `0.0.17` produces nightlies on `0.0.18-nightly.*`.
- Publishes Electron auto-update metadata to the dedicated `nightly` updater channel, so desktop users can opt into that track independently from stable.
-- Publishes the CLI npm packages (`t3` and `@t3code/t3-<platform>-<arch>`) to the `nightly` npm dist-tag using the same nightly version.
+- Publishes the `t3` npm launcher to the `nightly` npm dist-tag using the same nightly version.
- Does not commit version bumps back to `main`.
## Server self-update release invariant
-Connected servers update to the client's exact version, not to an npm dist-tag. Every released
-desktop or hosted client version must therefore have a matching `t3@<version>` package available on
-npm before users can receive that client.
+Connected servers update to the client's exact version, not to an npm dist-tag. Servers that update
+themselves download that version's CLI archive from the GitHub Release; servers run through npm are
+handed a `t3@<version>` command to run. Every released client version must therefore have its
+release archives, and then its npm launcher, available before users can receive that client.
The workflow enforces this ordering:
-1. `publish_cli` publishes the exact release version to npm, on every channel.
-2. `release` depends on `publish_cli` before exposing desktop artifacts in GitHub Releases.
-3. `deploy_web` depends on `release` before moving the hosted channel to the new client.
+1. `release` publishes the GitHub Release with the CLI archives and `SHA256SUMS`.
+2. `publish_cli` publishes the `t3@<version>` launcher, which downloads from that release, on every
+ channel.
+3. `deploy_web` depends on both before moving the hosted channel to the new client.
`build_web` builds that client earlier with `vercel deploy --prod --skip-domain`, which
leaves the custom domains alone but moves the project's own `*.vercel.app` production
hostname. That hostname is behind Vercel SSO, so users only get the client through the
custom domains.
+Desktop auto-update reads the GitHub Release directly, so a desktop client can see the new version
+a few minutes before `t3@<version>` is on npm. Only the copied manual command for npm-run servers
+depends on npm, and it works once `publish_cli` finishes.
+
Preserve these dependencies when changing the release graph. Publishing a client first would leave
the **Update server** action targeting a package version that does not exist yet.
@@ -508,32 +514,21 @@ blockmaps, with a 60 MB maximum for a representative sidecar-to-sidecar update.
## 0) npm OIDC trusted publishing setup (CLI)
-The workflow runs `node scripts/build-npm-platform-packages.ts` on the downloaded CLI archives, then
+After the GitHub Release is published, the workflow runs `node scripts/build-npm-launcher.ts`, then
`node apps/server/scripts/cli.ts publish --packages-dir npm-packages`, which runs `npm publish` on
-each `@t3code/t3-<platform>-<arch>.tgz` and finally on `t3.tgz`, the launcher. The script publishes
-tarballs it built itself rather than directories: `npm publish <dir>` strips `node_modules/` from the
-tarball no matter what `files` says, and the executable loads its native addons from there. Seven
-packages are published per release: `t3`, `@t3code/t3-darwin-arm64`, `@t3code/t3-darwin-x64`,
-`@t3code/t3-linux-arm64`, `@t3code/t3-linux-x64`, `@t3code/t3-win32-arm64`,
-`@t3code/t3-win32-x64`.
+`t3.tgz`. That is the only package published per release.
Checklist:
-1. Confirm the npm org owns package `t3` and the `@t3code` scope exists on npm (create the org if
- it does not).
-2. For `t3` and each `@t3code/t3-<platform>-<arch>` package, configure a Trusted Publisher in the
- npm package settings (a package that has never been published needs a first publish or a
- placeholder before the setting exists; the `--dry-run` step in `publish_cli` reports which
- names are still rejected):
+1. Confirm the npm org owns package `t3`.
+2. For `t3`, configure a Trusted Publisher in the npm package settings:
- Provider: GitHub Actions
- Repository: this repo
- Workflow file: `.github/workflows/release.yml`
- Environment (if used): match your npm trusted publishing config
-3. Ensure npm account and org policies allow trusted publishing for every package.
-4. Create release tag `vX.Y.Z` and push; workflow will:
- - build and smoke-test the five CLI archives
- - build the npm packages from those archives
- - publish them with npm dist-tag `latest`
+3. Ensure npm account and org policies allow trusted publishing for the package.
+4. Create release tag `vX.Y.Z` and push; the workflow publishes the GitHub Release and then the
+ launcher with npm dist-tag `latest`.
5. Nightly runs publish with npm dist-tag `nightly`; preview runs with `preview`.
## 1) Release validation and unsigned builds
diff --git a/knip.jsonc b/knip.jsonc
index 6e16e4b25a1..12c661fd083 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -20,6 +20,8 @@
// Knip loads its preprocessor through a CLI option; native verification and
// worktree setup (from t3.json) run directly.
"entry": ["knip-schemas.ts", "mobile-native-client.ts", "setup-worktree.ts"],
+ // The `t3` npm package's files: copied into the package, never imported.
+ "ignore": ["npm-launcher/**"],
},
"apps/server": {
// Vite+ pack entries and the launcher used by installed background services.
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 4b78dfb9543..22f240aa163 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -15,10 +15,6 @@
"types": "./src/orchestrationV2ThreadError.ts",
"import": "./src/orchestrationV2ThreadError.ts"
},
- "./legacyCliLauncher": {
- "types": "./src/legacyCliLauncher.ts",
- "import": "./src/legacyCliLauncher.ts"
- },
"./delimitedPreview": {
"types": "./src/delimitedPreview.ts",
"import": "./src/delimitedPreview.ts"
diff --git a/packages/shared/src/cliRelease.ts b/packages/shared/src/cliRelease.ts
index 4a8a535da0c..c029592bee2 100644
--- a/packages/shared/src/cliRelease.ts
+++ b/packages/shared/src/cliRelease.ts
@@ -10,7 +10,7 @@ export const CLI_RELEASE_BASE_URL_ENV = "T3CODE_RELEASE_BASE_URL";
*/
// No darwin-x64: Node single-executables are unsupported on x64 macOS (the
// SEA docs list macOS as arm64 only) and the binary segfaults on start.
-export const CLI_ARCHIVE_PLATFORM_KEYS = [
+const CLI_ARCHIVE_PLATFORM_KEYS = [
"darwin-arm64",
"linux-arm64",
"linux-x64",
diff --git a/packages/shared/src/legacyCliLauncher.test.ts b/packages/shared/src/legacyCliLauncher.test.ts
deleted file mode 100644
index 447c5a12e84..00000000000
--- a/packages/shared/src/legacyCliLauncher.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-// @effect-diagnostics nodeBuiltinImport:off - Exercises real Node IPC and process signals.
-import * as NodeChildProcess from "node:child_process";
-import * as NodeEvents from "node:events";
-import * as NodeFSP from "node:fs/promises";
-import * as NodeOS from "node:os";
-import * as NodePath from "node:path";
-import { expect, it } from "vite-plus/test";
-
-import { legacyCliLauncherScript } from "./legacyCliLauncher.ts";
-
-// oxlint-disable-next-line t3code/no-global-process-runtime -- This test launches a real host executable.
-const hostPlatform = NodeOS.platform();
-// oxlint-disable-next-line t3code/no-global-process-runtime -- Match the real executable used by the subprocess.
-const hostArch = NodeOS.arch();
-
-// The fixture executable uses a POSIX shebang.
-it.skipIf(hostPlatform === "win32")(
- "keeps service IPC, arguments, and termination connected",
- async () => {
- const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-legacy-launcher-"));
- const entry = NodePath.join(root, "node_modules/t3/dist/bin.mjs");
- const executable = NodePath.join(
- root,
- `node_modules/@t3code/t3-${hostPlatform}-${hostArch}/t3`,
- );
- await NodeFSP.mkdir(NodePath.dirname(entry), { recursive: true });
- await NodeFSP.mkdir(NodePath.dirname(executable), { recursive: true });
- await NodeFSP.writeFile(
- NodePath.join(NodePath.dirname(executable), "package.json"),
- '{"type":"commonjs"}',
- );
- await NodeFSP.writeFile(entry, legacyCliLauncherScript());
- await NodeFSP.writeFile(
- executable,
- `#!${process.execPath}
-process.on("SIGTERM", () => process.exit(23));
-process.on("message", message => process.send({ reply: message }));
-process.send({ args: process.argv.slice(2) });
-`,
- );
- await NodeFSP.chmod(executable, 0o755);
- const child = NodeChildProcess.fork(entry, ["serve", "a path with spaces"], { silent: true });
- try {
- expect((await NodeEvents.EventEmitter.once(child, "message"))[0]).toEqual({
- args: ["serve", "a path with spaces"],
- });
- const reply = NodeEvents.EventEmitter.once(child, "message");
- child.send({ type: "trial-accepted" });
- expect((await reply)[0]).toEqual({ reply: { type: "trial-accepted" } });
- const exit = NodeEvents.EventEmitter.once(child, "exit");
- child.kill("SIGTERM");
- expect(await exit).toEqual([23, null]);
- } finally {
- if (child.exitCode === null && child.signalCode === null) {
- const exit = NodeEvents.EventEmitter.once(child, "exit");
- child.kill("SIGTERM");
- await exit;
- }
- await NodeFSP.rm(root, { recursive: true, force: true });
- }
- },
-);
diff --git a/packages/shared/src/legacyCliLauncher.ts b/packages/shared/src/legacyCliLauncher.ts
deleted file mode 100644
index 5be30d923b1..00000000000
--- a/packages/shared/src/legacyCliLauncher.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * `dist/bin.mjs` of the `t3` npm package: the entry point boot-service
- * launchers installed before 0.0.41 run with Node to start a new version they
- * just npm-installed.
- */
-export function legacyCliLauncherScript(): string {
- return `import { spawn } from "node:child_process";
-import { constants } from "node:os";
-import { dirname, join } from "node:path";
-import { createRequire } from "node:module";
-const require = createRequire(import.meta.url);
-const executableName = process.platform === "win32" ? "t3.exe" : "t3";
-const executable = join(dirname(require.resolve("@t3code/t3-" + process.platform + "-" + process.arch + "/package.json")), executableName);
-const ipc = process.send !== undefined;
-const child = spawn(executable, process.argv.slice(2), {
- stdio: ipc ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
-});
-const fail = (error) => {
- if (!error) return;
- process.stderr.write("t3: " + error.message + "\\n");
- child.kill("SIGTERM");
- process.exitCode = 1;
-};
-if (ipc) {
- process.on("message", (message) => { if (child.connected) child.send(message, fail); });
- child.on("message", (message) => { if (process.connected) process.send(message, fail); });
- process.on("disconnect", () => { if (child.connected) child.disconnect(); });
-}
-for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
- process.on(signal, () => child.kill(signal));
-}
-child.on("error", (error) => { fail(error); process.exit(1); });
-child.on("exit", (code, signal) => process.exit(code ?? 128 + (constants.signals[signal] || 1)));
-`;
-}
diff --git a/scripts/build-npm-launcher.test.ts b/scripts/build-npm-launcher.test.ts
new file mode 100644
index 00000000000..d1b620e1f29
--- /dev/null
+++ b/scripts/build-npm-launcher.test.ts
@@ -0,0 +1,217 @@
+// @effect-diagnostics nodeBuiltinImport:off - Serves a fake GitHub Release over real HTTP to the published launcher.
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
+import * as NodeChildProcess from "node:child_process";
+import * as NodeCrypto from "node:crypto";
+import * as NodeEvents from "node:events";
+import * as NodeHttp from "node:http";
+
+import { buildNpmLauncher } from "./build-npm-launcher.ts";
+
+const VERSION = "1.2.3";
+const decodeManifest = Schema.decodeEffect(
+ Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
+);
+
+const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
+ stream.pipe(
+ Stream.decodeText(),
+ Stream.runFold(
+ () => "",
+ (acc, chunk) => acc + chunk,
+ ),
+ );
+
+const run = Effect.fn("test.run")(function* (
+ command: string,
+ args: ReadonlyArray<string>,
+ options: { readonly cwd: string; readonly env: Record<string, string | undefined> },
+) {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const child = yield* spawner.spawn(
+ ChildProcess.make(command, args, { cwd: options.cwd, env: options.env, extendEnv: false }),
+ );
+ const [stdout, stderr, exitCode] = yield* Effect.all(
+ [collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
+ { concurrency: "unbounded" },
+ );
+ return { stdout, stderr, exitCode };
+}, Effect.scoped);
+
+/** A release archive for this host with a stub `t3` that echoes its args and launcher. */
+const serveFakeRelease = Effect.fn("test.serveFakeRelease")(function* (root: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const key = `${yield* HostProcess.Platform}-${yield* HostProcess.Architecture}`;
+ const stem = `t3-${VERSION}-${key}`;
+ const archiveName = `${stem}.tar.gz`;
+ yield* fs.makeDirectory(path.join(root, "release", stem, "node_modules/native"), {
+ recursive: true,
+ });
+ yield* fs.writeFileString(
+ path.join(root, "release", stem, "t3"),
+ '#!/bin/sh\necho "stub $* launcher=$T3CODE_NPM_LAUNCHER_PATH"\nexit 7\n',
+ );
+ yield* fs.chmod(path.join(root, "release", stem, "t3"), 0o755);
+ const tar = yield* run("tar", ["-czf", archiveName, stem], {
+ cwd: path.join(root, "release"),
+ env: { PATH: process.env.PATH },
+ });
+ assert.equal(tar.exitCode, 0, tar.stderr);
+ const archive = yield* fs.readFile(path.join(root, "release", archiveName));
+ let checksum = NodeCrypto.createHash("sha256").update(archive).digest("hex");
+ const requests: Array<string> = [];
+ const server = NodeHttp.createServer((request, response) => {
+ requests.push(request.url ?? "");
+ if (request.url === `/v${VERSION}/SHA256SUMS`) {
+ response.end(`${checksum} ${archiveName}\n`);
+ } else if (request.url === `/v${VERSION}/${archiveName}`) {
+ response.writeHead(200, { "Content-Length": archive.length }).end(archive);
+ } else {
+ response.writeHead(404).end();
+ }
+ });
+ yield* Effect.acquireRelease(
+ Effect.callback<void>((resume) => {
+ server.listen(0, "127.0.0.1", () => resume(Effect.void));
+ }),
+ () =>
+ Effect.callback<void>((resume) => {
+ server.close(() => resume(Effect.void));
+ }),
+ );
+ const address = server.address();
+ if (address === null || typeof address === "string") return yield* Effect.die("no TCP address");
+ return {
+ baseUrl: `http://127.0.0.1:${address.port}`,
+ requests,
+ corruptChecksum: () => {
+ checksum = "0".repeat(64);
+ },
+ };
+});
+
+it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
+ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
+ "publishes a launcher that downloads, verifies, caches, and runs the release executable",
+ () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" });
+ const output = yield* buildNpmLauncher({
+ version: VERSION,
+ outputDir: path.join(root, "out"),
+ });
+
+ const manifest = yield* decodeManifest(
+ yield* fs.readFileString(path.join(output.packageDir, "package.json")),
+ );
+ assert.equal(manifest.name, "t3");
+ assert.equal(manifest.version, VERSION);
+ assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
+ // Nothing for npm to resolve, so nothing that can lag behind the launcher.
+ assert.isUndefined(manifest.dependencies);
+ assert.isUndefined(manifest.optionalDependencies);
+
+ // Run what npm would install: the published tarball, unpacked.
+ const installed = path.join(root, "installed");
+ yield* fs.makeDirectory(installed);
+ const unpack = yield* run("tar", ["-xzf", output.tarball, "-C", installed], {
+ cwd: root,
+ env: { PATH: process.env.PATH },
+ });
+ assert.equal(unpack.exitCode, 0, unpack.stderr);
+ const packageDir = path.join(installed, "package");
+
+ const release = yield* serveFakeRelease(root);
+ const home = path.join(root, "home");
+ const env = {
+ PATH: process.env.PATH,
+ T3CODE_HOME: home,
+ T3CODE_RELEASE_BASE_URL: release.baseUrl,
+ };
+ const launcher = path.join(packageDir, "bin/t3.mjs");
+ const first = yield* run(process.execPath, [launcher, "serve", "a b"], {
+ cwd: root,
+ env,
+ });
+ assert.equal(first.stdout.trim(), `stub serve a b launcher=${launcher}`, first.stderr);
+ assert.equal(first.exitCode, 7);
+ // The same layout the install scripts and `t3 update` use.
+ const versionDir = path.join(home, "runtime/versions", VERSION);
+ assert.equal(
+ (yield* fs.readFileString(path.join(versionDir, ".install-complete"))).trim(),
+ VERSION,
+ );
+ assert.isTrue(yield* fs.exists(path.join(versionDir, "node_modules/native")));
+ assert.deepStrictEqual(
+ (yield* fs.readDirectory(path.join(home, "runtime/versions"))).sort(),
+ [VERSION],
+ );
+
+ // A second run reuses the download.
+ const requestsAfterFirst = release.requests.length;
+ const second = yield* run(process.execPath, [launcher, "--version"], { cwd: root, env });
+ assert.equal(second.exitCode, 7);
+ assert.equal(release.requests.length, requestsAfterFirst);
+
+ // Services installed before 0.0.41 fork dist/bin.mjs and talk to the
+ // server over IPC; the channel and SIGTERM must reach the executable.
+ const ipcServer = path.join(home, "runtime/versions", VERSION, "t3");
+ yield* fs.writeFileString(
+ ipcServer,
+ `#!${process.execPath}\nprocess.on("SIGTERM", () => process.exit(23));\nprocess.on("message", (m) => process.send({ reply: m }));\nprocess.send({ args: process.argv.slice(2) });\n`,
+ );
+ const legacy = NodeChildProcess.fork(
+ path.join(packageDir, "dist/bin.mjs"),
+ ["__service-preflight", "a b"],
+ { env, silent: true },
+ );
+ yield* Effect.promise(async () => {
+ assert.deepStrictEqual((await NodeEvents.EventEmitter.once(legacy, "message"))[0], {
+ args: ["__service-preflight", "a b"],
+ });
+ const reply = NodeEvents.EventEmitter.once(legacy, "message");
+ legacy.send({ type: "trial-accepted" });
+ assert.deepStrictEqual((await reply)[0], { reply: { type: "trial-accepted" } });
+ const exit = NodeEvents.EventEmitter.once(legacy, "exit");
+ legacy.kill("SIGTERM");
+ assert.deepStrictEqual(await exit, [23, null]);
+ });
+
+ // Two first runs at once both start, and neither removes the other's install.
+ const raceHome = path.join(root, "race-home");
+ const launch = run(process.execPath, [launcher, "--version"], {
+ cwd: root,
+ env: { ...env, T3CODE_HOME: raceHome },
+ });
+ const [one, two] = yield* Effect.all([launch, launch], { concurrency: "unbounded" });
+ assert.equal(one.exitCode, 7, one.stderr);
+ assert.equal(two.exitCode, 7, two.stderr);
+ assert.deepStrictEqual(yield* fs.readDirectory(path.join(raceHome, "runtime/versions")), [
+ VERSION,
+ ]);
+
+ // A download that does not match the release checksums is never installed.
+ release.corruptChecksum();
+ const corrupt = yield* run(process.execPath, [launcher, "--version"], {
+ cwd: root,
+ env: { ...env, T3CODE_HOME: path.join(root, "other-home") },
+ });
+ assert.equal(corrupt.exitCode, 1);
+ assert.include(corrupt.stderr, "checksum mismatch");
+ assert.deepStrictEqual(
+ yield* fs.readDirectory(path.join(root, "other-home/runtime/versions")),
+ [],
+ );
+ }),
+ );
+});
diff --git a/scripts/build-npm-launcher.ts b/scripts/build-npm-launcher.ts
new file mode 100644
index 00000000000..e12186e90ab
--- /dev/null
+++ b/scripts/build-npm-launcher.ts
@@ -0,0 +1,125 @@
+#!/usr/bin/env node
+/**
+ * Builds the `t3` npm package behind `npx t3` / `npm i -g t3`: a launcher
+ * with no dependencies that downloads this exact version's CLI archive from
+ * the GitHub Release on first run (scripts/npm-launcher/t3.mjs).
+ * The executables are not published to npm. npm's publish-time scanning held
+ * 250 MB platform packages back for up to an hour after the launcher went
+ * live, and every install in that window ran a launcher with nothing to
+ * launch.
+ *
+ * Output: `<output-dir>/t3/` (the package tree) and `<output-dir>/t3.tgz`,
+ * which is what gets published.
+ */
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Logger from "effect/Logger";
+import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
+import { Command, Flag } from "effect/cli";
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
+
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
+import serverPackageJson from "../apps/server/package.json" with { type: "json" };
+
+import { windowsSystemTar } from "./build-cli-archive.ts";
+
+export const NPM_LAUNCHER_PACKAGE_NAME = "t3";
+
+const encodePackageJson = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown));
+
+export class NpmLauncherCommandFailedError extends Schema.TaggedError<NpmLauncherCommandFailedError>()(
+ "NpmLauncherCommandFailedError",
+ { command: Schema.String, exitCode: Schema.Int },
+) {
+ override get message(): string {
+ return `${this.command} exited with code ${this.exitCode}.`;
+ }
+}
+
+/** package.json for the launcher. `engines` asks for `import.meta.dirname` and `fetch`. */
+export function npmLauncherPackageManifest(version: string) {
+ return {
+ name: NPM_LAUNCHER_PACKAGE_NAME,
+ version,
+ description:
+ "T3 Code CLI. Downloads the self-contained executable for this platform from the GitHub Release.",
+ license: serverPackageJson.license,
+ repository: serverPackageJson.repository,
+ bin: { t3: "./bin/t3.mjs" },
+ files: ["bin", "dist"],
+ engines: { node: ">=20.11" },
+ };
+}
+
+export const buildNpmLauncher = Effect.fn("buildNpmLauncher")(function* (input: {
+ readonly version: string;
+ readonly outputDir: string;
+}) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const sourceDir = yield* path.fromFileUrl(new URL("./npm-launcher/", import.meta.url));
+
+ yield* fs.makeDirectory(input.outputDir, { recursive: true });
+ const scratch = yield* fs.makeTempDirectoryScoped({
+ directory: input.outputDir,
+ prefix: ".launcher-",
+ });
+ const stageDir = path.join(scratch, "package");
+ yield* fs.makeDirectory(path.join(stageDir, "bin"), { recursive: true });
+ yield* fs.makeDirectory(path.join(stageDir, "dist"));
+ yield* fs.writeFileString(
+ path.join(stageDir, "package.json"),
+ `${yield* encodePackageJson(npmLauncherPackageManifest(input.version))}\n`,
+ );
+ yield* fs.copyFile(path.join(sourceDir, "t3.mjs"), path.join(stageDir, "bin/t3.mjs"));
+ yield* fs.chmod(path.join(stageDir, "bin/t3.mjs"), 0o755);
+ yield* fs.copyFile(path.join(sourceDir, "bin.mjs"), path.join(stageDir, "dist/bin.mjs"));
+ const readme = yield* path.fromFileUrl(new URL("../apps/server/README.md", import.meta.url));
+ if (yield* fs.exists(readme)) {
+ yield* fs.copyFile(readme, path.join(stageDir, "README.md"));
+ }
+
+ const packageDir = path.join(input.outputDir, NPM_LAUNCHER_PACKAGE_NAME);
+ const tarball = path.join(input.outputDir, `${NPM_LAUNCHER_PACKAGE_NAME}.tgz`);
+ yield* fs.remove(tarball, { force: true });
+ const tar = (yield* HostProcess.Platform) === "win32" ? windowsSystemTar() : "tar";
+ // npm tarballs root everything under `package/`.
+ const child = yield* spawner.spawn(
+ ChildProcess.make(tar, ["-czf", tarball, "-C", scratch, "package"], {
+ stdout: "inherit",
+ stderr: "inherit",
+ }),
+ );
+ const exitCode = Number(yield* child.exitCode);
+ if (exitCode !== 0) {
+ return yield* new NpmLauncherCommandFailedError({ command: `tar (${tarball})`, exitCode });
+ }
+ yield* fs.remove(packageDir, { recursive: true, force: true });
+ yield* fs.rename(stageDir, packageDir);
+ yield* Effect.log(`[npm-launcher] Wrote ${packageDir} and ${tarball}`);
+ return { packageDir, tarball };
+}, Effect.scoped);
+
+const command = Command.make(
+ "build-npm-launcher",
+ {
+ version: Flag.String("version").pipe(
+ Flag.withDescription("Exact release version; the launcher downloads this version's archive."),
+ ),
+ outputDir: Flag.String("output-dir").pipe(Flag.withDefault("npm-packages")),
+ },
+ buildNpmLauncher,
+).pipe(Command.withDescription("Build the t3 npm launcher package."));
+
+if (import.meta.main) {
+ Command.run(command, { version: "0.0.0" }).pipe(
+ Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
+ NodeRuntime.runMain,
+ );
+}
diff --git a/scripts/build-npm-platform-packages.test.ts b/scripts/build-npm-platform-packages.test.ts
deleted file mode 100644
index 6f604db9f51..00000000000
--- a/scripts/build-npm-platform-packages.test.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-import * as HostProcess from "@t3tools/shared/HostProcess";
-import * as NodeServices from "@effect/platform-node/NodeServices";
-import { assert, it } from "@effect/vitest";
-import * as Effect from "effect/Effect";
-import * as FileSystem from "effect/FileSystem";
-import * as Path from "effect/Path";
-import * as Schema from "effect/Schema";
-import * as Stream from "effect/Stream";
-import { ChildProcess, ChildProcessSpawner } from "effect/process";
-
-import {
- buildNpmPlatformPackages,
- NpmPackagesArchivesMissingError,
-} from "./build-npm-platform-packages.ts";
-
-const VERSION = "1.2.3";
-const decodeManifest = Schema.decodeEffect(
- Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
-);
-const KEYS = ["linux-x64", "darwin-arm64"] as const;
-
-const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
- stream.pipe(
- Stream.decodeText(),
- Stream.runFold(
- () => "",
- (acc, chunk) => acc + chunk,
- ),
- );
-
-const run = Effect.fn("test.run")(function* (
- command: string,
- args: ReadonlyArray<string>,
- options: { readonly cwd: string; readonly env?: Record<string, string> },
-) {
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const child = yield* spawner.spawn(
- ChildProcess.make(command, args, { cwd: options.cwd, env: options.env ?? {} }),
- );
- const [stdout, stderr, exitCode] = yield* Effect.all(
- [collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
- { concurrency: "unbounded" },
- );
- return { stdout, stderr, exitCode };
-});
-
-const makeFakeArchives = Effect.fn("test.makeFakeArchives")(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-packages-test-" });
- const archivesDir = path.join(root, "archives");
- yield* fs.makeDirectory(archivesDir);
- for (const key of KEYS) {
- const stem = `t3-${VERSION}-${key}`;
- const stage = path.join(root, "stage", key);
- const contentDir = path.join(stage, stem);
- for (const dir of [
- "client",
- "resource-monitor",
- "node_modules/node-pty",
- "node_modules/@ff-labs/fff-node",
- ]) {
- yield* fs.makeDirectory(path.join(contentDir, dir), { recursive: true });
- }
- yield* fs.writeFileString(
- path.join(contentDir, "node_modules/node-pty/package.json"),
- '{ "name": "node-pty", "version": "1.1.0" }\n',
- );
- yield* fs.writeFileString(
- path.join(contentDir, "node_modules/@ff-labs/fff-node/package.json"),
- '{ "name": "@ff-labs/fff-node", "version": "0.9.4" }\n',
- );
- yield* fs.writeFileString(path.join(contentDir, "client/index.html"), "<html></html>\n");
- yield* fs.writeFileString(
- path.join(contentDir, "t3"),
- `#!/bin/sh\necho "stub ${key} $*"\nexit 7\n`,
- );
- yield* fs.chmod(path.join(contentDir, "t3"), 0o755);
- const exit = yield* run("tar", ["-czf", path.join(archivesDir, `${stem}.tar.gz`), stem], {
- cwd: stage,
- });
- assert.equal(exit.exitCode, 0, exit.stderr);
- }
- yield* fs.writeFileString(path.join(archivesDir, "SHA256SUMS"), "");
- return { root, archivesDir, outputDir: path.join(root, "out") };
-});
-
-it.layer(NodeServices.layer)("build-npm-platform-packages", (it) => {
- it.effect("refuses a partial release unless --allow-missing is passed", () =>
- Effect.gen(function* () {
- const fixture = yield* makeFakeArchives();
- const error = yield* buildNpmPlatformPackages({
- ...fixture,
- version: VERSION,
- allowMissing: false,
- }).pipe(Effect.flip);
- assert.instanceOf(error, NpmPackagesArchivesMissingError);
- assert.deepStrictEqual((error as NpmPackagesArchivesMissingError).missing, [
- "linux-arm64",
- "win32-arm64",
- "win32-x64",
- ]);
- }),
- );
-
- it.effect("builds platform packages and a launcher that execs the installed one", () =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const fixture = yield* makeFakeArchives();
- const outputs = yield* buildNpmPlatformPackages({
- ...fixture,
- version: VERSION,
- allowMissing: true,
- });
- assert.deepStrictEqual(
- outputs.map((output) => output.name),
- ["@t3code/t3-darwin-arm64", "@t3code/t3-linux-x64", "t3"],
- );
- for (const output of outputs) {
- assert.isTrue(yield* fs.exists(output.tarball), output.tarball);
- }
-
- const linuxDir = path.join(fixture.outputDir, "@t3code/t3-linux-x64");
- const linuxManifest = yield* decodeManifest(
- yield* fs.readFileString(path.join(linuxDir, "package.json")),
- );
- assert.equal(linuxManifest.name, "@t3code/t3-linux-x64");
- assert.equal(linuxManifest.version, VERSION);
- assert.deepStrictEqual(linuxManifest.os, ["linux"]);
- assert.deepStrictEqual(linuxManifest.cpu, ["x64"]);
- assert.deepStrictEqual(linuxManifest.files, [
- "t3",
- "t3.exe",
- "client",
- "resource-monitor",
- "node_modules",
- ]);
- assert.equal(linuxManifest.preferUnplugged, true);
- assert.isUndefined(linuxManifest.bin);
- assert.deepStrictEqual(linuxManifest.dependencies, {
- "@ff-labs/fff-node": "0.9.4",
- "node-pty": "1.1.0",
- });
- assert.deepStrictEqual(linuxManifest.bundleDependencies, ["@ff-labs/fff-node", "node-pty"]);
- assert.isTrue(yield* fs.exists(path.join(linuxDir, "client/index.html")));
- assert.include(
- yield* fs.readFileString(path.join(linuxDir, "README.md")),
- "# @t3code/t3-linux-x64",
- );
- assert.isTrue(yield* fs.exists(path.join(linuxDir, "node_modules/node-pty")));
- assert.equal(Number((yield* fs.stat(path.join(linuxDir, "t3"))).mode) & 0o111, 0o111);
-
- const darwinManifest = yield* decodeManifest(
- yield* fs.readFileString(
- path.join(fixture.outputDir, "@t3code/t3-darwin-arm64/package.json"),
- ),
- );
- assert.deepStrictEqual(darwinManifest.os, ["darwin"]);
- assert.deepStrictEqual(darwinManifest.cpu, ["arm64"]);
-
- const launcherDir = path.join(fixture.outputDir, "t3");
- const launcherManifest = yield* decodeManifest(
- yield* fs.readFileString(path.join(launcherDir, "package.json")),
- );
- assert.equal(launcherManifest.name, "t3");
- assert.equal(launcherManifest.version, VERSION);
- assert.deepStrictEqual(launcherManifest.bin, { t3: "./bin/t3.js" });
- assert.deepStrictEqual(launcherManifest.files, ["bin", "dist"]);
- assert.deepStrictEqual(launcherManifest.optionalDependencies, {
- "@t3code/t3-darwin-arm64": VERSION,
- "@t3code/t3-linux-x64": VERSION,
- });
- assert.isUndefined(launcherManifest.engines);
- assert.isTrue(yield* fs.exists(path.join(launcherDir, "bin/t3.js")));
-
- const outputEntries = yield* fs.readDirectory(fixture.outputDir);
- assert.deepStrictEqual(outputEntries.sort(), ["@t3code", "t3", "t3.tgz"]);
-
- const listing = yield* run(
- "tar",
- ["-tzvf", path.join(fixture.outputDir, "@t3code/t3-linux-x64.tgz")],
- { cwd: fixture.outputDir },
- );
- assert.equal(listing.exitCode, 0, listing.stderr);
- const lines = listing.stdout.split("\n");
- assert.isTrue(lines.some((line) => line.endsWith(" package/node_modules/node-pty/")));
- assert.isTrue(lines.some((line) => line.endsWith(" package/package.json")));
- assert.isTrue(
- lines.some((line) => /^-rwxr-xr-x .* package\/t3$/.test(line)),
- listing.stdout,
- );
-
- const hostPlatform = yield* HostProcess.Platform;
- const hostArch = yield* HostProcess.Architecture;
- const env = { ...process.env, NODE_PATH: fixture.outputDir } as Record<string, string>;
- if (KEYS.some((key) => key === `${hostPlatform}-${hostArch}`)) {
- const passthrough = yield* run(process.execPath, ["bin/t3.js", "serve", "--port", "1234"], {
- cwd: launcherDir,
- env,
- });
- assert.equal(
- passthrough.stdout.trim(),
- `stub ${hostPlatform}-${hostArch} serve --port 1234`,
- );
- assert.equal(passthrough.exitCode, 7);
-
- const installedLauncher = path.join(fixture.root, "installed-launcher");
- yield* fs.makeDirectory(installedLauncher);
- const unpack = yield* run(
- "tar",
- ["-xf", path.join(fixture.outputDir, "t3.tgz"), "-C", installedLauncher],
- {
- cwd: fixture.root,
- },
- );
- assert.equal(unpack.exitCode, 0, unpack.stderr);
- const legacy = yield* run(
- process.execPath,
- [
- "dist/bin.mjs",
- "__service-preflight",
- "--database-path",
- "a database.sqlite",
- "--launcher-protocol",
- "2",
- ],
- { cwd: path.join(installedLauncher, "package"), env },
- );
- assert.equal(
- legacy.stdout.trim(),
- `stub ${hostPlatform}-${hostArch} __service-preflight --database-path a database.sqlite --launcher-protocol 2`,
- );
- assert.equal(legacy.exitCode, 7);
- }
-
- const unsupported = yield* run(process.execPath, ["bin/t3.js", "--version"], {
- cwd: launcherDir,
- env: { ...env, NODE_PATH: path.join(fixture.root, "nowhere") },
- });
- assert.equal(unsupported.exitCode, 1);
- assert.include(unsupported.stderr, "linux-x64");
- assert.include(unsupported.stderr, "win32-arm64");
- assert.include(unsupported.stderr, "https://github.com/pingdotgg/t3code/releases");
- }),
- );
-});
diff --git a/scripts/build-npm-platform-packages.ts b/scripts/build-npm-platform-packages.ts
deleted file mode 100644
index 20f74443e1c..00000000000
--- a/scripts/build-npm-platform-packages.ts
+++ /dev/null
@@ -1,451 +0,0 @@
-#!/usr/bin/env node
-/**
- * `npm publish <dir>` always drops `node_modules/` (npm-packlist ignores it
- * whatever `files` says, and bundleDependencies needs an arborist tree these
- * flattened installs are not), whereas `npm publish <tarball>` uploads the
- * bytes as given.
- */
-import { legacyCliLauncherScript } from "@t3tools/shared/legacyCliLauncher";
-import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
-import * as NodeServices from "@effect/platform-node/NodeServices";
-import * as Effect from "effect/Effect";
-import * as FileSystem from "effect/FileSystem";
-import * as Layer from "effect/Layer";
-import * as Logger from "effect/Logger";
-import * as Path from "effect/Path";
-import * as Schema from "effect/Schema";
-import { Command, Flag } from "effect/cli";
-import { ChildProcess, ChildProcessSpawner } from "effect/process";
-
-import {
- CLI_ARCHIVE_PLATFORM_KEYS,
- cliArchiveFileName,
- type CliArchivePlatformKey,
-} from "@t3tools/shared/cliRelease";
-import * as HostProcess from "@t3tools/shared/HostProcess";
-import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
-import { isCommandAvailable } from "@t3tools/shared/shell";
-import serverPackageJson from "../apps/server/package.json" with { type: "json" };
-
-import { windowsSystemTar } from "./build-cli-archive.ts";
-
-export const NPM_PLATFORM_PACKAGE_SCOPE = "@t3code";
-export const NPM_LAUNCHER_PACKAGE_NAME = "t3";
-
-const encodePackageJson = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown));
-
-export class NpmPackagesCommandFailedError extends Schema.TaggedError<NpmPackagesCommandFailedError>()(
- "NpmPackagesCommandFailedError",
- { command: Schema.String, exitCode: Schema.Int },
-) {
- override get message(): string {
- return `${this.command} exited with code ${this.exitCode}.`;
- }
-}
-
-export class NpmPackagesToolMissingError extends Schema.TaggedError<NpmPackagesToolMissingError>()(
- "NpmPackagesToolMissingError",
- { tool: Schema.String, purpose: Schema.String },
-) {
- override get message(): string {
- return `\`${this.tool}\` is not on PATH; it is needed to ${this.purpose}.`;
- }
-}
-
-export class NpmPackagesArchivesMissingError extends Schema.TaggedError<NpmPackagesArchivesMissingError>()(
- "NpmPackagesArchivesMissingError",
- { archivesDir: Schema.String, missing: Schema.Array(Schema.String) },
-) {
- override get message(): string {
- return `${this.archivesDir} lacks archives for ${this.missing.join(", ")}. A launcher published without them would silently skip those platforms; pass --allow-missing for a deliberately partial build.`;
- }
-}
-
-export class NpmPackagesArchiveLayoutError extends Schema.TaggedError<NpmPackagesArchiveLayoutError>()(
- "NpmPackagesArchiveLayoutError",
- { archive: Schema.String, detail: Schema.String },
-) {
- override get message(): string {
- return `${this.archive}: ${this.detail}`;
- }
-}
-
-export function npmPlatformPackageName(platformKey: CliArchivePlatformKey): string {
- return `${NPM_PLATFORM_PACKAGE_SCOPE}/t3-${platformKey}`;
-}
-
-/**
- * The archive's runtime `node_modules` (native addons and their loaders) ships
- * inside the tarball, and npm only keeps a nested tree it can account for:
- * anything not declared is extraneous and pruned on the next `npm install` in
- * that project, which then breaks the executable.
- */
-export function npmPlatformPackageManifest(
- platformKey: CliArchivePlatformKey,
- version: string,
- bundled: Readonly<Record<string, string>>,
-) {
- const [os, cpu] = platformKey.split("-") as [string, string];
- const bundleDependencies = Object.keys(bundled).sort();
- return {
- name: npmPlatformPackageName(platformKey),
- version,
- description: `T3 Code CLI executable for ${platformKey}`,
- license: serverPackageJson.license,
- repository: serverPackageJson.repository,
- os: [os],
- cpu: [cpu],
- files: ["t3", "t3.exe", "client", "resource-monitor", "node_modules"],
- preferUnplugged: true,
- dependencies: Object.fromEntries(bundleDependencies.map((name) => [name, bundled[name]])),
- bundleDependencies,
- };
-}
-
-const PackageVersion = Schema.Struct({ version: Schema.String });
-const decodePackageVersion = Schema.decodeUnknownEffect(Schema.fromJsonString(PackageVersion));
-
-const readBundledPackages = Effect.fn("readBundledPackages")(function* (nodeModulesDir: string) {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const bundled: Record<string, string> = {};
- const packageDirs: Array<{ readonly name: string; readonly dir: string }> = [];
- for (const entry of yield* fs.readDirectory(nodeModulesDir)) {
- if (entry.startsWith(".")) continue;
- const dir = path.join(nodeModulesDir, entry);
- if (entry.startsWith("@")) {
- for (const scoped of yield* fs.readDirectory(dir)) {
- packageDirs.push({ name: `${entry}/${scoped}`, dir: path.join(dir, scoped) });
- }
- } else {
- packageDirs.push({ name: entry, dir });
- }
- }
- for (const { name, dir } of packageDirs) {
- const manifest = yield* fs.readFileString(path.join(dir, "package.json"));
- bundled[name] = (yield* decodePackageVersion(manifest)).version;
- }
- return bundled;
-});
-
-/**
- * Without one at the package root, npm shows the first README it finds in the
- * tarball, which is a bundled dependency's (ffi-rs).
- */
-export function npmPlatformPackageReadme(platformKey: CliArchivePlatformKey): string {
- return [
- `# ${npmPlatformPackageName(platformKey)}`,
- "",
- `The T3 Code CLI executable for ${platformKey}. Do not install this package directly:`,
- `it is an optional dependency of \`${NPM_LAUNCHER_PACKAGE_NAME}\`, which picks the package for the`,
- "current platform and runs the executable inside it.",
- "",
- "```sh",
- `npx ${NPM_LAUNCHER_PACKAGE_NAME}@latest`,
- "```",
- "",
- "Source and documentation: https://github.com/pingdotgg/t3code",
- "",
- ].join("\n");
-}
-
-export function npmLauncherPackageManifest(
- version: string,
- platformKeys: ReadonlyArray<CliArchivePlatformKey>,
-) {
- return {
- name: NPM_LAUNCHER_PACKAGE_NAME,
- version,
- description: "T3 Code CLI. Installs the self-contained executable for this platform.",
- license: serverPackageJson.license,
- repository: serverPackageJson.repository,
- bin: { t3: "./bin/t3.js" },
- files: ["bin", "dist"],
- optionalDependencies: Object.fromEntries(
- platformKeys.map((key) => [npmPlatformPackageName(key), version]),
- ),
- };
-}
-
-export const NPM_LAUNCHER_SCRIPT = `#!/usr/bin/env node
-"use strict";
-const { spawnSync } = require("node:child_process");
-const { constants } = require("node:os");
-const { dirname, join } = require("node:path");
-
-const SUPPORTED = [${CLI_ARCHIVE_PLATFORM_KEYS.map((key) => `"${key}"`).join(", ")}];
-const key = process.platform + "-" + process.arch;
-
-let packageDir;
-try {
- packageDir = dirname(require.resolve("${NPM_PLATFORM_PACKAGE_SCOPE}/t3-" + key + "/package.json"));
-} catch {
- process.stderr.write(
- [
- "t3: no T3 Code CLI build is available for this platform (" + key + ").",
- "Supported platforms: " + SUPPORTED.join(", ") + ".",
- "If yours is listed, reinstall t3 so npm fetches its optional dependency.",
- "The desktop app and release archives are at https://github.com/pingdotgg/t3code/releases",
- "",
- ].join("\\n"),
- );
- process.exit(1);
-}
-
-const executable = join(packageDir, process.platform === "win32" ? "t3.exe" : "t3");
-const result = spawnSync(executable, process.argv.slice(2), { stdio: "inherit" });
-if (result.error) {
- process.stderr.write("t3: failed to start " + executable + ": " + result.error.message + "\\n");
- process.exit(1);
-}
-// A child killed by a signal has no status; report it the way a shell would.
-process.exit(result.status ?? 128 + (constants.signals[result.signal] || 1));
-`;
-
-const runCommand = Effect.fn("runCommand")(function* (
- command: ChildProcess.StandardCommand,
- label: string,
-) {
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const child = yield* spawner.spawn(
- ChildProcess.make(command.command, command.args, {
- ...command.options,
- stdout: "inherit",
- stderr: "inherit",
- }),
- );
- const exitCode = Number(yield* child.exitCode);
- if (exitCode !== 0) {
- return yield* new NpmPackagesCommandFailedError({ command: label, exitCode });
- }
-});
-
-/**
- * `.tar.gz` goes through tar everywhere; `.zip` through the bsdtar Windows
- * ships or, elsewhere, `unzip`, since GNU tar cannot read zip.
- */
-const extractArchive = Effect.fn("extractArchive")(function* (archive: string, into: string) {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const platform = yield* HostProcess.Platform;
- if (!archive.endsWith(".zip")) {
- yield* runCommand(ChildProcess.make("tar", ["-xf", archive, "-C", into]), "tar -xf");
- } else if (platform === "win32") {
- yield* runCommand(
- ChildProcess.make(windowsSystemTar(), ["-xf", archive, "-C", into]),
- "tar.exe -xf (zip)",
- );
- } else {
- if (!(yield* isCommandAvailable("unzip"))) {
- return yield* new NpmPackagesToolMissingError({
- tool: "unzip",
- purpose: `extract ${path.basename(archive)} (GNU tar cannot read zip)`,
- });
- }
- yield* runCommand(ChildProcess.make("unzip", ["-q", archive, "-d", into]), "unzip");
- }
- const entries = yield* fs.readDirectory(into);
- const [root] = entries;
- if (root === undefined || entries.length !== 1) {
- return yield* new NpmPackagesArchiveLayoutError({
- archive: path.basename(archive),
- detail: `expected exactly one top-level directory, found ${String(entries.length)} entries`,
- });
- }
- return path.join(into, root);
-});
-
-/** Tar to build npm tarballs with; see build-cli-archive.ts for why Windows names bsdtar by path. */
-const hostTar = Effect.map(HostProcess.Platform, (platform) =>
- platform === "win32" ? windowsSystemTar() : "tar",
-);
-
-const packAndPlace = Effect.fn("packAndPlace")(function* (input: {
- readonly stageDir: string;
- readonly packageDir: string;
- readonly tarball: string;
-}) {
- const fs = yield* FileSystem.FileSystem;
- yield* fs.remove(input.tarball, { force: true });
- yield* runCommand(
- ChildProcess.make(yield* hostTar, ["-czf", input.tarball, "-C", input.stageDir, "package"]),
- `tar (${input.tarball})`,
- );
- yield* fs.remove(input.packageDir, { recursive: true, force: true });
- yield* fs.rename(`${input.stageDir}/package`, input.packageDir);
-});
-
-export interface NpmPackageOutput {
- readonly name: string;
- readonly packageDir: string;
- readonly tarball: string;
-}
-
-const stagePlatformPackage = Effect.fn("stagePlatformPackage")(function* (input: {
- readonly key: CliArchivePlatformKey;
- readonly archive: string;
- readonly outputDir: string;
- readonly version: string;
-}) {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- yield* Effect.log(`[npm-packages] Extracting ${path.basename(input.archive)}...`);
- const scratch = yield* fs.makeTempDirectoryScoped({
- directory: input.outputDir,
- prefix: ".extract-",
- });
- const extractDir = path.join(scratch, "extract");
- yield* fs.makeDirectory(extractDir);
- const contentDir = yield* extractArchive(input.archive, extractDir);
- const executableName = input.key.startsWith("win32") ? "t3.exe" : "t3";
- const executable = path.join(contentDir, executableName);
- if (!(yield* fs.exists(executable))) {
- return yield* new NpmPackagesArchiveLayoutError({
- archive: path.basename(input.archive),
- detail: `missing ${executableName} at the archive root`,
- });
- }
- // The tarball carries the on-disk mode, so the bit must be set before packing.
- if (executableName === "t3") {
- yield* fs.chmod(executable, 0o755);
- }
- const bundled = yield* readBundledPackages(path.join(contentDir, "node_modules"));
- yield* fs.writeFileString(
- path.join(contentDir, "package.json"),
- `${yield* encodePackageJson(npmPlatformPackageManifest(input.key, input.version, bundled))}\n`,
- );
- yield* fs.writeFileString(
- path.join(contentDir, "README.md"),
- npmPlatformPackageReadme(input.key),
- );
- // npm tarballs root everything under `package/`.
- yield* fs.rename(contentDir, path.join(scratch, "package"));
- const name = npmPlatformPackageName(input.key);
- const output: NpmPackageOutput = {
- name,
- packageDir: path.join(input.outputDir, name),
- tarball: path.join(input.outputDir, `${name}.tgz`),
- };
- yield* packAndPlace({ stageDir: scratch, ...output });
- return output;
-}, Effect.scoped);
-
-const stageLauncherPackage = Effect.fn("stageLauncherPackage")(function* (input: {
- readonly outputDir: string;
- readonly version: string;
- readonly platformKeys: ReadonlyArray<CliArchivePlatformKey>;
-}) {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const scratch = yield* fs.makeTempDirectoryScoped({
- directory: input.outputDir,
- prefix: ".launcher-",
- });
- const stageDir = path.join(scratch, "package");
- yield* fs.makeDirectory(path.join(stageDir, "bin"), { recursive: true });
- yield* fs.writeFileString(
- path.join(stageDir, "package.json"),
- `${yield* encodePackageJson(npmLauncherPackageManifest(input.version, input.platformKeys))}\n`,
- );
- const launcherScript = path.join(stageDir, "bin/t3.js");
- yield* fs.writeFileString(launcherScript, NPM_LAUNCHER_SCRIPT);
- yield* fs.chmod(launcherScript, 0o755);
- // Older service updaters and launchers run this exact path with Node.
- // Keep it in the package so they can preflight and start the new executable.
- yield* fs.makeDirectory(path.join(stageDir, "dist"));
- yield* fs.writeFileString(path.join(stageDir, "dist/bin.mjs"), legacyCliLauncherScript());
- const readme = yield* path.fromFileUrl(new URL("../apps/server/README.md", import.meta.url));
- if (yield* fs.exists(readme)) {
- yield* fs.copyFile(readme, path.join(stageDir, "README.md"));
- }
- const output: NpmPackageOutput = {
- name: NPM_LAUNCHER_PACKAGE_NAME,
- packageDir: path.join(input.outputDir, NPM_LAUNCHER_PACKAGE_NAME),
- tarball: path.join(input.outputDir, `${NPM_LAUNCHER_PACKAGE_NAME}.tgz`),
- };
- yield* packAndPlace({ stageDir: scratch, ...output });
- return output;
-}, Effect.scoped);
-
-export const buildNpmPlatformPackages = Effect.fn("buildNpmPlatformPackages")(function* (input: {
- readonly archivesDir: string;
- readonly version: string;
- readonly outputDir: string;
- readonly allowMissing: boolean;
-}) {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
-
- const present = yield* fs.readDirectory(input.archivesDir);
- const archives = CLI_ARCHIVE_PLATFORM_KEYS.flatMap((key) => {
- const fileName = cliArchiveFileName(input.version, key);
- return present.includes(fileName)
- ? [{ key, archive: path.join(input.archivesDir, fileName) }]
- : [];
- });
- const missing = CLI_ARCHIVE_PLATFORM_KEYS.filter(
- (key) => !archives.some((entry) => entry.key === key),
- );
- if (missing.length > 0 && (!input.allowMissing || archives.length === 0)) {
- return yield* new NpmPackagesArchivesMissingError({ archivesDir: input.archivesDir, missing });
- }
-
- yield* fs.makeDirectory(path.join(input.outputDir, NPM_PLATFORM_PACKAGE_SCOPE), {
- recursive: true,
- });
- const platformOutputs = yield* Effect.forEach(
- archives,
- ({ key, archive }) =>
- stagePlatformPackage({ key, archive, outputDir: input.outputDir, version: input.version }),
- { concurrency: "unbounded" },
- );
- const outputs = [
- ...platformOutputs,
- yield* stageLauncherPackage({
- outputDir: input.outputDir,
- version: input.version,
- platformKeys: archives.map((entry) => entry.key),
- }),
- ];
-
- for (const output of outputs) {
- yield* Effect.log(`[npm-packages] Wrote ${output.packageDir} and ${output.tarball}`);
- }
- if (missing.length > 0) {
- yield* Effect.logWarning(
- `[npm-packages] Launcher omits ${missing.join(", ")} (--allow-missing).`,
- );
- }
- return outputs;
-});
-
-const command = Command.make(
- "build-npm-platform-packages",
- {
- archivesDir: Flag.String("archives-dir").pipe(
- Flag.withDescription("Directory holding the release's t3-<version>-<platform> archives."),
- ),
- version: Flag.String("version").pipe(
- Flag.withDescription(
- "Exact release version; selects the archives and versions the packages.",
- ),
- ),
- outputDir: Flag.String("output-dir").pipe(Flag.withDefault("npm-packages")),
- allowMissing: Flag.Boolean("allow-missing").pipe(
- Flag.withDefault(false),
- Flag.withDescription("Build a launcher that lists only the platforms present."),
- ),
- },
- buildNpmPlatformPackages,
-).pipe(
- Command.withDescription(
- "Build the t3 launcher and @t3code/t3-<platform> npm packages from CLI release archives.",
- ),
-);
-
-if (import.meta.main) {
- Command.run(command, { version: "0.0.0" }).pipe(
- Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
- NodeRuntime.runMain,
- );
-}
diff --git a/scripts/npm-launcher/bin.mjs b/scripts/npm-launcher/bin.mjs
new file mode 100644
index 00000000000..d328f69567b
--- /dev/null
+++ b/scripts/npm-launcher/bin.mjs
@@ -0,0 +1,2 @@
+// Background services installed before 0.0.41 start the npm package from this path.
+import "../bin/t3.mjs";
diff --git a/scripts/npm-launcher/t3.mjs b/scripts/npm-launcher/t3.mjs
new file mode 100644
index 00000000000..cc866746669
--- /dev/null
+++ b/scripts/npm-launcher/t3.mjs
@@ -0,0 +1,176 @@
+#!/usr/bin/env node
+// The `t3` npm package. Downloads this version's CLI archive from the GitHub
+// Release into <T3 home>/runtime/versions/<version> (the folder the install
+// scripts and `t3 update` use), verifies it against the release's SHA256SUMS,
+// then runs it. `dist/bin.mjs` re-enters here for background services
+// installed before 0.0.41, which start the npm package with Node and talk to
+// it over an IPC channel.
+import { spawn, spawnSync } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const { version } = JSON.parse(
+ fs.readFileSync(path.join(import.meta.dirname, "../package.json"), "utf8"),
+);
+
+const SUPPORTED = ["darwin-arm64", "linux-arm64", "linux-x64", "win32-arm64", "win32-x64"];
+
+function t3Home() {
+ const raw = (process.env.T3CODE_HOME || "").trim();
+ if (raw === "") return path.join(os.homedir(), ".t3");
+ if (raw === "~") return os.homedir();
+ if (raw.startsWith("~/") || raw.startsWith("~\\")) return path.join(os.homedir(), raw.slice(2));
+ return path.resolve(raw);
+}
+
+async function get(url) {
+ const response = await fetch(url);
+ if (response.status === 404) {
+ throw new Error(
+ `${url} does not exist yet. If ${version} was just released, try again in a few minutes.`,
+ );
+ }
+ if (!response.ok) throw new Error(`GET ${url} returned HTTP ${response.status}`);
+ return response;
+}
+
+/** Downloads `url` to `file` and returns its sha256, showing progress on a terminal. */
+async function download(url, file) {
+ const response = await get(url);
+ const total = Number(response.headers.get("content-length")) || 0;
+ const hash = crypto.createHash("sha256");
+ const out = fs.openSync(file, "w");
+ const tty = process.stderr.isTTY;
+ let received = 0;
+ let shown = -1;
+ try {
+ for await (const chunk of response.body) {
+ hash.update(chunk);
+ fs.writeSync(out, chunk);
+ received += chunk.byteLength;
+ // Redraw once per percent (or per MB without a length), not per chunk.
+ const step = total ? Math.floor((received * 100) / total) : Math.floor(received / 1048576);
+ if (tty && step !== shown) {
+ shown = step;
+ const percent = total ? ` ${step}%` : "";
+ process.stderr.write(
+ `\r\x1b[2Kt3: downloading T3 Code ${version}${percent} (${(received / 1048576).toFixed(1)} MB)`,
+ );
+ }
+ }
+ } finally {
+ fs.closeSync(out);
+ if (tty) process.stderr.write("\r\x1b[2K");
+ }
+ return hash.digest("hex");
+}
+
+async function install(dir, key) {
+ const archive = `t3-${version}-${key}.${process.platform === "win32" ? "zip" : "tar.gz"}`;
+ const base = (
+ process.env.T3CODE_RELEASE_BASE_URL || "https://github.com/pingdotgg/t3code/releases/download"
+ ).replace(/\/+$/, "");
+ const sums = await (await get(`${base}/v${version}/SHA256SUMS`)).text();
+ const expected = /^([0-9a-f]{64})\s+\*?(.+)$/im;
+ const line = sums
+ .split(/\r?\n/)
+ .map((l) => expected.exec(l.trim()))
+ .find((m) => m && m[2] === archive);
+ if (!line) throw new Error(`${archive} is not listed in the release's SHA256SUMS`);
+
+ // Extract beside the final folder and rename it into place, so an
+ // interrupted download never leaves a half-installed version behind.
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
+ const staging = fs.mkdtempSync(`${dir}.staging-`);
+ try {
+ const file = path.join(staging, archive);
+ if ((await download(`${base}/v${version}/${archive}`, file)) !== line[1].toLowerCase()) {
+ throw new Error(`checksum mismatch for ${archive}`);
+ }
+ // Windows' own tar.exe reads zip; a Git-for-Windows tar on PATH cannot.
+ const tar =
+ process.platform === "win32" ? `${process.env.SystemRoot}\\System32\\tar.exe` : "tar";
+ const extract = spawnSync(tar, ["-xf", file, "-C", staging, "--strip-components=1"], {
+ stdio: "inherit",
+ });
+ if (extract.status !== 0) throw new Error(`could not extract ${archive}`);
+ fs.rmSync(file);
+ fs.writeFileSync(path.join(staging, ".install-complete"), `${version}\n`);
+ publish(staging, dir);
+ } finally {
+ fs.rmSync(staging, { recursive: true, force: true });
+ }
+}
+
+const isComplete = (dir) => {
+ try {
+ return fs.readFileSync(path.join(dir, ".install-complete"), "utf8").trim() === version;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Moves a finished staging folder to `dir`. Rename never replaces an existing
+ * folder, so a complete install another launcher (or `t3 update`) published
+ * first is kept, never deleted from under a running process. Only a folder
+ * without the completion marker, left by an interrupted older installer, is
+ * cleared before trying again.
+ */
+function publish(staging, dir) {
+ try {
+ fs.renameSync(staging, dir);
+ } catch (error) {
+ if (isComplete(dir)) return;
+ if (!fs.existsSync(dir)) throw error;
+ fs.rmSync(dir, { recursive: true, force: true });
+ fs.renameSync(staging, dir);
+ }
+}
+
+async function main() {
+ const key = `${process.platform}-${process.arch}`;
+ if (!SUPPORTED.includes(key)) {
+ throw new Error(
+ `no T3 Code CLI build is available for ${key} (supported: ${SUPPORTED.join(", ")}).\n` +
+ "The desktop app is at https://github.com/pingdotgg/t3code/releases",
+ );
+ }
+ const dir = path.join(t3Home(), "runtime", "versions", version);
+ if (!isComplete(dir)) await install(dir, key);
+
+ // A service launcher talks to its server over IPC; pass that channel and
+ // signals through. In a terminal, Ctrl-C already reaches the child directly,
+ // so forwarding SIGINT too would deliver it twice.
+ const ipc = process.send !== undefined;
+ const child = spawn(
+ path.join(dir, process.platform === "win32" ? "t3.exe" : "t3"),
+ process.argv.slice(2),
+ {
+ stdio: ipc ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
+ // The executable lives in the T3 home, so this is how it knows npm launched it.
+ env: { ...process.env, T3CODE_NPM_LAUNCHER_PATH: import.meta.filename },
+ },
+ );
+ if (ipc) {
+ process.on("message", (message) => child.connected && child.send(message));
+ child.on("message", (message) => process.connected && process.send(message));
+ process.on("disconnect", () => child.connected && child.disconnect());
+ }
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
+ process.on(signal, () => (ipc || signal !== "SIGINT") && child.kill(signal));
+ }
+ child.on("error", (error) => fail(error));
+ child.on("exit", (code, signal) =>
+ process.exit(code ?? 128 + (os.constants.signals[signal] || 1)),
+ );
+}
+
+function fail(error) {
+ process.stderr.write(`t3: ${error.message}\n`);
+ process.exit(1);
+}
+
+await main().catch(fail);
diff --git a/vite.config.ts b/vite.config.ts
index 928540a0e3c..293b6873dcd 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -214,6 +214,14 @@ export default defineConfig({
files: ["packages/shared/src/HostProcess.ts"],
rules: { "t3code/no-global-process-runtime": "off" },
},
+ {
+ // The `t3` npm launcher is published as plain, dependency-free Node.
+ files: ["scripts/npm-launcher/**"],
+ rules: {
+ "t3code/no-global-process-runtime": "off",
+ "t3code/namespace-node-imports": "off",
+ },
+ },
{
files: ["apps/server/src/mcp/McpHttpServer.ts"],
rules: { "t3code/no-raw-mcp-registration": "off" },