@devries-cameron20 / t3code-1 / commits / 6b450c75b5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

bye npm (#20148)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 15, 2026 at 23:18 UTC 6b450c75b5db816c864d6b5dfbf703c62b1c3063
19 files changed +685 -1066
.github/workflows/release.yml
+48 -69
@@ -689,11 +689,8 @@ jobs:
689 resource_key: win32-arm64
690 cli_archive: true
691
692 - # npm gets the same bytes as the GitHub Release: the launcher plus one
693 - # package per CLI archive. Preview publishes too, under the `preview`
694 - # dist-tag, which nothing resolves unless asked for by name.
695 - publish_cli:
696 - name: Publish CLI to npm
692 + release:
693 + name: Publish GitHub Release
694 needs:
695 [
696 preflight,
@@ -702,74 +699,13 @@ jobs:
699 test,
700 test_server,
701 desktop_mac_arm64,
705 - desktop_linux_x64,
706 - desktop_linux_arm64,
707 - desktop_win_x64,
708 - desktop_win_arm64,
709 - ]
710 - 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' }}
711 - runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
712 - timeout-minutes: 15
713 - permissions:
714 - contents: read
715 - id-token: write
716 - steps:
717 - - name: Checkout
718 - uses: actions/checkout@v6
719 - with:
720 - ref: ${{ needs.preflight.outputs.ref }}
721 - sparse-checkout: |
722 - /*
723 - !/.repos/
724 - sparse-checkout-cone-mode: false
725 -
726 - - name: Setup Vite+
727 - uses: voidzero-dev/setup-vp@v1
728 - with:
729 - node-version-file: package.json
730 - cache: true
731 - run-install: |
732 - args:
733 - - --filter=t3...
734 - - --filter=@t3tools/scripts...
735 -
736 - - name: Download all CLI archives
737 - uses: actions/download-artifact@v8
738 - with:
739 - pattern: cli-*
740 - merge-multiple: true
741 - path: release-cli
742 -
743 - - name: Build npm packages from CLI archives
744 - run: node scripts/build-npm-platform-packages.ts --archives-dir release-cli --version "${{ needs.preflight.outputs.version }}" --output-dir npm-packages
745 -
746 - # A dry run of every package first: an auth or scope error here (the
747 - # @t3code org missing, a package without a trusted publisher) fails
748 - # before anything is live, instead of after some platforms already are.
749 - - name: Check npm publish access (dry run)
750 - run: |
751 - if ! node apps/server/scripts/cli.ts publish --packages-dir npm-packages --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --provenance --dry-run --verbose; then
752 - 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
753 - exit 1
754 - fi
755 -
756 - - name: Publish CLI packages
757 - run: node apps/server/scripts/cli.ts publish --packages-dir npm-packages --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --provenance --verbose
758 -
759 - release:
760 - name: Publish GitHub Release
761 - needs:
762 - [
763 - preflight,
764 - desktop_mac_arm64,
702 desktop_mac_x64,
703 desktop_linux_x64,
704 desktop_linux_arm64,
705 desktop_win_x64,
706 desktop_win_arm64,
770 - publish_cli,
707 ]
772 - 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' }}
708 + 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' }}
709 runs-on: blacksmith-8vcpu-ubuntu-2404
710 timeout-minutes: 30
711 permissions:
@@ -957,6 +893,49 @@ jobs:
893 fail_on_unmatched_files: true
894 token: ${{ github.token }}
895
896 + # The `t3` npm package is a launcher that downloads this version's CLI
897 + # archive from the GitHub Release, so it publishes only once that release
898 + # exists. Preview publishes too, under the `preview` dist-tag, which
899 + # nothing resolves unless asked for by name.
900 + publish_cli:
901 + name: Publish CLI to npm
902 + needs: [preflight, release]
903 + if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
904 + runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
905 + timeout-minutes: 15
906 + permissions:
907 + contents: read
908 + id-token: write
909 + steps:
910 + - name: Checkout
911 + uses: actions/checkout@v6
912 + with:
913 + ref: ${{ needs.preflight.outputs.ref }}
914 + sparse-checkout: |
915 + /*
916 + !/.repos/
917 + sparse-checkout-cone-mode: false
918 +
919 + - name: Setup Vite+
920 + uses: voidzero-dev/setup-vp@v1
921 + with:
922 + node-version-file: package.json
923 + cache: true
924 + run-install: |
925 + args:
926 + - --filter=t3...
927 + - --filter=@t3tools/scripts...
928 +
929 + - name: Build the npm launcher
930 + run: node scripts/build-npm-launcher.ts --version "${{ needs.preflight.outputs.version }}" --output-dir npm-packages
931 +
932 + - name: Publish the npm launcher
933 + run: |
934 + if ! node apps/server/scripts/cli.ts publish --packages-dir npm-packages --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --provenance --verbose; then
935 + 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
936 + exit 1
937 + fi
938 +
939 publish_aur:
940 name: Publish AUR package
941 needs: [preflight, release]
@@ -1074,8 +1053,8 @@ jobs:
1053
1054 deploy_web:
1055 name: Deploy hosted web app
1077 - needs: [preflight, build_web, release]
1078 - if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build_web.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel != 'preview' }}
1056 + needs: [preflight, build_web, release, publish_cli]
1057 + 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' }}
1058 runs-on: blacksmith-2vcpu-ubuntu-2404
1059 timeout-minutes: 10
1060 env:
apps/server/scripts/cli.ts
+15 -39
@@ -19,7 +19,6 @@ import {
19 ServerCliDevelopmentIconTargetMissingError,
20 ServerCliExecutableImportError,
21 } from "./cliErrors.ts";
22 -import { publishPlatformsThenLauncher } from "./publishOrder.ts";
22
23 const RepoRoot = Effect.service(Path.Path).pipe(
24 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
@@ -155,17 +154,15 @@ const buildExeCmd = Command.make(
154 );
155
156 /**
158 - * Publishes the tarballs scripts/build-npm-platform-packages.ts produced:
159 - * every `@t3code/t3-<platform>.tgz` first, `t3.tgz` (the launcher) last, so
160 - * the launcher is never installable before the executables it depends on.
161 - * Tarballs rather than directories because `npm publish <dir>` strips the
162 - * `node_modules/` the executable loads its native addons from.
157 + * Publishes the `t3.tgz` launcher scripts/build-npm-launcher.ts produced. The
158 + * launcher downloads its executable from the GitHub Release, so the release
159 + * workflow runs this only after that release is published.
160 */
161 const publishCmd = Command.make(
162 "publish",
163 {
164 packagesDir: Flag.String("packages-dir").pipe(
168 - Flag.withDescription("Output dir of scripts/build-npm-platform-packages.ts."),
165 + Flag.withDescription("Output dir of scripts/build-npm-launcher.ts."),
166 ),
167 tag: Flag.String("tag").pipe(Flag.withDefault("latest")),
168 access: Flag.String("access").pipe(Flag.withDefault("public")),
@@ -178,19 +175,7 @@ const publishCmd = Command.make(
175 const path = yield* Path.Path;
176 const fs = yield* FileSystem.FileSystem;
177 const packagesDir = path.resolve(config.packagesDir);
181 - const scopeDir = path.join(packagesDir, "@t3code");
178 const launcherTarball = path.join(packagesDir, "t3.tgz");
183 - const platformTarballs = (yield* fs
184 - .readDirectory(scopeDir)
185 - .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => [])))
186 - .filter((entry) => entry.startsWith("t3-") && entry.endsWith(".tgz"))
187 - .sort()
188 - .map((entry) => path.join(scopeDir, entry));
189 - if (platformTarballs.length === 0) {
190 - return yield* new ServerCliBuildAssetMissingError({
191 - assetPath: path.join(scopeDir, "t3-<platform>.tgz"),
192 - });
193 - }
179 if (!(yield* fs.exists(launcherTarball))) {
180 return yield* new ServerCliBuildAssetMissingError({ assetPath: launcherTarball });
181 }
@@ -198,27 +183,18 @@ const publishCmd = Command.make(
183 const args = ["publish", "--access", config.access, "--tag", config.tag];
184 if (config.provenance) args.push("--provenance");
185 if (config.dryRun) args.push("--dry-run");
201 -
202 - const publish = Effect.fn("publish")(function* (tarball: string) {
203 - const spawnCommand = yield* resolveSpawnCommand("npm", [...args, tarball]);
204 - yield* Effect.log(`[cli] npm ${args.join(" ")} ${path.basename(tarball)}`);
205 - yield* runCommand(
206 - ChildProcess.make(spawnCommand.command, spawnCommand.args, {
207 - cwd: packagesDir,
208 - stdout: config.verbose ? "inherit" : "ignore",
209 - stderr: "inherit",
210 - shell: spawnCommand.shell,
211 - }),
212 - );
213 - });
214 -
215 - yield* publishPlatformsThenLauncher({ platformTarballs, launcherTarball, publish });
186 + const spawnCommand = yield* resolveSpawnCommand("npm", [...args, launcherTarball]);
187 + yield* Effect.log(`[cli] npm ${args.join(" ")} t3.tgz`);
188 + yield* runCommand(
189 + ChildProcess.make(spawnCommand.command, spawnCommand.args, {
190 + cwd: packagesDir,
191 + stdout: config.verbose ? "inherit" : "ignore",
192 + stderr: "inherit",
193 + shell: spawnCommand.shell,
194 + }),
195 + );
196 }),
217 -).pipe(
218 - Command.withDescription(
219 - "Publish the @t3code/t3-<platform> tarballs and then the t3 launcher to npm.",
220 - ),
221 -);
197 +).pipe(Command.withDescription("Publish the t3 launcher to npm."));
198
199 const cli = Command.make("cli").pipe(
200 Command.withDescription("T3 server build & publish CLI."),
apps/server/scripts/publishOrder.test.ts deleted
-55
@@ -1,55 +0,0 @@
1 -import { assert, it } from "@effect/vitest";
2 -import * as Effect from "effect/Effect";
3 -import * as Exit from "effect/Exit";
4 -import * as Latch from "effect/Latch";
5 -
6 -import { publishPlatformsThenLauncher } from "./publishOrder.ts";
7 -
8 -const platformTarballs = ["a.tgz", "b.tgz", "c.tgz"];
9 -const launcherTarball = "t3.tgz";
10 -
11 -const fakePublish = Effect.fn("fakePublish")(function* (failing?: string) {
12 - const events: Array<string> = [];
13 - const allStarted = yield* Latch.make();
14 - let started = 0;
15 - const publish = (tarball: string) =>
16 - Effect.gen(function* () {
17 - events.push(`start ${tarball}`);
18 - if (tarball === launcherTarball) return;
19 - started += 1;
20 - if (started === platformTarballs.length) yield* allStarted.open;
21 - if (tarball === failing) return yield* Effect.fail(`${tarball} failed`);
22 - yield* allStarted.await;
23 - events.push(`end ${tarball}`);
24 - });
25 - return { events, publish };
26 -});
27 -
28 -it.effect("publishes the platform packages at once and the launcher last", () =>
29 - Effect.gen(function* () {
30 - const { events, publish } = yield* fakePublish();
31 -
32 - yield* publishPlatformsThenLauncher({ platformTarballs, launcherTarball, publish });
33 -
34 - assert.deepStrictEqual(events.slice(0, 3).toSorted(), [
35 - "start a.tgz",
36 - "start b.tgz",
37 - "start c.tgz",
38 - ]);
39 - assert.strictEqual(events.at(-1), `start ${launcherTarball}`);
40 - }),
41 -);
42 -
43 -it.effect("finishes the other uploads and skips the launcher when one fails", () =>
44 - Effect.gen(function* () {
45 - const { events, publish } = yield* fakePublish("b.tgz");
46 -
47 - const exit = yield* Effect.exit(
48 - publishPlatformsThenLauncher({ platformTarballs, launcherTarball, publish }),
49 - );
50 -
51 - assert.deepStrictEqual(exit, Exit.fail("b.tgz failed"));
52 - assert.includeMembers(events, ["end a.tgz", "end c.tgz"]);
53 - assert.notInclude(events, `start ${launcherTarball}`);
54 - }),
55 -);
apps/server/scripts/publishOrder.ts deleted
-26
@@ -1,26 +0,0 @@
1 -import * as Effect from "effect/Effect";
2 -import * as Result from "effect/Result";
3 -
4 -/**
5 - * Publishes every platform package at once, then the launcher, which must never
6 - * be installable before the executables it points to. When one platform fails,
7 - * the other uploads still finish rather than being interrupted: npm never
8 - * accepts the same version twice, and an interrupted upload may already be
9 - * live.
10 - */
11 -export const publishPlatformsThenLauncher = <E, R>(input: {
12 - readonly platformTarballs: ReadonlyArray<string>;
13 - readonly launcherTarball: string;
14 - readonly publish: (tarball: string) => Effect.Effect<void, E, R>;
15 -}) =>
16 - Effect.gen(function* () {
17 - const results = yield* Effect.all(input.platformTarballs.map(input.publish), {
18 - concurrency: "unbounded",
19 - mode: "result",
20 - });
21 - const failed = results.find(Result.isFailure);
22 - if (failed) {
23 - return yield* Effect.fail(failed.failure);
24 - }
25 - yield* input.publish(input.launcherTarball);
26 - });
apps/server/src/cli/invocation.test.ts
+33 -20
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Path from "effect/Path";
7
8 +import packageJson from "../../package.json" with { type: "json" };
9 import {
10 formatCliCommand,
11 resolveHostCliCommand,
@@ -226,24 +227,36 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => {
227 });
228
229 it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
229 - it.effect("recognizes runner caches for both script and executable packages", () =>
230 + it.effect("recognizes runner caches for script packages and the npm launcher", () =>
231 Effect.gen(function* () {
232 const fs = yield* FileSystem.FileSystem;
233 const path = yield* Path.Path;
234 const root = yield* fs.makeTempDirectoryScoped();
235 + const executable = path.join(root, ".t3/runtime/versions/1.0.0/t3");
236 + yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
237 + yield* fs.writeFileString(executable, "");
238 for (const [relative, kind] of [
239 ["npm/_npx/hash/node_modules/t3/dist/bin.mjs", "npx"],
236 - ["npm/_npx/hash/node_modules/@t3code/t3-linux-x64/t3", "npx"],
240 + ["npm/_npx/hash/node_modules/t3/bin/t3.mjs", "npx"],
241 ["pnpm/dlx/hash/node_modules/t3/dist/bin.mjs", "pnpm-dlx"],
242 [".bun/install/cache/t3/dist/bin.mjs", "bunx"],
243 ] as const) {
244 const entry = path.join(root, relative);
245 yield* fs.makeDirectory(path.dirname(entry), { recursive: true });
246 yield* fs.writeFileString(entry, "");
247 + yield* fs.writeFileString(
248 + path.join(path.dirname(entry), "../package.json"),
249 + `{"name":"t3","version":"${packageJson.version}","bin":{"t3":"./bin/t3.mjs"}}`,
250 + );
251 + const launchedBy = entry.endsWith("t3.mjs");
252 const installation = yield* resolveServerInstallation.pipe(
244 - Effect.provideService(HostProcess.Arguments, ["node", entry]),
245 - Effect.provideService(HostProcess.ExecutablePath, entry),
246 - Effect.provideService(HostProcess.IsExecutable, entry.endsWith("/t3")),
253 + Effect.provideService(HostProcess.Arguments, [launchedBy ? executable : "node", entry]),
254 + Effect.provideService(HostProcess.ExecutablePath, executable),
255 + Effect.provideService(HostProcess.IsExecutable, launchedBy),
256 + Effect.provideService(
257 + HostProcess.Environment,
258 + launchedBy ? { T3CODE_NPM_LAUNCHER_PATH: entry } : {},
259 + ),
260 );
261 expect(installation).toEqual({ kind });
262 }
@@ -281,37 +294,37 @@ it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
294 }),
295 );
296
284 - it.effect("proves the native executable belongs to the npm launcher", () =>
297 + it.effect("proves the downloaded executable was started by a global npm launcher", () =>
298 Effect.gen(function* () {
299 const fs = yield* FileSystem.FileSystem;
300 const path = yield* Path.Path;
301 const root = yield* fs.makeTempDirectoryScoped();
302 const prefix = path.join(root, "bunx-tools");
303 const packageRoot = path.join(prefix, "lib/node_modules/t3");
291 - const launcher = path.join(packageRoot, "bin/t3.js");
292 - const entry = path.join(packageRoot, "node_modules/@t3code/t3-linux-x64/t3");
304 + const launcher = path.join(packageRoot, "bin/t3.mjs");
305 + const executable = path.join(root, ".t3/runtime/versions/1.0.0/t3");
306 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
294 - yield* fs.makeDirectory(path.dirname(entry), { recursive: true });
307 + yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
308 yield* fs.makeDirectory(path.join(prefix, "bin"));
309 yield* fs.writeFileString(launcher, "");
297 - yield* fs.writeFileString(entry, "");
298 - yield* fs.writeFileString(
299 - path.join(packageRoot, "package.json"),
300 - '{"name":"t3","version":"0.0.45","bin":{"t3":"./bin/t3.js"},"optionalDependencies":{"@t3code/t3-linux-x64":"0.0.45"}}',
301 - );
310 + yield* fs.writeFileString(executable, "");
311 yield* fs.symlink(launcher, path.join(prefix, "bin/t3"));
312 const resolve = resolveServerInstallation.pipe(
304 - Effect.provideService(HostProcess.ExecutablePath, entry),
313 + Effect.provideService(HostProcess.ExecutablePath, executable),
314 + Effect.provideService(HostProcess.Arguments, [executable, executable]),
315 Effect.provideService(HostProcess.IsExecutable, true),
316 Effect.provideService(HostProcess.Platform, "linux"),
317 + Effect.provideService(HostProcess.Environment, { T3CODE_NPM_LAUNCHER_PATH: launcher }),
318 );
319 + // A launcher for another version is some other `t3` the server spawned
320 + // (the variable is inherited), not the install this executable runs from.
321 for (const [version, expected] of [
309 - ["0.0.44", null],
310 - ["0.0.45", { kind: "npm-global", prefix }],
311 - ]) {
322 + ["0.0.1", null],
323 + [packageJson.version, { kind: "npm-global", prefix }],
324 + ] as const) {
325 yield* fs.writeFileString(
313 - path.join(path.dirname(entry), "package.json"),
314 - `{"name":"@t3code/t3-linux-x64","version":"${version}"}`,
326 + path.join(packageRoot, "package.json"),
327 + `{"name":"t3","version":"${version}","bin":{"t3":"./bin/t3.mjs"}}`,
328 );
329 expect(yield* resolve).toEqual(expected);
330 }
apps/server/src/cli/invocation.ts
+35 -29
@@ -35,22 +35,45 @@ const InstallManifest = Schema.Struct({
35 name: Schema.String,
36 version: Schema.String,
37 bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })),
38 - optionalDependencies: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
38 });
39 const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest));
40
41 +/**
42 + * The script this CLI was started through: the `t3` npm launcher that
43 + * downloaded and ran this executable (it names itself in
44 + * `T3CODE_NPM_LAUNCHER_PATH`), or the Node entry script of a build run from
45 + * source. A standalone executable has none and reports its own path.
46 + *
47 + * The variable is inherited by everything the server spawns, so a launcher
48 + * counts only when its package is this exact version: a different `t3` run
49 + * from an agent's shell must not claim to be the npm install.
50 + */
51 +const resolveEntryPath = Effect.gen(function* () {
52 + const npmLauncher = (yield* HostProcess.Environment).T3CODE_NPM_LAUNCHER_PATH?.trim();
53 + if (npmLauncher) {
54 + const fs = yield* FileSystem.FileSystem;
55 + const path = yield* Path.Path;
56 + const manifest = yield* fs
57 + .readFileString(path.join(path.dirname(npmLauncher), "../package.json"))
58 + .pipe(Effect.flatMap(decodeInstallManifest), Effect.option);
59 + if (
60 + Option.isSome(manifest) &&
61 + manifest.value.name === "t3" &&
62 + manifest.value.version === packageJson.version
63 + ) {
64 + return npmLauncher;
65 + }
66 + }
67 + if (yield* HostProcess.IsExecutable) return yield* HostProcess.ExecutablePath;
68 + return (yield* HostProcess.Arguments)[1] ?? "";
69 +});
70 +
71 export const resolveServerInstallation = Effect.gen(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
45 - const args = yield* HostProcess.Arguments;
46 - const executable = yield* HostProcess.IsExecutable;
47 - const executablePath = yield* HostProcess.ExecutablePath;
74 const platform = yield* HostProcess.Platform;
49 - const entry = yield* fs.realPath(executable ? executablePath : (args[1] ?? ""));
50 - const match =
51 - /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.js|node_modules\/@t3code\/t3-[^/]+\/t3)$/.exec(
52 - entry,
53 - );
75 + const entry = yield* fs.realPath(yield* resolveEntryPath);
76 + const match = /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.mjs)$/.exec(entry);
77 if (!match) {
78 const runner = detectCliRunner(entry);
79 return runner === null
@@ -73,20 +96,7 @@ export const resolveServerInstallation = Effect.gen(function* () {
96 if (manifest.name !== "t3" || !manifest.bin) return null;
97 const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3));
98 const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3"));
76 - if (globalBin !== bin) return null;
77 - if (executable) {
78 - const nativeManifest = yield* fs
79 - .readFileString(path.join(path.dirname(entry), "package.json"))
80 - .pipe(Effect.flatMap(decodeInstallManifest));
81 - if (
82 - manifest.bin.t3 !== "./bin/t3.js" ||
83 - manifest.optionalDependencies?.[nativeManifest.name] !== nativeManifest.version ||
84 - nativeManifest.version !== manifest.version
85 - )
86 - return null;
87 - } else if (bin !== entry) {
88 - return null;
89 - }
99 + if (globalBin !== bin || bin !== entry) return null;
100 return { kind: "npm-global", prefix } satisfies ServerInstallation;
101 }).pipe(Effect.orElseSucceed(() => null));
102
@@ -113,12 +123,8 @@ export function formatCliCommand(input: {
123 }
124
125 export const resolveCliCommand = (subcommand: string) =>
116 - Effect.map(HostProcess.Arguments, (processArguments) =>
117 - formatCliCommand({
118 - subcommand,
119 - entryPath: processArguments[1] ?? "",
120 - version: packageJson.version,
121 - }),
126 + Effect.map(resolveEntryPath, (entryPath) =>
127 + formatCliCommand({ subcommand, entryPath, version: packageJson.version }),
128 );
129
130 const shellWord = (value: string) =>
docs/operations/release.md
+23 -28
@@ -43,15 +43,15 @@ the version.
43 - 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.
44 - Includes Electron auto-update metadata (for example `latest*.yml`, `nightly*.yml`, and `*.blockmap`) in release assets.
45 - 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.
46 - - 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`.
46 + - 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`.
47 - 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`.
48 - 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.
49 - Each archive is extracted and executed on its build runner (`scripts/smoke-cli-archive.ts`) before it is uploaded.
50 -- 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.
50 +- 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.
51 - stable releases publish npm dist-tag `latest`
52 - nightly releases publish npm dist-tag `nightly`
53 - preview releases publish npm dist-tag `preview`, which nothing resolves unless asked for by name
54 - - 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).
54 + - one-time setup: package `t3` needs a trusted publisher registered for this workflow file (see below).
55 - Builds the hosted web app on Vercel while the desktop jobs run, and makes it live only after a release is published:
56 - stable releases are aliased to the `latest` hosted app channel
57 - nightly releases are aliased to the `nightly` hosted app channel
@@ -408,25 +408,31 @@ One-time Vercel dashboard setup:
408 - `make_latest` is always `false`
409 - Uses the next stable patch version as the nightly base. For example, `0.0.17` produces nightlies on `0.0.18-nightly.*`.
410 - Publishes Electron auto-update metadata to the dedicated `nightly` updater channel, so desktop users can opt into that track independently from stable.
411 -- Publishes the CLI npm packages (`t3` and `@t3code/t3-<platform>-<arch>`) to the `nightly` npm dist-tag using the same nightly version.
411 +- Publishes the `t3` npm launcher to the `nightly` npm dist-tag using the same nightly version.
412 - Does not commit version bumps back to `main`.
413
414 ## Server self-update release invariant
415
416 -Connected servers update to the client's exact version, not to an npm dist-tag. Every released
417 -desktop or hosted client version must therefore have a matching `t3@<version>` package available on
418 -npm before users can receive that client.
416 +Connected servers update to the client's exact version, not to an npm dist-tag. Servers that update
417 +themselves download that version's CLI archive from the GitHub Release; servers run through npm are
418 +handed a `t3@<version>` command to run. Every released client version must therefore have its
419 +release archives, and then its npm launcher, available before users can receive that client.
420
421 The workflow enforces this ordering:
422
422 -1. `publish_cli` publishes the exact release version to npm, on every channel.
423 -2. `release` depends on `publish_cli` before exposing desktop artifacts in GitHub Releases.
424 -3. `deploy_web` depends on `release` before moving the hosted channel to the new client.
423 +1. `release` publishes the GitHub Release with the CLI archives and `SHA256SUMS`.
424 +2. `publish_cli` publishes the `t3@<version>` launcher, which downloads from that release, on every
425 + channel.
426 +3. `deploy_web` depends on both before moving the hosted channel to the new client.
427 `build_web` builds that client earlier with `vercel deploy --prod --skip-domain`, which
428 leaves the custom domains alone but moves the project's own `*.vercel.app` production
429 hostname. That hostname is behind Vercel SSO, so users only get the client through the
430 custom domains.
431
432 +Desktop auto-update reads the GitHub Release directly, so a desktop client can see the new version
433 +a few minutes before `t3@<version>` is on npm. Only the copied manual command for npm-run servers
434 +depends on npm, and it works once `publish_cli` finishes.
435 +
436 Preserve these dependencies when changing the release graph. Publishing a client first would leave
437 the **Update server** action targeting a package version that does not exist yet.
438
@@ -508,32 +514,21 @@ blockmaps, with a 60 MB maximum for a representative sidecar-to-sidecar update.
514
515 ## 0) npm OIDC trusted publishing setup (CLI)
516
511 -The workflow runs `node scripts/build-npm-platform-packages.ts` on the downloaded CLI archives, then
517 +After the GitHub Release is published, the workflow runs `node scripts/build-npm-launcher.ts`, then
518 `node apps/server/scripts/cli.ts publish --packages-dir npm-packages`, which runs `npm publish` on
513 -each `@t3code/t3-<platform>-<arch>.tgz` and finally on `t3.tgz`, the launcher. The script publishes
514 -tarballs it built itself rather than directories: `npm publish <dir>` strips `node_modules/` from the
515 -tarball no matter what `files` says, and the executable loads its native addons from there. Seven
516 -packages are published per release: `t3`, `@t3code/t3-darwin-arm64`, `@t3code/t3-darwin-x64`,
517 -`@t3code/t3-linux-arm64`, `@t3code/t3-linux-x64`, `@t3code/t3-win32-arm64`,
518 -`@t3code/t3-win32-x64`.
519 +`t3.tgz`. That is the only package published per release.
520
521 Checklist:
522
522 -1. Confirm the npm org owns package `t3` and the `@t3code` scope exists on npm (create the org if
523 - it does not).
524 -2. For `t3` and each `@t3code/t3-<platform>-<arch>` package, configure a Trusted Publisher in the
525 - npm package settings (a package that has never been published needs a first publish or a
526 - placeholder before the setting exists; the `--dry-run` step in `publish_cli` reports which
527 - names are still rejected):
523 +1. Confirm the npm org owns package `t3`.
524 +2. For `t3`, configure a Trusted Publisher in the npm package settings:
525 - Provider: GitHub Actions
526 - Repository: this repo
527 - Workflow file: `.github/workflows/release.yml`
528 - Environment (if used): match your npm trusted publishing config
532 -3. Ensure npm account and org policies allow trusted publishing for every package.
533 -4. Create release tag `vX.Y.Z` and push; workflow will:
534 - - build and smoke-test the five CLI archives
535 - - build the npm packages from those archives
536 - - publish them with npm dist-tag `latest`
529 +3. Ensure npm account and org policies allow trusted publishing for the package.
530 +4. Create release tag `vX.Y.Z` and push; the workflow publishes the GitHub Release and then the
531 + launcher with npm dist-tag `latest`.
532 5. Nightly runs publish with npm dist-tag `nightly`; preview runs with `preview`.
533
534 ## 1) Release validation and unsigned builds
knip.jsonc
+2
@@ -20,6 +20,8 @@
20 // Knip loads its preprocessor through a CLI option; native verification and
21 // worktree setup (from t3.json) run directly.
22 "entry": ["knip-schemas.ts", "mobile-native-client.ts", "setup-worktree.ts"],
23 + // The `t3` npm package's files: copied into the package, never imported.
24 + "ignore": ["npm-launcher/**"],
25 },
26 "apps/server": {
27 // Vite+ pack entries and the launcher used by installed background services.
packages/shared/package.json
-4
@@ -15,10 +15,6 @@
15 "types": "./src/orchestrationV2ThreadError.ts",
16 "import": "./src/orchestrationV2ThreadError.ts"
17 },
18 - "./legacyCliLauncher": {
19 - "types": "./src/legacyCliLauncher.ts",
20 - "import": "./src/legacyCliLauncher.ts"
21 - },
18 "./delimitedPreview": {
19 "types": "./src/delimitedPreview.ts",
20 "import": "./src/delimitedPreview.ts"
packages/shared/src/cliRelease.ts
+1 -1
@@ -10,7 +10,7 @@ export const CLI_RELEASE_BASE_URL_ENV = "T3CODE_RELEASE_BASE_URL";
10 */
11 // No darwin-x64: Node single-executables are unsupported on x64 macOS (the
12 // SEA docs list macOS as arm64 only) and the binary segfaults on start.
13 -export const CLI_ARCHIVE_PLATFORM_KEYS = [
13 +const CLI_ARCHIVE_PLATFORM_KEYS = [
14 "darwin-arm64",
15 "linux-arm64",
16 "linux-x64",
packages/shared/src/legacyCliLauncher.test.ts deleted
-62
@@ -1,62 +0,0 @@
1 -// @effect-diagnostics nodeBuiltinImport:off - Exercises real Node IPC and process signals.
2 -import * as NodeChildProcess from "node:child_process";
3 -import * as NodeEvents from "node:events";
4 -import * as NodeFSP from "node:fs/promises";
5 -import * as NodeOS from "node:os";
6 -import * as NodePath from "node:path";
7 -import { expect, it } from "vite-plus/test";
8 -
9 -import { legacyCliLauncherScript } from "./legacyCliLauncher.ts";
10 -
11 -// oxlint-disable-next-line t3code/no-global-process-runtime -- This test launches a real host executable.
12 -const hostPlatform = NodeOS.platform();
13 -// oxlint-disable-next-line t3code/no-global-process-runtime -- Match the real executable used by the subprocess.
14 -const hostArch = NodeOS.arch();
15 -
16 -// The fixture executable uses a POSIX shebang.
17 -it.skipIf(hostPlatform === "win32")(
18 - "keeps service IPC, arguments, and termination connected",
19 - async () => {
20 - const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-legacy-launcher-"));
21 - const entry = NodePath.join(root, "node_modules/t3/dist/bin.mjs");
22 - const executable = NodePath.join(
23 - root,
24 - `node_modules/@t3code/t3-${hostPlatform}-${hostArch}/t3`,
25 - );
26 - await NodeFSP.mkdir(NodePath.dirname(entry), { recursive: true });
27 - await NodeFSP.mkdir(NodePath.dirname(executable), { recursive: true });
28 - await NodeFSP.writeFile(
29 - NodePath.join(NodePath.dirname(executable), "package.json"),
30 - '{"type":"commonjs"}',
31 - );
32 - await NodeFSP.writeFile(entry, legacyCliLauncherScript());
33 - await NodeFSP.writeFile(
34 - executable,
35 - `#!${process.execPath}
36 -process.on("SIGTERM", () => process.exit(23));
37 -process.on("message", message => process.send({ reply: message }));
38 -process.send({ args: process.argv.slice(2) });
39 -`,
40 - );
41 - await NodeFSP.chmod(executable, 0o755);
42 - const child = NodeChildProcess.fork(entry, ["serve", "a path with spaces"], { silent: true });
43 - try {
44 - expect((await NodeEvents.EventEmitter.once(child, "message"))[0]).toEqual({
45 - args: ["serve", "a path with spaces"],
46 - });
47 - const reply = NodeEvents.EventEmitter.once(child, "message");
48 - child.send({ type: "trial-accepted" });
49 - expect((await reply)[0]).toEqual({ reply: { type: "trial-accepted" } });
50 - const exit = NodeEvents.EventEmitter.once(child, "exit");
51 - child.kill("SIGTERM");
52 - expect(await exit).toEqual([23, null]);
53 - } finally {
54 - if (child.exitCode === null && child.signalCode === null) {
55 - const exit = NodeEvents.EventEmitter.once(child, "exit");
56 - child.kill("SIGTERM");
57 - await exit;
58 - }
59 - await NodeFSP.rm(root, { recursive: true, force: true });
60 - }
61 - },
62 -);
packages/shared/src/legacyCliLauncher.ts deleted
-35
@@ -1,35 +0,0 @@
1 -/**
2 - * `dist/bin.mjs` of the `t3` npm package: the entry point boot-service
3 - * launchers installed before 0.0.41 run with Node to start a new version they
4 - * just npm-installed.
5 - */
6 -export function legacyCliLauncherScript(): string {
7 - return `import { spawn } from "node:child_process";
8 -import { constants } from "node:os";
9 -import { dirname, join } from "node:path";
10 -import { createRequire } from "node:module";
11 -const require = createRequire(import.meta.url);
12 -const executableName = process.platform === "win32" ? "t3.exe" : "t3";
13 -const executable = join(dirname(require.resolve("@t3code/t3-" + process.platform + "-" + process.arch + "/package.json")), executableName);
14 -const ipc = process.send !== undefined;
15 -const child = spawn(executable, process.argv.slice(2), {
16 - stdio: ipc ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
17 -});
18 -const fail = (error) => {
19 - if (!error) return;
20 - process.stderr.write("t3: " + error.message + "\\n");
21 - child.kill("SIGTERM");
22 - process.exitCode = 1;
23 -};
24 -if (ipc) {
25 - process.on("message", (message) => { if (child.connected) child.send(message, fail); });
26 - child.on("message", (message) => { if (process.connected) process.send(message, fail); });
27 - process.on("disconnect", () => { if (child.connected) child.disconnect(); });
28 -}
29 -for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
30 - process.on(signal, () => child.kill(signal));
31 -}
32 -child.on("error", (error) => { fail(error); process.exit(1); });
33 -child.on("exit", (code, signal) => process.exit(code ?? 128 + (constants.signals[signal] || 1)));
34 -`;
35 -}
scripts/build-npm-launcher.test.ts new
+217
@@ -0,0 +1,217 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - Serves a fake GitHub Release over real HTTP to the published launcher.
2 +import * as NodeServices from "@effect/platform-node/NodeServices";
3 +import { assert, it } from "@effect/vitest";
4 +import * as HostProcess from "@t3tools/shared/HostProcess";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Path from "effect/Path";
8 +import * as Schema from "effect/Schema";
9 +import * as Stream from "effect/Stream";
10 +import { ChildProcess, ChildProcessSpawner } from "effect/process";
11 +import * as NodeChildProcess from "node:child_process";
12 +import * as NodeCrypto from "node:crypto";
13 +import * as NodeEvents from "node:events";
14 +import * as NodeHttp from "node:http";
15 +
16 +import { buildNpmLauncher } from "./build-npm-launcher.ts";
17 +
18 +const VERSION = "1.2.3";
19 +const decodeManifest = Schema.decodeEffect(
20 + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
21 +);
22 +
23 +const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
24 + stream.pipe(
25 + Stream.decodeText(),
26 + Stream.runFold(
27 + () => "",
28 + (acc, chunk) => acc + chunk,
29 + ),
30 + );
31 +
32 +const run = Effect.fn("test.run")(function* (
33 + command: string,
34 + args: ReadonlyArray<string>,
35 + options: { readonly cwd: string; readonly env: Record<string, string | undefined> },
36 +) {
37 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
38 + const child = yield* spawner.spawn(
39 + ChildProcess.make(command, args, { cwd: options.cwd, env: options.env, extendEnv: false }),
40 + );
41 + const [stdout, stderr, exitCode] = yield* Effect.all(
42 + [collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
43 + { concurrency: "unbounded" },
44 + );
45 + return { stdout, stderr, exitCode };
46 +}, Effect.scoped);
47 +
48 +/** A release archive for this host with a stub `t3` that echoes its args and launcher. */
49 +const serveFakeRelease = Effect.fn("test.serveFakeRelease")(function* (root: string) {
50 + const fs = yield* FileSystem.FileSystem;
51 + const path = yield* Path.Path;
52 + const key = `${yield* HostProcess.Platform}-${yield* HostProcess.Architecture}`;
53 + const stem = `t3-${VERSION}-${key}`;
54 + const archiveName = `${stem}.tar.gz`;
55 + yield* fs.makeDirectory(path.join(root, "release", stem, "node_modules/native"), {
56 + recursive: true,
57 + });
58 + yield* fs.writeFileString(
59 + path.join(root, "release", stem, "t3"),
60 + '#!/bin/sh\necho "stub $* launcher=$T3CODE_NPM_LAUNCHER_PATH"\nexit 7\n',
61 + );
62 + yield* fs.chmod(path.join(root, "release", stem, "t3"), 0o755);
63 + const tar = yield* run("tar", ["-czf", archiveName, stem], {
64 + cwd: path.join(root, "release"),
65 + env: { PATH: process.env.PATH },
66 + });
67 + assert.equal(tar.exitCode, 0, tar.stderr);
68 + const archive = yield* fs.readFile(path.join(root, "release", archiveName));
69 + let checksum = NodeCrypto.createHash("sha256").update(archive).digest("hex");
70 + const requests: Array<string> = [];
71 + const server = NodeHttp.createServer((request, response) => {
72 + requests.push(request.url ?? "");
73 + if (request.url === `/v${VERSION}/SHA256SUMS`) {
74 + response.end(`${checksum} ${archiveName}\n`);
75 + } else if (request.url === `/v${VERSION}/${archiveName}`) {
76 + response.writeHead(200, { "Content-Length": archive.length }).end(archive);
77 + } else {
78 + response.writeHead(404).end();
79 + }
80 + });
81 + yield* Effect.acquireRelease(
82 + Effect.callback<void>((resume) => {
83 + server.listen(0, "127.0.0.1", () => resume(Effect.void));
84 + }),
85 + () =>
86 + Effect.callback<void>((resume) => {
87 + server.close(() => resume(Effect.void));
88 + }),
89 + );
90 + const address = server.address();
91 + if (address === null || typeof address === "string") return yield* Effect.die("no TCP address");
92 + return {
93 + baseUrl: `http://127.0.0.1:${address.port}`,
94 + requests,
95 + corruptChecksum: () => {
96 + checksum = "0".repeat(64);
97 + },
98 + };
99 +});
100 +
101 +it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
102 + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
103 + "publishes a launcher that downloads, verifies, caches, and runs the release executable",
104 + () =>
105 + Effect.gen(function* () {
106 + const fs = yield* FileSystem.FileSystem;
107 + const path = yield* Path.Path;
108 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" });
109 + const output = yield* buildNpmLauncher({
110 + version: VERSION,
111 + outputDir: path.join(root, "out"),
112 + });
113 +
114 + const manifest = yield* decodeManifest(
115 + yield* fs.readFileString(path.join(output.packageDir, "package.json")),
116 + );
117 + assert.equal(manifest.name, "t3");
118 + assert.equal(manifest.version, VERSION);
119 + assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
120 + // Nothing for npm to resolve, so nothing that can lag behind the launcher.
121 + assert.isUndefined(manifest.dependencies);
122 + assert.isUndefined(manifest.optionalDependencies);
123 +
124 + // Run what npm would install: the published tarball, unpacked.
125 + const installed = path.join(root, "installed");
126 + yield* fs.makeDirectory(installed);
127 + const unpack = yield* run("tar", ["-xzf", output.tarball, "-C", installed], {
128 + cwd: root,
129 + env: { PATH: process.env.PATH },
130 + });
131 + assert.equal(unpack.exitCode, 0, unpack.stderr);
132 + const packageDir = path.join(installed, "package");
133 +
134 + const release = yield* serveFakeRelease(root);
135 + const home = path.join(root, "home");
136 + const env = {
137 + PATH: process.env.PATH,
138 + T3CODE_HOME: home,
139 + T3CODE_RELEASE_BASE_URL: release.baseUrl,
140 + };
141 + const launcher = path.join(packageDir, "bin/t3.mjs");
142 + const first = yield* run(process.execPath, [launcher, "serve", "a b"], {
143 + cwd: root,
144 + env,
145 + });
146 + assert.equal(first.stdout.trim(), `stub serve a b launcher=${launcher}`, first.stderr);
147 + assert.equal(first.exitCode, 7);
148 + // The same layout the install scripts and `t3 update` use.
149 + const versionDir = path.join(home, "runtime/versions", VERSION);
150 + assert.equal(
151 + (yield* fs.readFileString(path.join(versionDir, ".install-complete"))).trim(),
152 + VERSION,
153 + );
154 + assert.isTrue(yield* fs.exists(path.join(versionDir, "node_modules/native")));
155 + assert.deepStrictEqual(
156 + (yield* fs.readDirectory(path.join(home, "runtime/versions"))).sort(),
157 + [VERSION],
158 + );
159 +
160 + // A second run reuses the download.
161 + const requestsAfterFirst = release.requests.length;
162 + const second = yield* run(process.execPath, [launcher, "--version"], { cwd: root, env });
163 + assert.equal(second.exitCode, 7);
164 + assert.equal(release.requests.length, requestsAfterFirst);
165 +
166 + // Services installed before 0.0.41 fork dist/bin.mjs and talk to the
167 + // server over IPC; the channel and SIGTERM must reach the executable.
168 + const ipcServer = path.join(home, "runtime/versions", VERSION, "t3");
169 + yield* fs.writeFileString(
170 + ipcServer,
171 + `#!${process.execPath}\nprocess.on("SIGTERM", () => process.exit(23));\nprocess.on("message", (m) => process.send({ reply: m }));\nprocess.send({ args: process.argv.slice(2) });\n`,
172 + );
173 + const legacy = NodeChildProcess.fork(
174 + path.join(packageDir, "dist/bin.mjs"),
175 + ["__service-preflight", "a b"],
176 + { env, silent: true },
177 + );
178 + yield* Effect.promise(async () => {
179 + assert.deepStrictEqual((await NodeEvents.EventEmitter.once(legacy, "message"))[0], {
180 + args: ["__service-preflight", "a b"],
181 + });
182 + const reply = NodeEvents.EventEmitter.once(legacy, "message");
183 + legacy.send({ type: "trial-accepted" });
184 + assert.deepStrictEqual((await reply)[0], { reply: { type: "trial-accepted" } });
185 + const exit = NodeEvents.EventEmitter.once(legacy, "exit");
186 + legacy.kill("SIGTERM");
187 + assert.deepStrictEqual(await exit, [23, null]);
188 + });
189 +
190 + // Two first runs at once both start, and neither removes the other's install.
191 + const raceHome = path.join(root, "race-home");
192 + const launch = run(process.execPath, [launcher, "--version"], {
193 + cwd: root,
194 + env: { ...env, T3CODE_HOME: raceHome },
195 + });
196 + const [one, two] = yield* Effect.all([launch, launch], { concurrency: "unbounded" });
197 + assert.equal(one.exitCode, 7, one.stderr);
198 + assert.equal(two.exitCode, 7, two.stderr);
199 + assert.deepStrictEqual(yield* fs.readDirectory(path.join(raceHome, "runtime/versions")), [
200 + VERSION,
201 + ]);
202 +
203 + // A download that does not match the release checksums is never installed.
204 + release.corruptChecksum();
205 + const corrupt = yield* run(process.execPath, [launcher, "--version"], {
206 + cwd: root,
207 + env: { ...env, T3CODE_HOME: path.join(root, "other-home") },
208 + });
209 + assert.equal(corrupt.exitCode, 1);
210 + assert.include(corrupt.stderr, "checksum mismatch");
211 + assert.deepStrictEqual(
212 + yield* fs.readDirectory(path.join(root, "other-home/runtime/versions")),
213 + [],
214 + );
215 + }),
216 + );
217 +});
scripts/build-npm-launcher.ts new
+125
@@ -0,0 +1,125 @@
1 +#!/usr/bin/env node
2 +/**
3 + * Builds the `t3` npm package behind `npx t3` / `npm i -g t3`: a launcher
4 + * with no dependencies that downloads this exact version's CLI archive from
5 + * the GitHub Release on first run (scripts/npm-launcher/t3.mjs).
6 + * The executables are not published to npm. npm's publish-time scanning held
7 + * 250 MB platform packages back for up to an hour after the launcher went
8 + * live, and every install in that window ran a launcher with nothing to
9 + * launch.
10 + *
11 + * Output: `<output-dir>/t3/` (the package tree) and `<output-dir>/t3.tgz`,
12 + * which is what gets published.
13 + */
14 +import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
15 +import * as NodeServices from "@effect/platform-node/NodeServices";
16 +import * as Effect from "effect/Effect";
17 +import * as FileSystem from "effect/FileSystem";
18 +import * as Layer from "effect/Layer";
19 +import * as Logger from "effect/Logger";
20 +import * as Path from "effect/Path";
21 +import * as Schema from "effect/Schema";
22 +import { Command, Flag } from "effect/cli";
23 +import { ChildProcess, ChildProcessSpawner } from "effect/process";
24 +
25 +import * as HostProcess from "@t3tools/shared/HostProcess";
26 +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
27 +import serverPackageJson from "../apps/server/package.json" with { type: "json" };
28 +
29 +import { windowsSystemTar } from "./build-cli-archive.ts";
30 +
31 +export const NPM_LAUNCHER_PACKAGE_NAME = "t3";
32 +
33 +const encodePackageJson = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown));
34 +
35 +export class NpmLauncherCommandFailedError extends Schema.TaggedError<NpmLauncherCommandFailedError>()(
36 + "NpmLauncherCommandFailedError",
37 + { command: Schema.String, exitCode: Schema.Int },
38 +) {
39 + override get message(): string {
40 + return `${this.command} exited with code ${this.exitCode}.`;
41 + }
42 +}
43 +
44 +/** package.json for the launcher. `engines` asks for `import.meta.dirname` and `fetch`. */
45 +export function npmLauncherPackageManifest(version: string) {
46 + return {
47 + name: NPM_LAUNCHER_PACKAGE_NAME,
48 + version,
49 + description:
50 + "T3 Code CLI. Downloads the self-contained executable for this platform from the GitHub Release.",
51 + license: serverPackageJson.license,
52 + repository: serverPackageJson.repository,
53 + bin: { t3: "./bin/t3.mjs" },
54 + files: ["bin", "dist"],
55 + engines: { node: ">=20.11" },
56 + };
57 +}
58 +
59 +export const buildNpmLauncher = Effect.fn("buildNpmLauncher")(function* (input: {
60 + readonly version: string;
61 + readonly outputDir: string;
62 +}) {
63 + const fs = yield* FileSystem.FileSystem;
64 + const path = yield* Path.Path;
65 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
66 + const sourceDir = yield* path.fromFileUrl(new URL("./npm-launcher/", import.meta.url));
67 +
68 + yield* fs.makeDirectory(input.outputDir, { recursive: true });
69 + const scratch = yield* fs.makeTempDirectoryScoped({
70 + directory: input.outputDir,
71 + prefix: ".launcher-",
72 + });
73 + const stageDir = path.join(scratch, "package");
74 + yield* fs.makeDirectory(path.join(stageDir, "bin"), { recursive: true });
75 + yield* fs.makeDirectory(path.join(stageDir, "dist"));
76 + yield* fs.writeFileString(
77 + path.join(stageDir, "package.json"),
78 + `${yield* encodePackageJson(npmLauncherPackageManifest(input.version))}\n`,
79 + );
80 + yield* fs.copyFile(path.join(sourceDir, "t3.mjs"), path.join(stageDir, "bin/t3.mjs"));
81 + yield* fs.chmod(path.join(stageDir, "bin/t3.mjs"), 0o755);
82 + yield* fs.copyFile(path.join(sourceDir, "bin.mjs"), path.join(stageDir, "dist/bin.mjs"));
83 + const readme = yield* path.fromFileUrl(new URL("../apps/server/README.md", import.meta.url));
84 + if (yield* fs.exists(readme)) {
85 + yield* fs.copyFile(readme, path.join(stageDir, "README.md"));
86 + }
87 +
88 + const packageDir = path.join(input.outputDir, NPM_LAUNCHER_PACKAGE_NAME);
89 + const tarball = path.join(input.outputDir, `${NPM_LAUNCHER_PACKAGE_NAME}.tgz`);
90 + yield* fs.remove(tarball, { force: true });
91 + const tar = (yield* HostProcess.Platform) === "win32" ? windowsSystemTar() : "tar";
92 + // npm tarballs root everything under `package/`.
93 + const child = yield* spawner.spawn(
94 + ChildProcess.make(tar, ["-czf", tarball, "-C", scratch, "package"], {
95 + stdout: "inherit",
96 + stderr: "inherit",
97 + }),
98 + );
99 + const exitCode = Number(yield* child.exitCode);
100 + if (exitCode !== 0) {
101 + return yield* new NpmLauncherCommandFailedError({ command: `tar (${tarball})`, exitCode });
102 + }
103 + yield* fs.remove(packageDir, { recursive: true, force: true });
104 + yield* fs.rename(stageDir, packageDir);
105 + yield* Effect.log(`[npm-launcher] Wrote ${packageDir} and ${tarball}`);
106 + return { packageDir, tarball };
107 +}, Effect.scoped);
108 +
109 +const command = Command.make(
110 + "build-npm-launcher",
111 + {
112 + version: Flag.String("version").pipe(
113 + Flag.withDescription("Exact release version; the launcher downloads this version's archive."),
114 + ),
115 + outputDir: Flag.String("output-dir").pipe(Flag.withDefault("npm-packages")),
116 + },
117 + buildNpmLauncher,
118 +).pipe(Command.withDescription("Build the t3 npm launcher package."));
119 +
120 +if (import.meta.main) {
121 + Command.run(command, { version: "0.0.0" }).pipe(
122 + Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
123 + NodeRuntime.runMain,
124 + );
125 +}
scripts/build-npm-platform-packages.test.ts deleted
-247
@@ -1,247 +0,0 @@
1 -import * as HostProcess from "@t3tools/shared/HostProcess";
2 -import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { assert, it } from "@effect/vitest";
4 -import * as Effect from "effect/Effect";
5 -import * as FileSystem from "effect/FileSystem";
6 -import * as Path from "effect/Path";
7 -import * as Schema from "effect/Schema";
8 -import * as Stream from "effect/Stream";
9 -import { ChildProcess, ChildProcessSpawner } from "effect/process";
10 -
11 -import {
12 - buildNpmPlatformPackages,
13 - NpmPackagesArchivesMissingError,
14 -} from "./build-npm-platform-packages.ts";
15 -
16 -const VERSION = "1.2.3";
17 -const decodeManifest = Schema.decodeEffect(
18 - Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
19 -);
20 -const KEYS = ["linux-x64", "darwin-arm64"] as const;
21 -
22 -const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
23 - stream.pipe(
24 - Stream.decodeText(),
25 - Stream.runFold(
26 - () => "",
27 - (acc, chunk) => acc + chunk,
28 - ),
29 - );
30 -
31 -const run = Effect.fn("test.run")(function* (
32 - command: string,
33 - args: ReadonlyArray<string>,
34 - options: { readonly cwd: string; readonly env?: Record<string, string> },
35 -) {
36 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
37 - const child = yield* spawner.spawn(
38 - ChildProcess.make(command, args, { cwd: options.cwd, env: options.env ?? {} }),
39 - );
40 - const [stdout, stderr, exitCode] = yield* Effect.all(
41 - [collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
42 - { concurrency: "unbounded" },
43 - );
44 - return { stdout, stderr, exitCode };
45 -});
46 -
47 -const makeFakeArchives = Effect.fn("test.makeFakeArchives")(function* () {
48 - const fs = yield* FileSystem.FileSystem;
49 - const path = yield* Path.Path;
50 - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-packages-test-" });
51 - const archivesDir = path.join(root, "archives");
52 - yield* fs.makeDirectory(archivesDir);
53 - for (const key of KEYS) {
54 - const stem = `t3-${VERSION}-${key}`;
55 - const stage = path.join(root, "stage", key);
56 - const contentDir = path.join(stage, stem);
57 - for (const dir of [
58 - "client",
59 - "resource-monitor",
60 - "node_modules/node-pty",
61 - "node_modules/@ff-labs/fff-node",
62 - ]) {
63 - yield* fs.makeDirectory(path.join(contentDir, dir), { recursive: true });
64 - }
65 - yield* fs.writeFileString(
66 - path.join(contentDir, "node_modules/node-pty/package.json"),
67 - '{ "name": "node-pty", "version": "1.1.0" }\n',
68 - );
69 - yield* fs.writeFileString(
70 - path.join(contentDir, "node_modules/@ff-labs/fff-node/package.json"),
71 - '{ "name": "@ff-labs/fff-node", "version": "0.9.4" }\n',
72 - );
73 - yield* fs.writeFileString(path.join(contentDir, "client/index.html"), "<html></html>\n");
74 - yield* fs.writeFileString(
75 - path.join(contentDir, "t3"),
76 - `#!/bin/sh\necho "stub ${key} $*"\nexit 7\n`,
77 - );
78 - yield* fs.chmod(path.join(contentDir, "t3"), 0o755);
79 - const exit = yield* run("tar", ["-czf", path.join(archivesDir, `${stem}.tar.gz`), stem], {
80 - cwd: stage,
81 - });
82 - assert.equal(exit.exitCode, 0, exit.stderr);
83 - }
84 - yield* fs.writeFileString(path.join(archivesDir, "SHA256SUMS"), "");
85 - return { root, archivesDir, outputDir: path.join(root, "out") };
86 -});
87 -
88 -it.layer(NodeServices.layer)("build-npm-platform-packages", (it) => {
89 - it.effect("refuses a partial release unless --allow-missing is passed", () =>
90 - Effect.gen(function* () {
91 - const fixture = yield* makeFakeArchives();
92 - const error = yield* buildNpmPlatformPackages({
93 - ...fixture,
94 - version: VERSION,
95 - allowMissing: false,
96 - }).pipe(Effect.flip);
97 - assert.instanceOf(error, NpmPackagesArchivesMissingError);
98 - assert.deepStrictEqual((error as NpmPackagesArchivesMissingError).missing, [
99 - "linux-arm64",
100 - "win32-arm64",
101 - "win32-x64",
102 - ]);
103 - }),
104 - );
105 -
106 - it.effect("builds platform packages and a launcher that execs the installed one", () =>
107 - Effect.gen(function* () {
108 - const fs = yield* FileSystem.FileSystem;
109 - const path = yield* Path.Path;
110 - const fixture = yield* makeFakeArchives();
111 - const outputs = yield* buildNpmPlatformPackages({
112 - ...fixture,
113 - version: VERSION,
114 - allowMissing: true,
115 - });
116 - assert.deepStrictEqual(
117 - outputs.map((output) => output.name),
118 - ["@t3code/t3-darwin-arm64", "@t3code/t3-linux-x64", "t3"],
119 - );
120 - for (const output of outputs) {
121 - assert.isTrue(yield* fs.exists(output.tarball), output.tarball);
122 - }
123 -
124 - const linuxDir = path.join(fixture.outputDir, "@t3code/t3-linux-x64");
125 - const linuxManifest = yield* decodeManifest(
126 - yield* fs.readFileString(path.join(linuxDir, "package.json")),
127 - );
128 - assert.equal(linuxManifest.name, "@t3code/t3-linux-x64");
129 - assert.equal(linuxManifest.version, VERSION);
130 - assert.deepStrictEqual(linuxManifest.os, ["linux"]);
131 - assert.deepStrictEqual(linuxManifest.cpu, ["x64"]);
132 - assert.deepStrictEqual(linuxManifest.files, [
133 - "t3",
134 - "t3.exe",
135 - "client",
136 - "resource-monitor",
137 - "node_modules",
138 - ]);
139 - assert.equal(linuxManifest.preferUnplugged, true);
140 - assert.isUndefined(linuxManifest.bin);
141 - assert.deepStrictEqual(linuxManifest.dependencies, {
142 - "@ff-labs/fff-node": "0.9.4",
143 - "node-pty": "1.1.0",
144 - });
145 - assert.deepStrictEqual(linuxManifest.bundleDependencies, ["@ff-labs/fff-node", "node-pty"]);
146 - assert.isTrue(yield* fs.exists(path.join(linuxDir, "client/index.html")));
147 - assert.include(
148 - yield* fs.readFileString(path.join(linuxDir, "README.md")),
149 - "# @t3code/t3-linux-x64",
150 - );
151 - assert.isTrue(yield* fs.exists(path.join(linuxDir, "node_modules/node-pty")));
152 - assert.equal(Number((yield* fs.stat(path.join(linuxDir, "t3"))).mode) & 0o111, 0o111);
153 -
154 - const darwinManifest = yield* decodeManifest(
155 - yield* fs.readFileString(
156 - path.join(fixture.outputDir, "@t3code/t3-darwin-arm64/package.json"),
157 - ),
158 - );
159 - assert.deepStrictEqual(darwinManifest.os, ["darwin"]);
160 - assert.deepStrictEqual(darwinManifest.cpu, ["arm64"]);
161 -
162 - const launcherDir = path.join(fixture.outputDir, "t3");
163 - const launcherManifest = yield* decodeManifest(
164 - yield* fs.readFileString(path.join(launcherDir, "package.json")),
165 - );
166 - assert.equal(launcherManifest.name, "t3");
167 - assert.equal(launcherManifest.version, VERSION);
168 - assert.deepStrictEqual(launcherManifest.bin, { t3: "./bin/t3.js" });
169 - assert.deepStrictEqual(launcherManifest.files, ["bin", "dist"]);
170 - assert.deepStrictEqual(launcherManifest.optionalDependencies, {
171 - "@t3code/t3-darwin-arm64": VERSION,
172 - "@t3code/t3-linux-x64": VERSION,
173 - });
174 - assert.isUndefined(launcherManifest.engines);
175 - assert.isTrue(yield* fs.exists(path.join(launcherDir, "bin/t3.js")));
176 -
177 - const outputEntries = yield* fs.readDirectory(fixture.outputDir);
178 - assert.deepStrictEqual(outputEntries.sort(), ["@t3code", "t3", "t3.tgz"]);
179 -
180 - const listing = yield* run(
181 - "tar",
182 - ["-tzvf", path.join(fixture.outputDir, "@t3code/t3-linux-x64.tgz")],
183 - { cwd: fixture.outputDir },
184 - );
185 - assert.equal(listing.exitCode, 0, listing.stderr);
186 - const lines = listing.stdout.split("\n");
187 - assert.isTrue(lines.some((line) => line.endsWith(" package/node_modules/node-pty/")));
188 - assert.isTrue(lines.some((line) => line.endsWith(" package/package.json")));
189 - assert.isTrue(
190 - lines.some((line) => /^-rwxr-xr-x .* package\/t3$/.test(line)),
191 - listing.stdout,
192 - );
193 -
194 - const hostPlatform = yield* HostProcess.Platform;
195 - const hostArch = yield* HostProcess.Architecture;
196 - const env = { ...process.env, NODE_PATH: fixture.outputDir } as Record<string, string>;
197 - if (KEYS.some((key) => key === `${hostPlatform}-${hostArch}`)) {
198 - const passthrough = yield* run(process.execPath, ["bin/t3.js", "serve", "--port", "1234"], {
199 - cwd: launcherDir,
200 - env,
201 - });
202 - assert.equal(
203 - passthrough.stdout.trim(),
204 - `stub ${hostPlatform}-${hostArch} serve --port 1234`,
205 - );
206 - assert.equal(passthrough.exitCode, 7);
207 -
208 - const installedLauncher = path.join(fixture.root, "installed-launcher");
209 - yield* fs.makeDirectory(installedLauncher);
210 - const unpack = yield* run(
211 - "tar",
212 - ["-xf", path.join(fixture.outputDir, "t3.tgz"), "-C", installedLauncher],
213 - {
214 - cwd: fixture.root,
215 - },
216 - );
217 - assert.equal(unpack.exitCode, 0, unpack.stderr);
218 - const legacy = yield* run(
219 - process.execPath,
220 - [
221 - "dist/bin.mjs",
222 - "__service-preflight",
223 - "--database-path",
224 - "a database.sqlite",
225 - "--launcher-protocol",
226 - "2",
227 - ],
228 - { cwd: path.join(installedLauncher, "package"), env },
229 - );
230 - assert.equal(
231 - legacy.stdout.trim(),
232 - `stub ${hostPlatform}-${hostArch} __service-preflight --database-path a database.sqlite --launcher-protocol 2`,
233 - );
234 - assert.equal(legacy.exitCode, 7);
235 - }
236 -
237 - const unsupported = yield* run(process.execPath, ["bin/t3.js", "--version"], {
238 - cwd: launcherDir,
239 - env: { ...env, NODE_PATH: path.join(fixture.root, "nowhere") },
240 - });
241 - assert.equal(unsupported.exitCode, 1);
242 - assert.include(unsupported.stderr, "linux-x64");
243 - assert.include(unsupported.stderr, "win32-arm64");
244 - assert.include(unsupported.stderr, "https://github.com/pingdotgg/t3code/releases");
245 - }),
246 - );
247 -});
scripts/build-npm-platform-packages.ts deleted
-451
@@ -1,451 +0,0 @@
1 -#!/usr/bin/env node
2 -/**
3 - * `npm publish <dir>` always drops `node_modules/` (npm-packlist ignores it
4 - * whatever `files` says, and bundleDependencies needs an arborist tree these
5 - * flattened installs are not), whereas `npm publish <tarball>` uploads the
6 - * bytes as given.
7 - */
8 -import { legacyCliLauncherScript } from "@t3tools/shared/legacyCliLauncher";
9 -import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
10 -import * as NodeServices from "@effect/platform-node/NodeServices";
11 -import * as Effect from "effect/Effect";
12 -import * as FileSystem from "effect/FileSystem";
13 -import * as Layer from "effect/Layer";
14 -import * as Logger from "effect/Logger";
15 -import * as Path from "effect/Path";
16 -import * as Schema from "effect/Schema";
17 -import { Command, Flag } from "effect/cli";
18 -import { ChildProcess, ChildProcessSpawner } from "effect/process";
19 -
20 -import {
21 - CLI_ARCHIVE_PLATFORM_KEYS,
22 - cliArchiveFileName,
23 - type CliArchivePlatformKey,
24 -} from "@t3tools/shared/cliRelease";
25 -import * as HostProcess from "@t3tools/shared/HostProcess";
26 -import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
27 -import { isCommandAvailable } from "@t3tools/shared/shell";
28 -import serverPackageJson from "../apps/server/package.json" with { type: "json" };
29 -
30 -import { windowsSystemTar } from "./build-cli-archive.ts";
31 -
32 -export const NPM_PLATFORM_PACKAGE_SCOPE = "@t3code";
33 -export const NPM_LAUNCHER_PACKAGE_NAME = "t3";
34 -
35 -const encodePackageJson = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown));
36 -
37 -export class NpmPackagesCommandFailedError extends Schema.TaggedError<NpmPackagesCommandFailedError>()(
38 - "NpmPackagesCommandFailedError",
39 - { command: Schema.String, exitCode: Schema.Int },
40 -) {
41 - override get message(): string {
42 - return `${this.command} exited with code ${this.exitCode}.`;
43 - }
44 -}
45 -
46 -export class NpmPackagesToolMissingError extends Schema.TaggedError<NpmPackagesToolMissingError>()(
47 - "NpmPackagesToolMissingError",
48 - { tool: Schema.String, purpose: Schema.String },
49 -) {
50 - override get message(): string {
51 - return `\`${this.tool}\` is not on PATH; it is needed to ${this.purpose}.`;
52 - }
53 -}
54 -
55 -export class NpmPackagesArchivesMissingError extends Schema.TaggedError<NpmPackagesArchivesMissingError>()(
56 - "NpmPackagesArchivesMissingError",
57 - { archivesDir: Schema.String, missing: Schema.Array(Schema.String) },
58 -) {
59 - override get message(): string {
60 - 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.`;
61 - }
62 -}
63 -
64 -export class NpmPackagesArchiveLayoutError extends Schema.TaggedError<NpmPackagesArchiveLayoutError>()(
65 - "NpmPackagesArchiveLayoutError",
66 - { archive: Schema.String, detail: Schema.String },
67 -) {
68 - override get message(): string {
69 - return `${this.archive}: ${this.detail}`;
70 - }
71 -}
72 -
73 -export function npmPlatformPackageName(platformKey: CliArchivePlatformKey): string {
74 - return `${NPM_PLATFORM_PACKAGE_SCOPE}/t3-${platformKey}`;
75 -}
76 -
77 -/**
78 - * The archive's runtime `node_modules` (native addons and their loaders) ships
79 - * inside the tarball, and npm only keeps a nested tree it can account for:
80 - * anything not declared is extraneous and pruned on the next `npm install` in
81 - * that project, which then breaks the executable.
82 - */
83 -export function npmPlatformPackageManifest(
84 - platformKey: CliArchivePlatformKey,
85 - version: string,
86 - bundled: Readonly<Record<string, string>>,
87 -) {
88 - const [os, cpu] = platformKey.split("-") as [string, string];
89 - const bundleDependencies = Object.keys(bundled).sort();
90 - return {
91 - name: npmPlatformPackageName(platformKey),
92 - version,
93 - description: `T3 Code CLI executable for ${platformKey}`,
94 - license: serverPackageJson.license,
95 - repository: serverPackageJson.repository,
96 - os: [os],
97 - cpu: [cpu],
98 - files: ["t3", "t3.exe", "client", "resource-monitor", "node_modules"],
99 - preferUnplugged: true,
100 - dependencies: Object.fromEntries(bundleDependencies.map((name) => [name, bundled[name]])),
101 - bundleDependencies,
102 - };
103 -}
104 -
105 -const PackageVersion = Schema.Struct({ version: Schema.String });
106 -const decodePackageVersion = Schema.decodeUnknownEffect(Schema.fromJsonString(PackageVersion));
107 -
108 -const readBundledPackages = Effect.fn("readBundledPackages")(function* (nodeModulesDir: string) {
109 - const fs = yield* FileSystem.FileSystem;
110 - const path = yield* Path.Path;
111 - const bundled: Record<string, string> = {};
112 - const packageDirs: Array<{ readonly name: string; readonly dir: string }> = [];
113 - for (const entry of yield* fs.readDirectory(nodeModulesDir)) {
114 - if (entry.startsWith(".")) continue;
115 - const dir = path.join(nodeModulesDir, entry);
116 - if (entry.startsWith("@")) {
117 - for (const scoped of yield* fs.readDirectory(dir)) {
118 - packageDirs.push({ name: `${entry}/${scoped}`, dir: path.join(dir, scoped) });
119 - }
120 - } else {
121 - packageDirs.push({ name: entry, dir });
122 - }
123 - }
124 - for (const { name, dir } of packageDirs) {
125 - const manifest = yield* fs.readFileString(path.join(dir, "package.json"));
126 - bundled[name] = (yield* decodePackageVersion(manifest)).version;
127 - }
128 - return bundled;
129 -});
130 -
131 -/**
132 - * Without one at the package root, npm shows the first README it finds in the
133 - * tarball, which is a bundled dependency's (ffi-rs).
134 - */
135 -export function npmPlatformPackageReadme(platformKey: CliArchivePlatformKey): string {
136 - return [
137 - `# ${npmPlatformPackageName(platformKey)}`,
138 - "",
139 - `The T3 Code CLI executable for ${platformKey}. Do not install this package directly:`,
140 - `it is an optional dependency of \`${NPM_LAUNCHER_PACKAGE_NAME}\`, which picks the package for the`,
141 - "current platform and runs the executable inside it.",
142 - "",
143 - "```sh",
144 - `npx ${NPM_LAUNCHER_PACKAGE_NAME}@latest`,
145 - "```",
146 - "",
147 - "Source and documentation: https://github.com/pingdotgg/t3code",
148 - "",
149 - ].join("\n");
150 -}
151 -
152 -export function npmLauncherPackageManifest(
153 - version: string,
154 - platformKeys: ReadonlyArray<CliArchivePlatformKey>,
155 -) {
156 - return {
157 - name: NPM_LAUNCHER_PACKAGE_NAME,
158 - version,
159 - description: "T3 Code CLI. Installs the self-contained executable for this platform.",
160 - license: serverPackageJson.license,
161 - repository: serverPackageJson.repository,
162 - bin: { t3: "./bin/t3.js" },
163 - files: ["bin", "dist"],
164 - optionalDependencies: Object.fromEntries(
165 - platformKeys.map((key) => [npmPlatformPackageName(key), version]),
166 - ),
167 - };
168 -}
169 -
170 -export const NPM_LAUNCHER_SCRIPT = `#!/usr/bin/env node
171 -"use strict";
172 -const { spawnSync } = require("node:child_process");
173 -const { constants } = require("node:os");
174 -const { dirname, join } = require("node:path");
175 -
176 -const SUPPORTED = [${CLI_ARCHIVE_PLATFORM_KEYS.map((key) => `"${key}"`).join(", ")}];
177 -const key = process.platform + "-" + process.arch;
178 -
179 -let packageDir;
180 -try {
181 - packageDir = dirname(require.resolve("${NPM_PLATFORM_PACKAGE_SCOPE}/t3-" + key + "/package.json"));
182 -} catch {
183 - process.stderr.write(
184 - [
185 - "t3: no T3 Code CLI build is available for this platform (" + key + ").",
186 - "Supported platforms: " + SUPPORTED.join(", ") + ".",
187 - "If yours is listed, reinstall t3 so npm fetches its optional dependency.",
188 - "The desktop app and release archives are at https://github.com/pingdotgg/t3code/releases",
189 - "",
190 - ].join("\\n"),
191 - );
192 - process.exit(1);
193 -}
194 -
195 -const executable = join(packageDir, process.platform === "win32" ? "t3.exe" : "t3");
196 -const result = spawnSync(executable, process.argv.slice(2), { stdio: "inherit" });
197 -if (result.error) {
198 - process.stderr.write("t3: failed to start " + executable + ": " + result.error.message + "\\n");
199 - process.exit(1);
200 -}
201 -// A child killed by a signal has no status; report it the way a shell would.
202 -process.exit(result.status ?? 128 + (constants.signals[result.signal] || 1));
203 -`;
204 -
205 -const runCommand = Effect.fn("runCommand")(function* (
206 - command: ChildProcess.StandardCommand,
207 - label: string,
208 -) {
209 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
210 - const child = yield* spawner.spawn(
211 - ChildProcess.make(command.command, command.args, {
212 - ...command.options,
213 - stdout: "inherit",
214 - stderr: "inherit",
215 - }),
216 - );
217 - const exitCode = Number(yield* child.exitCode);
218 - if (exitCode !== 0) {
219 - return yield* new NpmPackagesCommandFailedError({ command: label, exitCode });
220 - }
221 -});
222 -
223 -/**
224 - * `.tar.gz` goes through tar everywhere; `.zip` through the bsdtar Windows
225 - * ships or, elsewhere, `unzip`, since GNU tar cannot read zip.
226 - */
227 -const extractArchive = Effect.fn("extractArchive")(function* (archive: string, into: string) {
228 - const fs = yield* FileSystem.FileSystem;
229 - const path = yield* Path.Path;
230 - const platform = yield* HostProcess.Platform;
231 - if (!archive.endsWith(".zip")) {
232 - yield* runCommand(ChildProcess.make("tar", ["-xf", archive, "-C", into]), "tar -xf");
233 - } else if (platform === "win32") {
234 - yield* runCommand(
235 - ChildProcess.make(windowsSystemTar(), ["-xf", archive, "-C", into]),
236 - "tar.exe -xf (zip)",
237 - );
238 - } else {
239 - if (!(yield* isCommandAvailable("unzip"))) {
240 - return yield* new NpmPackagesToolMissingError({
241 - tool: "unzip",
242 - purpose: `extract ${path.basename(archive)} (GNU tar cannot read zip)`,
243 - });
244 - }
245 - yield* runCommand(ChildProcess.make("unzip", ["-q", archive, "-d", into]), "unzip");
246 - }
247 - const entries = yield* fs.readDirectory(into);
248 - const [root] = entries;
249 - if (root === undefined || entries.length !== 1) {
250 - return yield* new NpmPackagesArchiveLayoutError({
251 - archive: path.basename(archive),
252 - detail: `expected exactly one top-level directory, found ${String(entries.length)} entries`,
253 - });
254 - }
255 - return path.join(into, root);
256 -});
257 -
258 -/** Tar to build npm tarballs with; see build-cli-archive.ts for why Windows names bsdtar by path. */
259 -const hostTar = Effect.map(HostProcess.Platform, (platform) =>
260 - platform === "win32" ? windowsSystemTar() : "tar",
261 -);
262 -
263 -const packAndPlace = Effect.fn("packAndPlace")(function* (input: {
264 - readonly stageDir: string;
265 - readonly packageDir: string;
266 - readonly tarball: string;
267 -}) {
268 - const fs = yield* FileSystem.FileSystem;
269 - yield* fs.remove(input.tarball, { force: true });
270 - yield* runCommand(
271 - ChildProcess.make(yield* hostTar, ["-czf", input.tarball, "-C", input.stageDir, "package"]),
272 - `tar (${input.tarball})`,
273 - );
274 - yield* fs.remove(input.packageDir, { recursive: true, force: true });
275 - yield* fs.rename(`${input.stageDir}/package`, input.packageDir);
276 -});
277 -
278 -export interface NpmPackageOutput {
279 - readonly name: string;
280 - readonly packageDir: string;
281 - readonly tarball: string;
282 -}
283 -
284 -const stagePlatformPackage = Effect.fn("stagePlatformPackage")(function* (input: {
285 - readonly key: CliArchivePlatformKey;
286 - readonly archive: string;
287 - readonly outputDir: string;
288 - readonly version: string;
289 -}) {
290 - const fs = yield* FileSystem.FileSystem;
291 - const path = yield* Path.Path;
292 - yield* Effect.log(`[npm-packages] Extracting ${path.basename(input.archive)}...`);
293 - const scratch = yield* fs.makeTempDirectoryScoped({
294 - directory: input.outputDir,
295 - prefix: ".extract-",
296 - });
297 - const extractDir = path.join(scratch, "extract");
298 - yield* fs.makeDirectory(extractDir);
299 - const contentDir = yield* extractArchive(input.archive, extractDir);
300 - const executableName = input.key.startsWith("win32") ? "t3.exe" : "t3";
301 - const executable = path.join(contentDir, executableName);
302 - if (!(yield* fs.exists(executable))) {
303 - return yield* new NpmPackagesArchiveLayoutError({
304 - archive: path.basename(input.archive),
305 - detail: `missing ${executableName} at the archive root`,
306 - });
307 - }
308 - // The tarball carries the on-disk mode, so the bit must be set before packing.
309 - if (executableName === "t3") {
310 - yield* fs.chmod(executable, 0o755);
311 - }
312 - const bundled = yield* readBundledPackages(path.join(contentDir, "node_modules"));
313 - yield* fs.writeFileString(
314 - path.join(contentDir, "package.json"),
315 - `${yield* encodePackageJson(npmPlatformPackageManifest(input.key, input.version, bundled))}\n`,
316 - );
317 - yield* fs.writeFileString(
318 - path.join(contentDir, "README.md"),
319 - npmPlatformPackageReadme(input.key),
320 - );
321 - // npm tarballs root everything under `package/`.
322 - yield* fs.rename(contentDir, path.join(scratch, "package"));
323 - const name = npmPlatformPackageName(input.key);
324 - const output: NpmPackageOutput = {
325 - name,
326 - packageDir: path.join(input.outputDir, name),
327 - tarball: path.join(input.outputDir, `${name}.tgz`),
328 - };
329 - yield* packAndPlace({ stageDir: scratch, ...output });
330 - return output;
331 -}, Effect.scoped);
332 -
333 -const stageLauncherPackage = Effect.fn("stageLauncherPackage")(function* (input: {
334 - readonly outputDir: string;
335 - readonly version: string;
336 - readonly platformKeys: ReadonlyArray<CliArchivePlatformKey>;
337 -}) {
338 - const fs = yield* FileSystem.FileSystem;
339 - const path = yield* Path.Path;
340 - const scratch = yield* fs.makeTempDirectoryScoped({
341 - directory: input.outputDir,
342 - prefix: ".launcher-",
343 - });
344 - const stageDir = path.join(scratch, "package");
345 - yield* fs.makeDirectory(path.join(stageDir, "bin"), { recursive: true });
346 - yield* fs.writeFileString(
347 - path.join(stageDir, "package.json"),
348 - `${yield* encodePackageJson(npmLauncherPackageManifest(input.version, input.platformKeys))}\n`,
349 - );
350 - const launcherScript = path.join(stageDir, "bin/t3.js");
351 - yield* fs.writeFileString(launcherScript, NPM_LAUNCHER_SCRIPT);
352 - yield* fs.chmod(launcherScript, 0o755);
353 - // Older service updaters and launchers run this exact path with Node.
354 - // Keep it in the package so they can preflight and start the new executable.
355 - yield* fs.makeDirectory(path.join(stageDir, "dist"));
356 - yield* fs.writeFileString(path.join(stageDir, "dist/bin.mjs"), legacyCliLauncherScript());
357 - const readme = yield* path.fromFileUrl(new URL("../apps/server/README.md", import.meta.url));
358 - if (yield* fs.exists(readme)) {
359 - yield* fs.copyFile(readme, path.join(stageDir, "README.md"));
360 - }
361 - const output: NpmPackageOutput = {
362 - name: NPM_LAUNCHER_PACKAGE_NAME,
363 - packageDir: path.join(input.outputDir, NPM_LAUNCHER_PACKAGE_NAME),
364 - tarball: path.join(input.outputDir, `${NPM_LAUNCHER_PACKAGE_NAME}.tgz`),
365 - };
366 - yield* packAndPlace({ stageDir: scratch, ...output });
367 - return output;
368 -}, Effect.scoped);
369 -
370 -export const buildNpmPlatformPackages = Effect.fn("buildNpmPlatformPackages")(function* (input: {
371 - readonly archivesDir: string;
372 - readonly version: string;
373 - readonly outputDir: string;
374 - readonly allowMissing: boolean;
375 -}) {
376 - const fs = yield* FileSystem.FileSystem;
377 - const path = yield* Path.Path;
378 -
379 - const present = yield* fs.readDirectory(input.archivesDir);
380 - const archives = CLI_ARCHIVE_PLATFORM_KEYS.flatMap((key) => {
381 - const fileName = cliArchiveFileName(input.version, key);
382 - return present.includes(fileName)
383 - ? [{ key, archive: path.join(input.archivesDir, fileName) }]
384 - : [];
385 - });
386 - const missing = CLI_ARCHIVE_PLATFORM_KEYS.filter(
387 - (key) => !archives.some((entry) => entry.key === key),
388 - );
389 - if (missing.length > 0 && (!input.allowMissing || archives.length === 0)) {
390 - return yield* new NpmPackagesArchivesMissingError({ archivesDir: input.archivesDir, missing });
391 - }
392 -
393 - yield* fs.makeDirectory(path.join(input.outputDir, NPM_PLATFORM_PACKAGE_SCOPE), {
394 - recursive: true,
395 - });
396 - const platformOutputs = yield* Effect.forEach(
397 - archives,
398 - ({ key, archive }) =>
399 - stagePlatformPackage({ key, archive, outputDir: input.outputDir, version: input.version }),
400 - { concurrency: "unbounded" },
401 - );
402 - const outputs = [
403 - ...platformOutputs,
404 - yield* stageLauncherPackage({
405 - outputDir: input.outputDir,
406 - version: input.version,
407 - platformKeys: archives.map((entry) => entry.key),
408 - }),
409 - ];
410 -
411 - for (const output of outputs) {
412 - yield* Effect.log(`[npm-packages] Wrote ${output.packageDir} and ${output.tarball}`);
413 - }
414 - if (missing.length > 0) {
415 - yield* Effect.logWarning(
416 - `[npm-packages] Launcher omits ${missing.join(", ")} (--allow-missing).`,
417 - );
418 - }
419 - return outputs;
420 -});
421 -
422 -const command = Command.make(
423 - "build-npm-platform-packages",
424 - {
425 - archivesDir: Flag.String("archives-dir").pipe(
426 - Flag.withDescription("Directory holding the release's t3-<version>-<platform> archives."),
427 - ),
428 - version: Flag.String("version").pipe(
429 - Flag.withDescription(
430 - "Exact release version; selects the archives and versions the packages.",
431 - ),
432 - ),
433 - outputDir: Flag.String("output-dir").pipe(Flag.withDefault("npm-packages")),
434 - allowMissing: Flag.Boolean("allow-missing").pipe(
435 - Flag.withDefault(false),
436 - Flag.withDescription("Build a launcher that lists only the platforms present."),
437 - ),
438 - },
439 - buildNpmPlatformPackages,
440 -).pipe(
441 - Command.withDescription(
442 - "Build the t3 launcher and @t3code/t3-<platform> npm packages from CLI release archives.",
443 - ),
444 -);
445 -
446 -if (import.meta.main) {
447 - Command.run(command, { version: "0.0.0" }).pipe(
448 - Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
449 - NodeRuntime.runMain,
450 - );
451 -}
scripts/npm-launcher/bin.mjs new
+2
@@ -0,0 +1,2 @@
1 +// Background services installed before 0.0.41 start the npm package from this path.
2 +import "../bin/t3.mjs";
scripts/npm-launcher/t3.mjs new
+176
@@ -0,0 +1,176 @@
1 +#!/usr/bin/env node
2 +// The `t3` npm package. Downloads this version's CLI archive from the GitHub
3 +// Release into <T3 home>/runtime/versions/<version> (the folder the install
4 +// scripts and `t3 update` use), verifies it against the release's SHA256SUMS,
5 +// then runs it. `dist/bin.mjs` re-enters here for background services
6 +// installed before 0.0.41, which start the npm package with Node and talk to
7 +// it over an IPC channel.
8 +import { spawn, spawnSync } from "node:child_process";
9 +import crypto from "node:crypto";
10 +import fs from "node:fs";
11 +import os from "node:os";
12 +import path from "node:path";
13 +
14 +const { version } = JSON.parse(
15 + fs.readFileSync(path.join(import.meta.dirname, "../package.json"), "utf8"),
16 +);
17 +
18 +const SUPPORTED = ["darwin-arm64", "linux-arm64", "linux-x64", "win32-arm64", "win32-x64"];
19 +
20 +function t3Home() {
21 + const raw = (process.env.T3CODE_HOME || "").trim();
22 + if (raw === "") return path.join(os.homedir(), ".t3");
23 + if (raw === "~") return os.homedir();
24 + if (raw.startsWith("~/") || raw.startsWith("~\\")) return path.join(os.homedir(), raw.slice(2));
25 + return path.resolve(raw);
26 +}
27 +
28 +async function get(url) {
29 + const response = await fetch(url);
30 + if (response.status === 404) {
31 + throw new Error(
32 + `${url} does not exist yet. If ${version} was just released, try again in a few minutes.`,
33 + );
34 + }
35 + if (!response.ok) throw new Error(`GET ${url} returned HTTP ${response.status}`);
36 + return response;
37 +}
38 +
39 +/** Downloads `url` to `file` and returns its sha256, showing progress on a terminal. */
40 +async function download(url, file) {
41 + const response = await get(url);
42 + const total = Number(response.headers.get("content-length")) || 0;
43 + const hash = crypto.createHash("sha256");
44 + const out = fs.openSync(file, "w");
45 + const tty = process.stderr.isTTY;
46 + let received = 0;
47 + let shown = -1;
48 + try {
49 + for await (const chunk of response.body) {
50 + hash.update(chunk);
51 + fs.writeSync(out, chunk);
52 + received += chunk.byteLength;
53 + // Redraw once per percent (or per MB without a length), not per chunk.
54 + const step = total ? Math.floor((received * 100) / total) : Math.floor(received / 1048576);
55 + if (tty && step !== shown) {
56 + shown = step;
57 + const percent = total ? ` ${step}%` : "";
58 + process.stderr.write(
59 + `\r\x1b[2Kt3: downloading T3 Code ${version}${percent} (${(received / 1048576).toFixed(1)} MB)`,
60 + );
61 + }
62 + }
63 + } finally {
64 + fs.closeSync(out);
65 + if (tty) process.stderr.write("\r\x1b[2K");
66 + }
67 + return hash.digest("hex");
68 +}
69 +
70 +async function install(dir, key) {
71 + const archive = `t3-${version}-${key}.${process.platform === "win32" ? "zip" : "tar.gz"}`;
72 + const base = (
73 + process.env.T3CODE_RELEASE_BASE_URL || "https://github.com/pingdotgg/t3code/releases/download"
74 + ).replace(/\/+$/, "");
75 + const sums = await (await get(`${base}/v${version}/SHA256SUMS`)).text();
76 + const expected = /^([0-9a-f]{64})\s+\*?(.+)$/im;
77 + const line = sums
78 + .split(/\r?\n/)
79 + .map((l) => expected.exec(l.trim()))
80 + .find((m) => m && m[2] === archive);
81 + if (!line) throw new Error(`${archive} is not listed in the release's SHA256SUMS`);
82 +
83 + // Extract beside the final folder and rename it into place, so an
84 + // interrupted download never leaves a half-installed version behind.
85 + fs.mkdirSync(path.dirname(dir), { recursive: true });
86 + const staging = fs.mkdtempSync(`${dir}.staging-`);
87 + try {
88 + const file = path.join(staging, archive);
89 + if ((await download(`${base}/v${version}/${archive}`, file)) !== line[1].toLowerCase()) {
90 + throw new Error(`checksum mismatch for ${archive}`);
91 + }
92 + // Windows' own tar.exe reads zip; a Git-for-Windows tar on PATH cannot.
93 + const tar =
94 + process.platform === "win32" ? `${process.env.SystemRoot}\\System32\\tar.exe` : "tar";
95 + const extract = spawnSync(tar, ["-xf", file, "-C", staging, "--strip-components=1"], {
96 + stdio: "inherit",
97 + });
98 + if (extract.status !== 0) throw new Error(`could not extract ${archive}`);
99 + fs.rmSync(file);
100 + fs.writeFileSync(path.join(staging, ".install-complete"), `${version}\n`);
101 + publish(staging, dir);
102 + } finally {
103 + fs.rmSync(staging, { recursive: true, force: true });
104 + }
105 +}
106 +
107 +const isComplete = (dir) => {
108 + try {
109 + return fs.readFileSync(path.join(dir, ".install-complete"), "utf8").trim() === version;
110 + } catch {
111 + return false;
112 + }
113 +};
114 +
115 +/**
116 + * Moves a finished staging folder to `dir`. Rename never replaces an existing
117 + * folder, so a complete install another launcher (or `t3 update`) published
118 + * first is kept, never deleted from under a running process. Only a folder
119 + * without the completion marker, left by an interrupted older installer, is
120 + * cleared before trying again.
121 + */
122 +function publish(staging, dir) {
123 + try {
124 + fs.renameSync(staging, dir);
125 + } catch (error) {
126 + if (isComplete(dir)) return;
127 + if (!fs.existsSync(dir)) throw error;
128 + fs.rmSync(dir, { recursive: true, force: true });
129 + fs.renameSync(staging, dir);
130 + }
131 +}
132 +
133 +async function main() {
134 + const key = `${process.platform}-${process.arch}`;
135 + if (!SUPPORTED.includes(key)) {
136 + throw new Error(
137 + `no T3 Code CLI build is available for ${key} (supported: ${SUPPORTED.join(", ")}).\n` +
138 + "The desktop app is at https://github.com/pingdotgg/t3code/releases",
139 + );
140 + }
141 + const dir = path.join(t3Home(), "runtime", "versions", version);
142 + if (!isComplete(dir)) await install(dir, key);
143 +
144 + // A service launcher talks to its server over IPC; pass that channel and
145 + // signals through. In a terminal, Ctrl-C already reaches the child directly,
146 + // so forwarding SIGINT too would deliver it twice.
147 + const ipc = process.send !== undefined;
148 + const child = spawn(
149 + path.join(dir, process.platform === "win32" ? "t3.exe" : "t3"),
150 + process.argv.slice(2),
151 + {
152 + stdio: ipc ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
153 + // The executable lives in the T3 home, so this is how it knows npm launched it.
154 + env: { ...process.env, T3CODE_NPM_LAUNCHER_PATH: import.meta.filename },
155 + },
156 + );
157 + if (ipc) {
158 + process.on("message", (message) => child.connected && child.send(message));
159 + child.on("message", (message) => process.connected && process.send(message));
160 + process.on("disconnect", () => child.connected && child.disconnect());
161 + }
162 + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
163 + process.on(signal, () => (ipc || signal !== "SIGINT") && child.kill(signal));
164 + }
165 + child.on("error", (error) => fail(error));
166 + child.on("exit", (code, signal) =>
167 + process.exit(code ?? 128 + (os.constants.signals[signal] || 1)),
168 + );
169 +}
170 +
171 +function fail(error) {
172 + process.stderr.write(`t3: ${error.message}\n`);
173 + process.exit(1);
174 +}
175 +
176 +await main().catch(fail);
vite.config.ts
+8
@@ -214,6 +214,14 @@ export default defineConfig({
214 files: ["packages/shared/src/HostProcess.ts"],
215 rules: { "t3code/no-global-process-runtime": "off" },
216 },
217 + {
218 + // The `t3` npm launcher is published as plain, dependency-free Node.
219 + files: ["scripts/npm-launcher/**"],
220 + rules: {
221 + "t3code/no-global-process-runtime": "off",
222 + "t3code/namespace-node-imports": "off",
223 + },
224 + },
225 {
226 files: ["apps/server/src/mcp/McpHttpServer.ts"],
227 rules: { "t3code/no-raw-mcp-registration": "off" },