Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat(sdk/ts): add paths module with HEADROOM_CONFIG_DIR / HEADROOM_WORKSPACE_DIR parity
JerrettDavis028e2c0c1bce
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 43123dc76..40eb3342e 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -108,3 +108,33 @@ export type {SharedContextStats,SharedContextOptions,} from "./shared-context.js";++// --- Filesystem contract (parity shell with headroom.paths) ---+export {+ HEADROOM_CONFIG_DIR_ENV,+ HEADROOM_WORKSPACE_DIR_ENV,+ HEADROOM_SAVINGS_PATH_ENV,+ HEADROOM_TOIN_PATH_ENV,+ HEADROOM_SUBSCRIPTION_STATE_PATH_ENV,+ configDir,+ workspaceDir,+ savingsPath,+ toinPath,+ subscriptionStatePath,+ memoryDbPath,+ nativeMemoryDir,+ licenseCachePath,+ sessionStatsPath,+ syncStatePath,+ bridgeStatePath,+ logDir,+ proxyLogPath,+ debug400Dir,+ binDir,+ rtkPath,+ deployRoot,+ beaconLockPath,+ modelsConfigPath,+ pluginConfigDir,+ pluginWorkspaceDir,+} from "./paths.js";diff --git a/sdk/typescript/src/paths.ts b/sdk/typescript/src/paths.tsnew file mode 100644index 000000000..c4e18a58e--- /dev/null+++ b/sdk/typescript/src/paths.ts@@ -0,0 +1,272 @@+/**+ * Canonical filesystem contract for Headroom — parity shell for the npm SDK.+ *+ * The TypeScript SDK is an HTTP client today and does not touch the+ * filesystem directly. This module mirrors `headroom/paths.py` so that+ * future local features (e.g. cache/log co-location with the Python+ * proxy) land on the same contract.+ *+ * Two canonical roots:+ * - HEADROOM_CONFIG_DIR — read-mostly configuration+ * (default: ~/.headroom/config)+ * - HEADROOM_WORKSPACE_DIR — read-write state+ * (default: ~/.headroom)+ *+ * Precedence for every per-resource helper is:+ * explicit argument > per-resource env var > derived from canonical+ * root > default.+ *+ * Browser behavior: when `process` is not available (typeof process ===+ * "undefined"), all helpers return the empty string. Consumers running+ * in a browser should not call these helpers; they exist here so the+ * shape of the API matches Python's `headroom.paths` module.+ */++// ---------------------------------------------------------------------------+// Env var names+// ---------------------------------------------------------------------------++export const HEADROOM_CONFIG_DIR_ENV = "HEADROOM_CONFIG_DIR";+export const HEADROOM_WORKSPACE_DIR_ENV = "HEADROOM_WORKSPACE_DIR";++export const HEADROOM_SAVINGS_PATH_ENV = "HEADROOM_SAVINGS_PATH";+export const HEADROOM_TOIN_PATH_ENV = "HEADROOM_TOIN_PATH";+export const HEADROOM_SUBSCRIPTION_STATE_PATH_ENV =+ "HEADROOM_SUBSCRIPTION_STATE_PATH";++// ---------------------------------------------------------------------------+// Node / browser guard (mirrors the pattern in client.ts::getEnv)+// ---------------------------------------------------------------------------++function isNode(): boolean {+ return (+ typeof process !== "undefined" &&+ typeof process.versions !== "undefined" &&+ typeof process.versions.node === "string"+ );+}++function getEnv(name: string): string {+ if (typeof process === "undefined" || !process.env) {+ return "";+ }+ const value = process.env[name];+ return typeof value === "string" ? value.trim() : "";+}++function homeDir(): string {+ if (!isNode()) {+ return "";+ }+ // Prefer the userInfo API, fall back to HOME / USERPROFILE env vars.+ try {+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ const os = require("os") as { homedir?: () => string };+ if (os.homedir) {+ const home = os.homedir();+ if (home) return home;+ }+ } catch {+ // ignore — fall back to env+ }+ return getEnv("HOME") || getEnv("USERPROFILE") || "";+}++function joinPath(...parts: string[]): string {+ if (!isNode()) {+ // Browser fallback — keep it simple, use forward slashes.+ return parts.filter((p) => p !== "").join("/");+ }+ try {+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ const path = require("path") as {+ join?: (...p: string[]) => string;+ };+ if (path.join) return path.join(...parts.filter((p) => p !== ""));+ } catch {+ // ignore — fall back+ }+ const sep = process.platform === "win32" ? "\\" : "/";+ return parts.filter((p) => p !== "").join(sep);+}++function expandTilde(p: string): string {+ if (!p.startsWith("~")) return p;+ const home = homeDir();+ if (!home) return p;+ if (p === "~") return home;+ if (p.startsWith("~/") || p.startsWith("~\\")) {+ return joinPath(home, p.slice(2));+ }+ return p;+}++function resolve(+ explicit: string | undefined,+ envVar: string,+ derived: string,+): string {+ if (!isNode()) {+ // Browser fallback: no filesystem, return empty string.+ return "";+ }+ if (explicit !== undefined && explicit !== "") {+ return expandTilde(explicit);+ }+ const envValue = getEnv(envVar);+ if (envValue) {+ return expandTilde(envValue);+ }+ return derived;+}++// ---------------------------------------------------------------------------+// Canonical roots+// ---------------------------------------------------------------------------++export function workspaceDir(): string {+ if (!isNode()) return "";+ const envValue = getEnv(HEADROOM_WORKSPACE_DIR_ENV);+ if (envValue) return expandTilde(envValue);+ const home = homeDir();+ if (!home) return "";+ return joinPath(home, ".headroom");+}++export function configDir(): string {+ if (!isNode()) return "";+ const envValue = getEnv(HEADROOM_CONFIG_DIR_ENV);+ if (envValue) return expandTilde(envValue);+ const workspaceEnv = getEnv(HEADROOM_WORKSPACE_DIR_ENV);+ if (workspaceEnv) {+ return joinPath(expandTilde(workspaceEnv), "config");+ }+ const home = homeDir();+ if (!home) return "";+ return joinPath(home, ".headroom", "config");+}++// ---------------------------------------------------------------------------+// Per-resource helpers -- workspace bucket+// ---------------------------------------------------------------------------++export function savingsPath(explicit?: string): string {+ return resolve(+ explicit,+ HEADROOM_SAVINGS_PATH_ENV,+ joinPath(workspaceDir(), "proxy_savings.json"),+ );+}++export function toinPath(explicit?: string): string {+ return resolve(+ explicit,+ HEADROOM_TOIN_PATH_ENV,+ joinPath(workspaceDir(), "toin.json"),+ );+}++export function subscriptionStatePath(explicit?: string): string {+ return resolve(+ explicit,+ HEADROOM_SUBSCRIPTION_STATE_PATH_ENV,+ joinPath(workspaceDir(), "subscription_state.json"),+ );+}++export function memoryDbPath(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "memory.db");+}++export function nativeMemoryDir(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "memories");+}++export function licenseCachePath(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "license_cache.json");+}++export function sessionStatsPath(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "session_stats.jsonl");+}++export function syncStatePath(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "sync_state.json");+}++export function bridgeStatePath(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "bridge_state.json");+}++export function logDir(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "logs");+}++export function proxyLogPath(): string {+ if (!isNode()) return "";+ return joinPath(logDir(), "proxy.log");+}++export function debug400Dir(): string {+ if (!isNode()) return "";+ return joinPath(logDir(), "debug_400");+}++export function binDir(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "bin");+}++export function rtkPath(): string {+ if (!isNode()) return "";+ const name = process.platform === "win32" ? "rtk.exe" : "rtk";+ return joinPath(binDir(), name);+}++export function deployRoot(): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "deploy");+}++export function beaconLockPath(port: number): string {+ if (!isNode()) return "";+ return joinPath(workspaceDir(), `.beacon_lock_${Math.trunc(port)}`);+}++// ---------------------------------------------------------------------------+// Per-resource helpers -- config bucket+// ---------------------------------------------------------------------------++export function modelsConfigPath(): string {+ if (!isNode()) return "";+ return joinPath(configDir(), "models.json");+}++// ---------------------------------------------------------------------------+// Plugin-author entry points+// ---------------------------------------------------------------------------++function assertPluginName(name: string): void {+ if (!name || name.includes("/") || name.includes("\\")) {+ throw new Error(`invalid plugin name: ${JSON.stringify(name)}`);+ }+}++export function pluginConfigDir(pluginName: string): string {+ assertPluginName(pluginName);+ if (!isNode()) return "";+ return joinPath(configDir(), "plugins", pluginName);+}++export function pluginWorkspaceDir(pluginName: string): string {+ assertPluginName(pluginName);+ if (!isNode()) return "";+ return joinPath(workspaceDir(), "plugins", pluginName);+}diff --git a/sdk/typescript/test/paths.test.ts b/sdk/typescript/test/paths.test.tsnew file mode 100644index 000000000..7c031298f--- /dev/null+++ b/sdk/typescript/test/paths.test.ts@@ -0,0 +1,368 @@+/**+ * Tests for the filesystem contract module — mirrors the Python+ * `tests/test_paths.py` precedence matrix to keep the SDK honest as a+ * parity shell.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as os from "os";+import * as path from "path";++import {+ HEADROOM_CONFIG_DIR_ENV,+ HEADROOM_SAVINGS_PATH_ENV,+ HEADROOM_SUBSCRIPTION_STATE_PATH_ENV,+ HEADROOM_TOIN_PATH_ENV,+ HEADROOM_WORKSPACE_DIR_ENV,+ beaconLockPath,+ binDir,+ bridgeStatePath,+ configDir,+ debug400Dir,+ deployRoot,+ licenseCachePath,+ logDir,+ memoryDbPath,+ modelsConfigPath,+ nativeMemoryDir,+ pluginConfigDir,+ pluginWorkspaceDir,+ proxyLogPath,+ rtkPath,+ savingsPath,+ sessionStatsPath,+ subscriptionStatePath,+ syncStatePath,+ toinPath,+ workspaceDir,+} from "../src/paths.js";++// ---------------------------------------------------------------------------+// Env var housekeeping+// ---------------------------------------------------------------------------++const ENV_VARS = [+ HEADROOM_CONFIG_DIR_ENV,+ HEADROOM_WORKSPACE_DIR_ENV,+ HEADROOM_SAVINGS_PATH_ENV,+ HEADROOM_TOIN_PATH_ENV,+ HEADROOM_SUBSCRIPTION_STATE_PATH_ENV,+];++function saveEnv(): Record<string, string | undefined> {+ const snap: Record<string, string | undefined> = {};+ for (const k of ENV_VARS) snap[k] = process.env[k];+ return snap;+}++function restoreEnv(snap: Record<string, string | undefined>): void {+ for (const k of ENV_VARS) {+ if (snap[k] === undefined) {+ delete process.env[k];+ } else {+ process.env[k] = snap[k];+ }+ }+}++function clearEnv(): void {+ for (const k of ENV_VARS) delete process.env[k];+}++// ---------------------------------------------------------------------------+// Canonical roots+// ---------------------------------------------------------------------------++describe("canonical roots", () => {+ let snap: Record<string, string | undefined>;+ beforeEach(() => {+ snap = saveEnv();+ clearEnv();+ });+ afterEach(() => restoreEnv(snap));++ it("workspaceDir defaults to ~/.headroom", () => {+ expect(workspaceDir()).toBe(path.join(os.homedir(), ".headroom"));+ });++ it("workspaceDir honors HEADROOM_WORKSPACE_DIR env override", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = "/tmp/alt_ws";+ expect(workspaceDir()).toBe("/tmp/alt_ws");+ });++ it("workspaceDir ignores blank env value", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = " ";+ expect(workspaceDir()).toBe(path.join(os.homedir(), ".headroom"));+ });++ it("workspaceDir expands tilde", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = "~/custom-ws";+ expect(workspaceDir()).toBe(path.join(os.homedir(), "custom-ws"));+ });++ it("configDir defaults to ~/.headroom/config", () => {+ expect(configDir()).toBe(path.join(os.homedir(), ".headroom", "config"));+ });++ it("configDir follows HEADROOM_WORKSPACE_DIR when only workspace set", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = "/tmp/alt_ws";+ expect(configDir()).toBe(path.join("/tmp/alt_ws", "config"));+ });++ it("explicit HEADROOM_CONFIG_DIR env beats workspace env", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = "/tmp/alt_ws";+ process.env[HEADROOM_CONFIG_DIR_ENV] = "/tmp/alt_cfg";+ expect(configDir()).toBe("/tmp/alt_cfg");+ });+});++// ---------------------------------------------------------------------------+// Per-resource precedence matrix+// ---------------------------------------------------------------------------++type ResourceCase = {+ name: string;+ fn: (explicit?: string) => string;+ envVar: string;+ filename: string;+};++const RESOURCES: ResourceCase[] = [+ {+ name: "savingsPath",+ fn: savingsPath,+ envVar: HEADROOM_SAVINGS_PATH_ENV,+ filename: "proxy_savings.json",+ },+ {+ name: "toinPath",+ fn: toinPath,+ envVar: HEADROOM_TOIN_PATH_ENV,+ filename: "toin.json",+ },+ {+ name: "subscriptionStatePath",+ fn: subscriptionStatePath,+ envVar: HEADROOM_SUBSCRIPTION_STATE_PATH_ENV,+ filename: "subscription_state.json",+ },+];++describe.each(RESOURCES)(+ "resource precedence: $name",+ ({ fn, envVar, filename }) => {+ let snap: Record<string, string | undefined>;+ beforeEach(() => {+ snap = saveEnv();+ clearEnv();+ });+ afterEach(() => restoreEnv(snap));++ it("default under ~/.headroom", () => {+ expect(fn()).toBe(path.join(os.homedir(), ".headroom", filename));+ });++ it("derived from HEADROOM_WORKSPACE_DIR when set", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = "/tmp/state";+ expect(fn()).toBe(path.join("/tmp/state", filename));+ });++ it("legacy env var wins over workspace-derived", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = "/tmp/state";+ process.env[envVar] = "/tmp/legacy.json";+ expect(fn()).toBe("/tmp/legacy.json");+ });++ it("explicit arg wins over everything", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = "/tmp/state";+ process.env[envVar] = "/tmp/legacy.json";+ expect(fn("/tmp/explicit.json")).toBe("/tmp/explicit.json");+ });++ it("explicit empty string falls through to default", () => {+ expect(fn("")).toBe(path.join(os.homedir(), ".headroom", filename));+ });++ it("legacy env expands tilde", () => {+ process.env[envVar] = "~/foo.json";+ expect(fn()).toBe(path.join(os.homedir(), "foo.json"));+ });+ },+);++// ---------------------------------------------------------------------------+// Resources without a legacy env var+// ---------------------------------------------------------------------------++describe("derived-only resources", () => {+ let snap: Record<string, string | undefined>;+ beforeEach(() => {+ snap = saveEnv();+ clearEnv();+ });+ afterEach(() => restoreEnv(snap));++ it("memoryDbPath", () => {+ expect(memoryDbPath()).toBe(+ path.join(os.homedir(), ".headroom", "memory.db"),+ );+ });++ it("nativeMemoryDir", () => {+ expect(nativeMemoryDir()).toBe(+ path.join(os.homedir(), ".headroom", "memories"),+ );+ });++ it("licenseCachePath", () => {+ expect(licenseCachePath()).toBe(+ path.join(os.homedir(), ".headroom", "license_cache.json"),+ );+ });++ it("sessionStatsPath", () => {+ expect(sessionStatsPath()).toBe(+ path.join(os.homedir(), ".headroom", "session_stats.jsonl"),+ );+ });++ it("syncStatePath", () => {+ expect(syncStatePath()).toBe(+ path.join(os.homedir(), ".headroom", "sync_state.json"),+ );+ });++ it("bridgeStatePath", () => {+ expect(bridgeStatePath()).toBe(+ path.join(os.homedir(), ".headroom", "bridge_state.json"),+ );+ });++ it("logDir", () => {+ expect(logDir()).toBe(path.join(os.homedir(), ".headroom", "logs"));+ });++ it("proxyLogPath", () => {+ expect(proxyLogPath()).toBe(+ path.join(os.homedir(), ".headroom", "logs", "proxy.log"),+ );+ });++ it("debug400Dir", () => {+ expect(debug400Dir()).toBe(+ path.join(os.homedir(), ".headroom", "logs", "debug_400"),+ );+ });++ it("binDir", () => {+ expect(binDir()).toBe(path.join(os.homedir(), ".headroom", "bin"));+ });++ it("rtkPath ends with rtk or rtk.exe", () => {+ const p = rtkPath();+ const expected = process.platform === "win32" ? "rtk.exe" : "rtk";+ expect(path.basename(p)).toBe(expected);+ });++ it("deployRoot", () => {+ expect(deployRoot()).toBe(path.join(os.homedir(), ".headroom", "deploy"));+ });++ it("beaconLockPath includes port", () => {+ expect(beaconLockPath(8787)).toBe(+ path.join(os.homedir(), ".headroom", ".beacon_lock_8787"),+ );+ });++ it("modelsConfigPath under configDir", () => {+ expect(modelsConfigPath()).toBe(+ path.join(os.homedir(), ".headroom", "config", "models.json"),+ );+ });++ it("modelsConfigPath follows config env override", () => {+ process.env[HEADROOM_CONFIG_DIR_ENV] = "/tmp/cfg";+ expect(modelsConfigPath()).toBe(path.join("/tmp/cfg", "models.json"));+ });++ it("modelsConfigPath follows workspace env", () => {+ process.env[HEADROOM_WORKSPACE_DIR_ENV] = "/tmp/ws";+ expect(modelsConfigPath()).toBe(+ path.join("/tmp/ws", "config", "models.json"),+ );+ });+});++// ---------------------------------------------------------------------------+// Plugin namespace isolation+// ---------------------------------------------------------------------------++describe("plugin dirs", () => {+ let snap: Record<string, string | undefined>;+ beforeEach(() => {+ snap = saveEnv();+ clearEnv();+ });+ afterEach(() => restoreEnv(snap));++ it("pluginConfigDir namespaced under configDir/plugins", () => {+ const a = pluginConfigDir("alpha");+ const b = pluginConfigDir("beta");+ expect(a).not.toBe(b);+ expect(a).toBe(+ path.join(os.homedir(), ".headroom", "config", "plugins", "alpha"),+ );+ });++ it("pluginWorkspaceDir namespaced under workspaceDir/plugins", () => {+ const a = pluginWorkspaceDir("alpha");+ const b = pluginWorkspaceDir("beta");+ expect(a).not.toBe(b);+ expect(a).toBe(+ path.join(os.homedir(), ".headroom", "plugins", "alpha"),+ );+ });++ for (const bad of ["", "foo/bar", "foo\\bar"]) {+ it(`rejects invalid plugin name ${JSON.stringify(bad)}`, () => {+ expect(() => pluginConfigDir(bad)).toThrow();+ expect(() => pluginWorkspaceDir(bad)).toThrow();+ });+ }+});++// ---------------------------------------------------------------------------+// Browser fallback (simulated absence of `process`)+// ---------------------------------------------------------------------------++describe("browser fallback", () => {+ it("all helpers return empty string when Node guard fails", async () => {+ const snap = saveEnv();+ clearEnv();+ const originalDescriptor = Object.getOwnPropertyDescriptor(+ process,+ "versions",+ );+ // Simulate a non-Node runtime by making `process.versions.node` go away.+ // `process.versions` is read-only in Node, so swap via defineProperty.+ Object.defineProperty(process, "versions", {+ value: { v8: "x" } as NodeJS.ProcessVersions,+ configurable: true,+ writable: true,+ });+ try {+ vi.resetModules();+ const mod = await import("../src/paths.js");+ expect(mod.workspaceDir()).toBe("");+ expect(mod.configDir()).toBe("");+ expect(mod.savingsPath()).toBe("");+ expect(mod.toinPath()).toBe("");+ expect(mod.memoryDbPath()).toBe("");+ expect(mod.modelsConfigPath()).toBe("");+ } finally {+ if (originalDescriptor) {+ Object.defineProperty(process, "versions", originalDescriptor);+ }+ restoreEnv(snap);+ }+ });+});