Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentDeviceTarget.ts

43 lines1.8 KB

1import * as NodeCrypto from "node:crypto";
2import * as Schema from "effect/Schema";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6​
7import type { AgentDeviceEndpoint } from "./DeviceHost.ts";
8​
9const encodeEndpoint = Schema.encodeEffect(
10 Schema.fromJsonString(
11 Schema.Struct({ daemonBaseUrl: Schema.String, daemonAuthToken: Schema.String }),
12 ),
13);
14​
15const key = (value: string) =>
16 NodeCrypto.createHash("sha256").update(value).digest("hex").slice(0, 24);
17​
18/** A stable file per host lets forwarded endpoints change without retargeting other commands. */
19export const agentDeviceConfigPath = (stateDir: string, hostId: string, path: Path.Path) =>
20 path.join(stateDir, "device", "hosts", `${key(hostId)}.json`);
21​
22export const agentDeviceSession = (threadId: string, hostId: string, deviceId: string) =>
23 `t3-${key(JSON.stringify([threadId, hostId, deviceId]))}`;
24​
25export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")(function* (
26 file: string,
27 endpoint: AgentDeviceEndpoint,
28) {
29 const fs = yield* FileSystem.FileSystem;
30 const path = yield* Path.Path;
31 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
32 const content = yield* encodeEndpoint({
33 daemonBaseUrl: endpoint.baseUrl,
34 daemonAuthToken: endpoint.token,
35 });
36 if ((yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => ""))) === content) return;
37 const temporary = yield* fs.makeTempFile({ directory: path.dirname(file), prefix: ".endpoint-" });
38 yield* Effect.gen(function* () {
39 yield* fs.chmod(temporary, 0o600);
40 yield* fs.writeFileString(temporary, content);
41 yield* fs.rename(temporary, file);
42 }).pipe(Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)));
43});