import { Context, Effect, FileSystem, Layer, Option } from "effect"; import { ChildProcessSpawner } from "effect/process"; import { AGENT_PROGRAMS } from "./internal/agentSession.js"; import { readEnv } from "./internal/envRecord.js"; import type { ProcessEntry } from "./internal/processTable.js"; import { findAncestor, procTable, psTable } from "./internal/processTable.js"; import type { AgentHost } from "./RuntimeEnv.js"; import { CurrentRuntimeEnv } from "./RuntimeEnv.js"; /** * How {@link InnermostAgent} decided: `environment` when the environment alone settles it (one agent host, or a * process table it could not read), `process-tree` when it found the host among the process's ancestors. * * @public */ export type InnermostAgentMethod = "environment" | "process-tree"; /** * The agent host nearest the running process, with how it was decided. * * @public */ export interface InnermostAgentResult { /** The host, one of `RuntimeEnv.agents`, with the session its own variable carries. */ readonly agent: AgentHost; /** How it was decided: see {@link InnermostAgentMethod}. */ readonly method: InnermostAgentMethod; /** The host's process id when the process tree found it; `None` under `environment`. */ readonly pid: Option.Option; } /** * The shape {@link InnermostAgent} provides. * * @public */ export interface InnermostAgentShape { /** * The agent host nearest the running process, or `None` when no agent is detected. Never fails: a process table * it cannot read falls back to `RuntimeEnv.agents`' first entry, as `environment`. Computed once, on first use. */ readonly resolve: Effect.Effect>; } /** * The agent host nearest the running process, decided from the process tree when the environment cannot say. * * @remarks * When one agent host starts another, the environment carries both hosts' variables and no record of which is * inner (see `RuntimeEnv.agents`). This service walks the process's ancestors and returns the first that is one of * the detected hosts: Claude Code by `CLAUDE_PID` or a process named `claude`, Copilot CLI by a process named * `copilot`. With zero or one host detected it answers from the environment and never reads the process table. * * On Linux it reads `/proc/self/stat` and each ancestor's `stat` through `FileSystem`, with no subprocess; elsewhere * it runs one `ps -A -o pid=,ppid=,comm=` through `ChildProcessSpawner`. Where neither works (Windows), it falls * back to the environment's guess. The requirements are this layer's alone: `CurrentRuntimeEnv` still needs * nothing. * * @example * ```ts * import { CurrentRuntimeEnv, InnermostAgent } from "@effected/env" * import { NodeServices } from "@effect/platform-node" * import { Effect, Layer, Option } from "effect" * * const program = Effect.gen(function* () { * const innermost = yield* (yield* InnermostAgent).resolve * return Option.map(innermost, (found) => found.agent.name) * }).pipe( * Effect.provide(InnermostAgent.layer.pipe(Layer.provide([CurrentRuntimeEnv.layer, NodeServices.layer]))), * ) * ``` * * @public */ export class InnermostAgent extends Context.Service()( "@effected/env/InnermostAgent", ) { /** * Resolves from the process tree, once, the first time `resolve` runs. Reads `CLAUDE_PID` through `Config` when * the layer is built. */ static readonly layer: Layer.Layer< InnermostAgent, never, CurrentRuntimeEnv | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem > = Layer.effect( this, Effect.gen(function* () { const { agents } = yield* CurrentRuntimeEnv; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fs = yield* FileSystem.FileSystem; const claudePid = Number((yield* readEnv(["CLAUDE_PID"])).CLAUDE_PID); const fromEnvironment = (): Option.Option => Option.map(Option.fromNullishOr(agents[0]), (agent) => ({ agent, method: "environment" as const, pid: Option.none(), })); const match = (entry: ProcessEntry): Option.Option => { const agent = agents.find( (host) => (host.name === "claude" && entry.pid === claudePid) || AGENT_PROGRAMS.some(([family, program]) => family === host.name && program === entry.name), ); return agent === undefined ? Option.none() : Option.some({ agent, method: "process-tree", pid: Option.some(entry.pid) }); }; const walk = Effect.gen(function* () { const proc = yield* procTable(fs).pipe(Effect.orElseSucceed(() => Option.none())); const table = Option.isSome(proc) ? proc : yield* psTable(spawner).pipe(Effect.orElseSucceed(() => Option.none())); if (Option.isNone(table)) return Option.none(); return yield* findAncestor(table.value.start, table.value.lookup, match); }); const resolve = yield* Effect.cached( Effect.gen(function* () { if (agents.length <= 1) return fromEnvironment(); const found = yield* walk; return Option.isSome(found) ? found : fromEnvironment(); }).pipe(Effect.withSpan("InnermostAgent.resolve", { attributes: { agents: agents.length } })), ); return { resolve }; }), ); /** * A fixed answer that never reads the environment or the process table. * * @param result - what `resolve` returns; `None` when omitted */ static readonly layerTest = ( result: Option.Option = Option.none(), ): Layer.Layer => Layer.succeed(InnermostAgent, { resolve: Effect.succeed(result) }); }