UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

150 lines • 7.75 kB
import { readFileSync } from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; // Kernel identity: `<uname -s> <uname -r>` (`Darwin 25.3.0`, `Linux 6.8.0-45-generic`). // Deliberately NOT `os.version()` — Node returns the full xnu build string on // macOS (noisy) and some runtimes return the literal "unknown", which makes // models misidentify the host platform. function cpuModel() { if (process.platform === "linux") { try { const cpuInfo = readFileSync("/proc/cpuinfo", "utf8"); const match = /^model name\s*:\s*(.+)$/m.exec(cpuInfo); if (match?.[1]) return match[1].trim(); } catch { // fall through to os.cpus() } } return os.cpus()[0]?.model?.trim() || undefined; } // GPU: only derivable without a subprocess on Apple Silicon, where the SoC // name doubles as the GPU name. Other platforms would need nvidia-smi/lspci — // deliberately skipped to keep prompt assembly synchronous. function terminalName(env) { const program = env.TERM_PROGRAM?.trim(); if (program) { const version = env.TERM_PROGRAM_VERSION?.trim(); return version ? `${program} ${version}` : program; } return env.TERM?.trim() || undefined; } /** * Test-only host pin (senpi#4660): `SENPI_TEST_WORKSTATION={"cpuModel":string,"cores":int,"kernel":string}` * replaces the CPU model, core count and kernel identity so a harness driving the real CLI gets the same prompt * bytes on every host. The optional `"repoRoot":{"from":absolute path,"to":absolute path}` (senpi#5067) shows a * path under the checkout `from` as the same path under `to` wherever the prompt renders it (`pinnedDisplayPath`), * so the checkout location does not reach the prompt either. Unset (or empty) in every production launch. */ const WORKSTATION_ENV = "SENPI_TEST_WORKSTATION"; function pinnedRepoRoot(value) { if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined; const fields = value; const { from, to } = fields; if (Object.keys(fields).sort().join(",") !== "from,to") return undefined; if (typeof from !== "string" || typeof to !== "string" || !path.isAbsolute(from) || !path.isAbsolute(to)) return undefined; return { from, to }; } function pinnedHost(env) { const value = env[WORKSTATION_ENV]; if (value === undefined || value === "") return undefined; const invalid = new Error(`${WORKSTATION_ENV} must be a JSON object {"cpuModel": non-empty string, "cores": positive integer, "kernel": non-empty string, optional "repoRoot": {"from": absolute path, "to": absolute path}}, got ${JSON.stringify(value)}`); let parsed; try { parsed = JSON.parse(value); } catch { throw invalid; } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw invalid; const fields = parsed; const { cpuModel, cores, kernel } = fields; const keys = Object.keys(fields).sort().join(","); const exactKeys = keys === "cores,cpuModel,kernel" || keys === "cores,cpuModel,kernel,repoRoot"; const repoRoot = "repoRoot" in fields ? pinnedRepoRoot(fields.repoRoot) : undefined; if (("repoRoot" in fields && repoRoot === undefined) || !exactKeys || typeof cpuModel !== "string" || cpuModel === "" || typeof kernel !== "string" || kernel === "" || typeof cores !== "number" || !Number.isInteger(cores) || cores < 1) { throw invalid; } return { cpuModel, cores, kernel, ...(repoRoot === undefined ? {} : { repoRoot }) }; } /** * `filePath` as the prompt should show it: under the test-only `repoRoot` pin, a path inside the pinned checkout * (`from`) is shown under `to`. Every other path, and every path when the pin is unset, is returned unchanged. * Only for rendering: reads and writes keep using the real path. */ export function pinnedDisplayPath(filePath, env = process.env) { const root = pinnedHost(env)?.repoRoot; if (root === undefined) return filePath; if (filePath === root.from) return root.to; const prefix = root.from.endsWith(path.sep) ? root.from : root.from + path.sep; return filePath.startsWith(prefix) ? path.join(root.to, filePath.slice(prefix.length)) : filePath; } /** Read host facts from `node:os` and `env`, honoring the test-only `SENPI_TEST_WORKSTATION` pin. Not cached. */ export function readWorkstationFacts(env = process.env) { const pinned = pinnedHost(env); const cpu = pinned ? pinned.cpuModel : cpuModel(); const cores = pinned ? pinned.cores : os.availableParallelism(); const gpu = process.platform === "darwin" && os.arch() === "arm64" && cpu?.startsWith("Apple ") ? cpu : undefined; const terminal = terminalName(env); return { osLine: os.platform(), kernel: pinned ? pinned.kernel : `${os.type()} ${os.release()}`.trim(), arch: os.arch(), ...(cpu === undefined ? {} : { cpu: `${cpu} (${cores} cores)` }), ...(gpu === undefined ? {} : { gpu }), ...(terminal === undefined ? {} : { terminal }), }; } let cachedFacts; /** Collect host facts once per process; every call after the first is free. */ export function collectWorkstationFacts() { cachedFacts ??= readWorkstationFacts(); return cachedFacts; } /** Subject + verb naming the local executors, e.g. "`bash` and `eval` execute". */ function executorPhrase(selectedTools) { const executors = ["bash", "eval"].filter((name) => selectedTools.includes(name)); if (executors.length === 0) return "Everything you run executes"; return `${executors.map((name) => `\`${name}\``).join(" and ")} execute${executors.length === 1 ? "s" : ""}`; } const INSTRUCTIONS = { claude: (executors) => `<execution_context> ${executors} on THIS workstation. Match commands, paths, package managers, and parallel pool sizes to it. Code you write may target any machine; code you run always runs here. </execution_context>`, codex: (executors) => `${executors} on this workstation; match commands, paths, and parallelism to it. Written code may target other platforms: executed code runs here.`, kimi: (executors) => `${executors} on this workstation: choose commands, paths, and parallelism that fit it. When writing code for another target platform, keep the code portable; only the execution happens here.`, gemini: (executors) => `${executors} on this workstation; match commands, paths, package managers, and parallel pool sizes to it. Code you write may target another machine; code you run always runs here.`, default: (executors) => `**EXECUTION HAPPENS HERE.** ${executors} on THIS machine: match commands, paths, package managers, parallel pool sizes to the workstation above. Code you WRITE may target another machine; anything you RUN executes HERE.`, }; /** Render the `<workstation>` facts block plus the dialect-tuned execution-context instruction. */ export function buildWorkstationSection(options) { const facts = options.facts ?? collectWorkstationFacts(); const dialect = options.dialect ?? "default"; const lines = [ `- OS: ${facts.osLine} (kernel ${facts.kernel})`, `- Arch: ${facts.arch}`, ...(facts.cpu ? [`- CPU: ${facts.cpu}`] : []), ...(facts.gpu ? [`- GPU: ${facts.gpu}`] : []), ...(facts.terminal ? [`- Terminal: ${facts.terminal}`] : []), ]; const instruction = INSTRUCTIONS[dialect](executorPhrase(options.selectedTools)); return `<workstation>\n${lines.join("\n")}\n</workstation>\n${instruction}`; } //# sourceMappingURL=workstation.js.map