The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import * as Context from "effect/Context"; |
| 2 | import * as Clock from "effect/Clock"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as FileSystem from "effect/FileSystem"; |
| 5 | import * as Layer from "effect/Layer"; |
| 6 | import * as LogLevel from "effect/LogLevel"; |
| 7 | import * as Path from "effect/Path"; |
| 8 | import type * as Redacted from "effect/Redacted"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | |
| 11 | import type { OtlpEndpointSource } from "@t3tools/contracts"; |
| 12 | import { sweepStalePendingAttachments } from "./attachmentStore.ts"; |
| 13 | import { markNoCopyOnWrite } from "./noCopyOnWrite.ts"; |
| 14 | import { |
| 15 | DEFAULT_SIGNAL_EXPORT, |
| 16 | nodeProcessRuntimeAttributes, |
| 17 | processServiceInstanceId, |
| 18 | type SignalExport, |
| 19 | } from "@t3tools/shared/observability"; |
| 20 | import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; |
| 21 | import { type ReleaseChannel, releaseResourceAttributes } from "@t3tools/shared/releaseResource"; |
| 22 | import packageJson from "../package.json" with { type: "json" }; |
| 23 | |
| 24 | // Official release workflows set this telemetry channel; other builds report dev. |
| 25 | // Unlike __T3CODE_BUILD_CHANNEL__, this is not the sign-in page's latest/nightly channel. |
| 26 | declare const __T3CODE_TELEMETRY_CHANNEL__: ReleaseChannel | undefined; |
| 27 | export const telemetryChannel: ReleaseChannel = |
| 28 | typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__; |
| 29 | |
| 30 | export const DEFAULT_PORT = 3773; |
| 31 | |
| 32 | export const RuntimeMode = Schema.Literals(["web", "desktop"]); |
| 33 | export type RuntimeMode = typeof RuntimeMode.Type; |
| 34 | |
| 35 | export const StartupPresentation = Schema.Literals(["browser", "headless"]); |
| 36 | export type StartupPresentation = typeof StartupPresentation.Type; |
| 37 | |
| 38 | export interface ServerDerivedPaths { |
| 39 | readonly stateDir: string; |
| 40 | readonly dbPath: string; |
| 41 | readonly keybindingsConfigPath: string; |
| 42 | readonly settingsPath: string; |
| 43 | readonly environmentThemesDir: string; |
| 44 | readonly providerStatusCacheDir: string; |
| 45 | readonly worktreesDir: string; |
| 46 | readonly worktreeCheckoutCacheDir: string; |
| 47 | readonly attachmentsDir: string; |
| 48 | readonly browserArtifactsDir: string; |
| 49 | readonly logsDir: string; |
| 50 | readonly serverTracePath: string; |
| 51 | readonly providerLogsDir: string; |
| 52 | readonly providerEventLogPath: string; |
| 53 | readonly terminalLogsDir: string; |
| 54 | readonly anonymousIdPath: string; |
| 55 | readonly environmentIdPath: string; |
| 56 | readonly serverRuntimeStatePath: string; |
| 57 | readonly secretsDir: string; |
| 58 | } |
| 59 | |
| 60 | export interface DeriveServerPathsOptions { |
| 61 | readonly baseDirIsExplicit?: boolean; |
| 62 | } |
| 63 | |
| 64 | export class ServerConfig extends Context.Service< |
| 65 | ServerConfig, |
| 66 | ServerDerivedPaths & { |
| 67 | readonly logLevel: LogLevel.LogLevel; |
| 68 | readonly traceMinLevel: LogLevel.LogLevel; |
| 69 | readonly traceTimingEnabled: boolean; |
| 70 | readonly traceBatchWindowMs: number; |
| 71 | readonly traceMaxBytes: number; |
| 72 | readonly traceMaxFiles: number; |
| 73 | readonly otlpTracesUrl: string | undefined; |
| 74 | readonly otlpMetricsUrl: string | undefined; |
| 75 | readonly otlpLogsUrl: string | undefined; |
| 76 | readonly otlpTracesExport: SignalExport; |
| 77 | readonly otlpMetricsExport: SignalExport; |
| 78 | readonly otlpLogsExport: SignalExport; |
| 79 | readonly otlpTracesSource?: OtlpEndpointSource; |
| 80 | readonly otlpTracesVariable?: string; |
| 81 | readonly otlpMetricsSource?: OtlpEndpointSource; |
| 82 | readonly otlpMetricsVariable?: string; |
| 83 | readonly otlpLogsSource?: OtlpEndpointSource; |
| 84 | readonly otlpLogsVariable?: string; |
| 85 | readonly otelEnvironment: OtelEnvironment.OtelEnvironment; |
| 86 | readonly mode: RuntimeMode; |
| 87 | readonly port: number; |
| 88 | readonly host: string | undefined; |
| 89 | /** Set when the host was defaulted to a private-network listener for the service. */ |
| 90 | readonly privateNetworkOnly?: boolean | undefined; |
| 91 | readonly cwd: string; |
| 92 | readonly baseDir: string; |
| 93 | readonly staticDir: string | undefined; |
| 94 | readonly devUrl: URL | undefined; |
| 95 | readonly devAuthToken?: Redacted.Redacted<string> | undefined; |
| 96 | readonly devAllowedOrigins: ReadonlyArray<string>; |
| 97 | readonly noBrowser: boolean; |
| 98 | readonly startupPresentation: StartupPresentation; |
| 99 | readonly desktopBootstrapToken: string | undefined; |
| 100 | readonly desktopBootstrapSecret?: string | undefined; |
| 101 | readonly shellEnvironmentPrepared?: boolean | undefined; |
| 102 | readonly desktopTelemetryFd?: number | undefined; |
| 103 | readonly desktopTelemetryControlFd?: number | undefined; |
| 104 | readonly desktopAppUpdate?: boolean | undefined; |
| 105 | readonly desktopBrowserFd?: number | undefined; |
| 106 | readonly desktopBrowserControlFd?: number | undefined; |
| 107 | readonly resourceMonitorPath?: string | undefined; |
| 108 | readonly autoBootstrapProjectFromCwd: boolean; |
| 109 | readonly logWebSocketEvents: boolean; |
| 110 | readonly tailscaleServeEnabled: boolean; |
| 111 | readonly tailscaleServePort: number; |
| 112 | } |
| 113 | >()("t3/config/ServerConfig") { |
| 114 | static readonly layerTest = ( |
| 115 | cwd: string, |
| 116 | baseDirOrPrefix: string | { readonly prefix: string }, |
| 117 | ) => layerTest(cwd, baseDirOrPrefix); |
| 118 | } |
| 119 | |
| 120 | export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config); |
| 121 | |
| 122 | export const otlpResource = ( |
| 123 | config: Pick<ServerConfig["Service"], "mode" | "otelEnvironment">, |
| 124 | hostName: string, |
| 125 | ) => ({ |
| 126 | serviceName: "t3code-server", |
| 127 | serviceVersion: packageJson.version, |
| 128 | attributes: { |
| 129 | "service.namespace": "t3code", |
| 130 | "service.runtime": "t3-server", |
| 131 | "t3code.server.managed_by": config.mode === "desktop" ? "desktop" : "standalone", |
| 132 | "service.instance.id": processServiceInstanceId(config.otelEnvironment.resourceAttributes), |
| 133 | ...releaseResourceAttributes(telemetryChannel, config.otelEnvironment.resourceAttributes), |
| 134 | "host.name": config.otelEnvironment.resourceAttributes["host.name"] || hostName, |
| 135 | ...nodeProcessRuntimeAttributes(), |
| 136 | }, |
| 137 | }); |
| 138 | |
| 139 | export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config)); |
| 140 | |
| 141 | export const deriveServerPaths = Effect.fn(function* ( |
| 142 | baseDir: ServerConfig["Service"]["baseDir"], |
| 143 | devUrl: ServerConfig["Service"]["devUrl"], |
| 144 | options: DeriveServerPathsOptions = {}, |
| 145 | ): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> { |
| 146 | const { join } = yield* Path.Path; |
| 147 | const stateDir = join( |
| 148 | baseDir, |
| 149 | devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata", |
| 150 | ); |
| 151 | const dbPath = join(stateDir, "statev2.sqlite"); |
| 152 | const attachmentsDir = join(stateDir, "attachments"); |
| 153 | const logsDir = join(stateDir, "logs"); |
| 154 | const providerLogsDir = join(logsDir, "provider"); |
| 155 | const providerStatusCacheDir = join(baseDir, "caches"); |
| 156 | return { |
| 157 | stateDir, |
| 158 | dbPath, |
| 159 | keybindingsConfigPath: join(stateDir, "keybindings.json"), |
| 160 | settingsPath: join(stateDir, "settings.json"), |
| 161 | environmentThemesDir: join(stateDir, "themes"), |
| 162 | providerStatusCacheDir, |
| 163 | worktreesDir: join(baseDir, "worktrees"), |
| 164 | worktreeCheckoutCacheDir: join(providerStatusCacheDir, "worktree-checkouts"), |
| 165 | attachmentsDir, |
| 166 | browserArtifactsDir: join(stateDir, "browser-artifacts"), |
| 167 | logsDir, |
| 168 | serverTracePath: join(logsDir, "server.trace.ndjson"), |
| 169 | providerLogsDir, |
| 170 | providerEventLogPath: join(providerLogsDir, "events.log"), |
| 171 | terminalLogsDir: join(logsDir, "terminals"), |
| 172 | anonymousIdPath: join(stateDir, "anonymous-id"), |
| 173 | environmentIdPath: join(stateDir, "environment-id"), |
| 174 | serverRuntimeStatePath: join(stateDir, "server-runtime.json"), |
| 175 | secretsDir: join(stateDir, "secrets"), |
| 176 | }; |
| 177 | }); |
| 178 | |
| 179 | export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) { |
| 180 | const fs = yield* FileSystem.FileSystem; |
| 181 | const path = yield* Path.Path; |
| 182 | |
| 183 | yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true }); |
| 184 | // Only before the database exists: a No_COW WAL beside an existing copy-on-write database |
| 185 | // could not be reflinked into one backup folder with it. When unsure, leave the folder as is. |
| 186 | if (!(yield* fs.exists(derivedPaths.dbPath).pipe(Effect.orElseSucceed(() => true)))) { |
| 187 | yield* Effect.promise(() => markNoCopyOnWrite(derivedPaths.stateDir)); |
| 188 | } |
| 189 | yield* Effect.all( |
| 190 | [ |
| 191 | fs.makeDirectory(derivedPaths.logsDir, { recursive: true }), |
| 192 | fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }), |
| 193 | fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }), |
| 194 | fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }), |
| 195 | fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }), |
| 196 | fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }), |
| 197 | fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }), |
| 198 | fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }), |
| 199 | fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }), |
| 200 | fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }), |
| 201 | ], |
| 202 | { concurrency: "unbounded" }, |
| 203 | ); |
| 204 | // Logs, traces and the database are written with the process umask; keep them owner-only. |
| 205 | yield* fs |
| 206 | .chmod(derivedPaths.stateDir, 0o700) |
| 207 | .pipe( |
| 208 | Effect.catch((cause) => |
| 209 | Effect.logWarning("Could not restrict state directory permissions.", { cause }), |
| 210 | ), |
| 211 | ); |
| 212 | |
| 213 | const swept = sweepStalePendingAttachments({ |
| 214 | attachmentsDir: derivedPaths.attachmentsDir, |
| 215 | nowMs: yield* Clock.currentTimeMillis, |
| 216 | }); |
| 217 | if (swept.deleted > 0) { |
| 218 | yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted }); |
| 219 | } |
| 220 | }); |
| 221 | |
| 222 | const makeTest = Effect.fn("ServerConfig.makeTest")(function* ( |
| 223 | cwd: string, |
| 224 | baseDirOrPrefix: string | { readonly prefix: string }, |
| 225 | ) { |
| 226 | const devUrl = undefined; |
| 227 | const fs = yield* FileSystem.FileSystem; |
| 228 | const baseDir = |
| 229 | typeof baseDirOrPrefix === "string" |
| 230 | ? baseDirOrPrefix |
| 231 | : // macOS temp dirs live under the /var -> /private/var symlink; storage cleanup's |
| 232 | // symlink guards compare resolved paths, so generated test dirs must be real paths. |
| 233 | yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix })); |
| 234 | const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); |
| 235 | yield* ensureServerDirectories(derivedPaths); |
| 236 | |
| 237 | return ServerConfig.of({ |
| 238 | logLevel: "Error", |
| 239 | traceMinLevel: "Info", |
| 240 | traceTimingEnabled: true, |
| 241 | traceBatchWindowMs: 200, |
| 242 | traceMaxBytes: 10 * 1024 * 1024, |
| 243 | traceMaxFiles: 10, |
| 244 | otlpTracesUrl: undefined, |
| 245 | otlpMetricsUrl: undefined, |
| 246 | otlpLogsUrl: undefined, |
| 247 | otlpTracesExport: DEFAULT_SIGNAL_EXPORT, |
| 248 | otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, |
| 249 | otlpLogsExport: DEFAULT_SIGNAL_EXPORT, |
| 250 | otelEnvironment: OtelEnvironment.none, |
| 251 | cwd, |
| 252 | baseDir, |
| 253 | ...derivedPaths, |
| 254 | mode: "web", |
| 255 | autoBootstrapProjectFromCwd: false, |
| 256 | logWebSocketEvents: false, |
| 257 | tailscaleServeEnabled: false, |
| 258 | tailscaleServePort: 443, |
| 259 | port: 0, |
| 260 | host: undefined, |
| 261 | desktopBootstrapToken: undefined, |
| 262 | desktopTelemetryFd: undefined, |
| 263 | desktopTelemetryControlFd: undefined, |
| 264 | desktopBrowserFd: undefined, |
| 265 | desktopBrowserControlFd: undefined, |
| 266 | resourceMonitorPath: undefined, |
| 267 | staticDir: undefined, |
| 268 | devUrl, |
| 269 | devAllowedOrigins: [], |
| 270 | noBrowser: false, |
| 271 | startupPresentation: "browser", |
| 272 | }); |
| 273 | }); |
| 274 | |
| 275 | export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) => |
| 276 | Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix)); |
| 277 | |
| 278 | export const resolveStaticDir = Effect.fn(function* () { |
| 279 | const { join, resolve } = yield* Path.Path; |
| 280 | const { exists } = yield* FileSystem.FileSystem; |
| 281 | const bundledClient = resolve(join(import.meta.dirname, "client")); |
| 282 | const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe( |
| 283 | Effect.orElseSucceed(() => false), |
| 284 | ); |
| 285 | if (bundledStat) { |
| 286 | return bundledClient; |
| 287 | } |
| 288 | |
| 289 | const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist")); |
| 290 | const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe( |
| 291 | Effect.orElseSucceed(() => false), |
| 292 | ); |
| 293 | if (monorepoStat) { |
| 294 | return monorepoClient; |
| 295 | } |
| 296 | return undefined; |
| 297 | }); |