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

AgentDeviceTarget.ts

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