@gajae-code/utils

中文文档
0.21.0发布于 2026/11/16MITTypeScriptES Module构建来源已验证近 30 天下载 8374

Shared utilities for pi packages

原始使用文档
文档目录12 节
  1. Logger
  2. Paths ( dirs )
  3. Environment ( env )
  4. Formatting ( format )
  5. Async and streams
  6. Processes
  7. Files
  8. Errors
  9. Other modules
  10. Namespaces
  11. Development
  12. License

@gajae-code/utils

Shared utilities for the gajae-code packages: logging, config and data paths, environment access, formatting, streams, process management, file helpers, and crash reporting.

Everything below is exported from the package root (@gajae-code/utils). A few modules are exported as namespaces; see Namespaces.

Logger

The logger is exported as the logger namespace. By default it writes JSON lines to a rotating file, gjc.<YYYY-MM-DD>.log in the logs directory (getLogsDir(), see Paths; GJC_LOG_DIR overrides it). It writes nothing to stdout or stderr, because console output would corrupt the TUI.

import { logger } from "@gajae-code/utils";

logger.info("Server started", { port: 3847 });
logger.warn("Retrying", { attempt: 3 });
logger.error("Connection failed", { error: "ECONNRESET" });
logger.debug("Request details", { url: "https://example.com" });

// Long-running headless services can log to the console instead of the file.
logger.setTransports({ console: true, file: false });
  • Levels: error, warn, info, debug. Each record includes timestamp, level, pid, message, and the context fields.
  • Rotation: daily files, rotated again at 10 MB, gzipped, and at most 5 kept.
  • Records written before the logger finishes loading are buffered, up to 10,000.
  • logger.time(op, fn), logger.startTiming(), logger.endTiming(), and logger.printTimings() record nested timing spans.

Paths (dirs)

import {
  APP_NAME,
  CONFIG_DIR_NAME,
  getAgentDir,
  getConfigRootDir,
  getEffectiveLogsDir,
  getLogsDir,
  getProjectDir,
  getSessionsDir,
} from "@gajae-code/utils";

APP_NAME; // "gjc"
CONFIG_DIR_NAME; // ".gjc"

getConfigRootDir(); // config root, ~/.gjc by default
getAgentDir(); // agent directory under the config root
getSessionsDir(); // ~/.gjc/agent/sessions by default
getLogsDir(); // ~/.gjc/logs by default
getEffectiveLogsDir(); // where the logger actually writes (honors a trusted GJC_LOG_DIR)
getProjectDir(); // the current project directory (process.cwd() unless setProjectDir() changed it)

The module has more path getters for agent state (getPluginsDir, getMemoriesDir, getCrashLogPath, getMCPConfigPath, and others). They are all in src/dirs.ts.

Environment variables read by dirs:

VariablePurpose
GJC_CONFIG_DIRConfig directory name (legacy PI_CONFIG_DIR)
GJC_CODING_AGENT_DIRAgent directory override (legacy PI_CODING_AGENT_DIR)
GJC_LOG_DIRLog directory override
XDG_DATA_HOME, XDG_STATE_HOME, XDG_CACHE_HOMEXDG base directories (see below)

<config> below is ~/.gjc, or ~/<GJC_CONFIG_DIR> when that variable is set. XDG routing applies on Linux and macOS only when the variable is set and $XDG_*_HOME/gjc already exists (gjc config init-xdg creates it), and only for the default agent directory:

SetupgetLogsDir()getSessionsDir()
Default agent directory, XDG not in use<config>/logs<config>/agent/sessions
Default agent directory, XDG in use$XDG_STATE_HOME/gjc/logs$XDG_DATA_HOME/gjc/sessions
Custom GJC_CODING_AGENT_DIR (XDG ignored)<config>/logs$GJC_CODING_AGENT_DIR/sessions

These path variables (GJC_CONFIG_DIR, GJC_CODING_AGENT_DIR, and XDG_*_HOME) count only when they come from the process environment, such as your shell. The current directory's .env cannot set them: Bun loads it into the environment, but a value equal to the .env entry is ignored. If the .env entry uses $ or backtick expansion, the variable is ignored even when the shell sets a different value. In both cases the default path applies.

Environment (env)

import { $env, $flag, $pickenv, parseEnvFile } from "@gajae-code/utils";

const home = $env.HOME;
const apiKey = $pickenv("ANTHROPIC_API_KEY", "OPENAI_API_KEY"); // first non-empty value
const verbose = $flag("GJC_VERBOSE"); // boolean flag, false when unset
const fromFile = parseEnvFile(".env"); // reads and parses the file at this path

Formatting (format)

import {
  formatAge,
  formatBytes,
  formatCount,
  formatDuration,
  formatNumber,
  formatPercent,
  pluralize,
  truncate,
} from "@gajae-code/utils";

formatDuration(1500); // "1.5s"
formatDuration(123456789); // "1d10h"
formatNumber(12345); // "12K"
formatNumber(1234567); // "1.2M"
formatBytes(1024 * 1024); // "1.0MB"
formatPercent(0.1234); // "12.3%"
truncate("Hello World", 8); // "Hello W…"
formatCount("request", 42); // "42 requests"
formatAge(3661); // "1h ago" (argument in seconds)
pluralize("item", 5); // "items"

Async and streams

import { createAbortableStream, readJsonl, readLines, withTimeout } from "@gajae-code/utils";

// Rejects with the message if the promise does not settle within 5 s.
const response = await withTimeout(fetch("https://example.com"), 5000, "request timed out");

// readLines yields each line as bytes; readJsonl yields parsed values.
const body = createAbortableStream(response.body!, AbortSignal.timeout(10_000));
for await (const line of readLines(body)) {
  console.log(new TextDecoder().decode(line));
}

readJsonl, readSseJson, readSseEvents, and parseJsonlLenient cover JSONL and server-sent event streams.

Processes

Process helpers are exported through the ptree and procmgr namespaces. The error classes AbortError, ChildProcess, Exception, and NonZeroExitError are also exported at the root.

import { procmgr, ptree } from "@gajae-code/utils";

const result = await ptree.exec(["git", "status", "--short"]);
if (result.ok) console.log(result.stdout);

const child = ptree.spawn(["bun", "--version"]);
procmgr.isPidRunning(child.pid);

Files

import { globPaths, peekFile, TempDir, tryParseJson } from "@gajae-code/utils";

// Glob relative to cwd (defaults to getProjectDir()), with exclusions.
const sources = await globPaths("src/**/*.ts", { cwd: process.cwd(), exclude: ["**/*.test.ts"] });

// Read only the first bytes of a file.
const header = await peekFile("package.json", 64, bytes => new TextDecoder().decode(bytes));

// A temporary directory that is removed when the scope exits.
await using tmp = await TempDir.create("my-tool-");
console.log(tmp.path());

const parsed = tryParseJson<{ name: string }>("{\"name\":\"gjc\"}"); // null on invalid JSON

Errors

import { isDesignedError, isEnoent, markDesignedError, safeErrorDescription, toError } from "@gajae-code/utils";

try {
  await Bun.file("missing.txt").text();
} catch (error) {
  if (isEnoent(error)) console.log("not found");
  console.log(safeErrorDescription(error)); // a string for any thrown value
}

const expected = markDesignedError(new Error("user cancelled"));
isDesignedError(expected); // true
toError("plain string"); // wraps non-Error values in an Error

isEacces, isEisdir, isEnotdir, isEexist, isEnotempty, and hasFsCode classify other filesystem errors.

Other modules

ModuleMain exports
colorhexToRgb, rgbToHex, hsvToRgb, adjustHsv
crash-fingerprint, crash-journal, crash-redactioncomputeCrashFingerprint, appendCrashEvent, redactCrashSecrets
fetch-retryfetchWithRetry
frontmatterparseFrontmatter (returns { frontmatter, body }), FrontmatterError
mermaid-asciirenderMermaidAscii
sanitize-textsanitizeText, sanitizeDisplayLine
snowflakeSnowflake (sortable ID helpers)
tab-spacinggetDefaultTabWidth (3 by default), setDefaultTabWidth
type-guardsisRecord, asRecord, toError
which$which

Namespaces

These modules are exported as namespaces rather than as flat names:

NamespaceContents
loggerLogging and timing spans
postmortemCrash recording
procmgrProcess liveness and exit helpers
promptPrompt helpers
ptreespawn, exec, and the child-process classes

Development

cd packages/utils
bun run check   # Biome + tsc
bun test

License

MIT

版本与发布记录

@gajae-code/utils 共发布 159 个版本,首次发布于 2026/05/28;过去 12 个月发布了 159 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.21.0latest2026/11/16今天
0.20.1-nightly.20261108030927.43711868338.gb4127889c4a8nightly2026/11/15今天
0.20.1-nightly.20261108030927.43590872198.gb4127889c4a82026/11/141 天前
0.20.1-nightly.20261108030927.43424588966.gb4127889c4a82026/11/132 天前
0.20.1-nightly.20261108030927.43222623203.gb4127889c4a82026/11/123 天前
0.20.1-nightly.20261108030927.43016219422.gb4127889c4a82026/11/114 天前

关于 @gajae-code/utils 的常见问题

@gajae-code/utils 是什么?

Shared utilities for pi packages

如何安装 @gajae-code/utils?

在项目目录运行 npm install @gajae-code/utils,或使用 pnpm add / yarn add / bun add。

@gajae-code/utils 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gajae-code/utils 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gajae-code/utils 可以商用吗?

@gajae-code/utils 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gajae-code/utils 的下载量有多少?

根据 npm 官方下载统计,@gajae-code/utils 在 2026/10/16 – 2026/11/14 这 30 天内被下载 8,374 次,日均约 279 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gajae-code/utils 还在维护吗?

最新版本 0.21.0 发布于 2026/11/16(今天);至今共发布 159 个版本,其中过去 12 个月发布了 159 个;首次发布于 2026/05/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。