Open History to see the last commit
1// @effect-diagnostics preferSchemaOverJson:off - JSON string literals embed paths safely into generated JavaScript.
2/**
3 * A directory holding an `agent-device` launcher that runs the pinned install
4 * with the server's Node. Prepended to provider subprocess PATHs so the agent
5 * types `agent-device …` and gets the version the injected instructions were
6 * written for, regardless of what is or is not globally installed.
7 */
8import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Path from "effect/Path";
12
13const SHIM_DIR = "device/bin";
14
15export const ensureAgentDeviceShim = Effect.fn("AgentDeviceShim.ensure")(function* (input: {
16 readonly entryPath: string;
17 readonly stateDir: string;
18}) {
19 const { entryPath } = input;
20 const fs = yield* FileSystem.FileSystem;
21 const path = yield* Path.Path;
22 const platform = yield* HostProcessPlatform;
23 const shimDir = path.join(input.stateDir, SHIM_DIR);
24 yield* fs.makeDirectory(shimDir, { recursive: true });
25 const node = process.execPath;
26 const launcherPath = path.join(shimDir, "agent-device-launcher.mjs");
27 yield* fs.writeFileString(
28 launcherPath,
29 `import { spawn } from "node:child_process";
30const args = process.argv.slice(2);
31const informational = args.length === 1 && ["help", "--help", "-h", "--version", "version"].includes(args[0]);
32const hasValue = flag => { const index = args.indexOf(flag); return index >= 0 && !!args[index + 1] && !args[index + 1].startsWith("--"); };
33if (!informational && !(hasValue("--config") && hasValue("--session"))) {
34 console.error("Call device_open first and include its --config and --session flags.");
35 process.exit(1);
36}
37const env = { ...process.env };
38delete env.AGENT_DEVICE_DAEMON_BASE_URL;
39delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
40delete env.AGENT_DEVICE_CONFIG;
41const child = spawn(${JSON.stringify(node)}, [${JSON.stringify(entryPath)}, ...args], { stdio: "inherit", env });
42child.on("error", error => { console.error(error.message); process.exitCode = 1; });
43child.on("exit", code => { process.exitCode = code ?? 1; });
44`,
45 );
46 if (platform === "win32") {
47 const script = `@echo off\r\n"${node}" "${launcherPath}" %*\r\n`;
48 yield* fs.writeFileString(path.join(shimDir, "agent-device.cmd"), script);
49 } else {
50 const command = [node, launcherPath]
51 .map((value) => "'" + value.replaceAll("'", "'\"'\"'") + "'")
52 .join(" ");
53 const script = `#!/bin/sh\nexec ${command} "$@"\n`;
54 const shimPath = path.join(shimDir, "agent-device");
55 yield* fs.writeFileString(shimPath, script);
56 yield* fs.chmod(shimPath, 0o755);
57 }
58 return shimDir;
59});