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

AgentDeviceTarget.ts

59 lines2.2 KB

1import * as Crypto from "effect/Crypto";
2import * as Effect from "effect/Effect";
3import * as Hex from "effect/encoding/Hex";
4import * as Schema from "effect/Schema";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7​
8import type { AgentDaemonEndpoint } from "./DeviceHost.ts";
9​
10const encodeEndpoint = Schema.encodeEffect(
11 Schema.fromJsonString(
12 Schema.Struct({ daemonBaseUrl: Schema.String, daemonAuthToken: Schema.String }),
13 ),
14);
15​
16const key = Effect.fn("AgentDeviceTarget.key")(function* (value: string) {
17 const crypto = yield* Crypto.Crypto;
18 const digest = yield* crypto
19 .digest("SHA-256", new TextEncoder().encode(value))
20 .pipe(Effect.orDie);
21 return Hex.encode(digest).slice(0, 24);
22});
23​
24/**
25 * A stable file per host lets forwarded endpoints change without retargeting
26 * other commands. Hosts with a daemon per device get a file per device.
27 */
28export const agentDeviceConfigPath = (
29 stateDir: string,
30 hostId: string,
31 path: Path.Path,
32 deviceId?: string,
33) =>
34 key(deviceId === undefined ? hostId : JSON.stringify([hostId, deviceId])).pipe(
35 Effect.map((hash) => path.join(stateDir, "device", "hosts", `${hash}.json`)),
36 );
37​
38export const agentDeviceSession = (threadId: string, hostId: string, deviceId: string) =>
39 key(JSON.stringify([threadId, hostId, deviceId])).pipe(Effect.map((hash) => `t3-${hash}`));
40​
41export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")(function* (
42 file: string,
43 endpoint: AgentDaemonEndpoint,
44) {
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
48 const content = yield* encodeEndpoint({
49 daemonBaseUrl: endpoint.baseUrl,
50 daemonAuthToken: endpoint.token,
51 });
52 if ((yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => ""))) === content) return;
53 const temporary = yield* fs.makeTempFile({ directory: path.dirname(file), prefix: ".endpoint-" });
54 yield* Effect.gen(function* () {
55 yield* fs.chmod(temporary, 0o600);
56 yield* fs.writeFileString(temporary, content);
57 yield* fs.rename(temporary, file);
58 }).pipe(Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)));
59});