@gajae-code/ utils (英语)
共享gajae-code包的功能:日志、配置和数据路径、环境访问、格式化、流、流程管理、文件助手和崩溃报告.
下面所有东西都从包根导出(@gajae-code/utils) (中文(简体) ). 一些模块作为命名空间导出;参见 命名空间。 。 。 .
锁定器
导出为 logger 名称空间。 默认它会把 JSON 线条写入一个旋转文件, gjc.<YYYY-MM-DD>.log 日志目录中 (getLogsDir(),参见 路径· ; GJC_LOG_DIR 推翻它). 它没有写出任何 stdout 或 stderr, 因为控制台输出会腐蚀 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 });
- 级别 :
error, (中文(简体) ),warn, (中文(简体) ),info, (中文(简体) ),debug每个记录包括:timestamp, (中文(简体) ),level, (中文(简体) ),pid, (中文(简体) ),message,以及上下文字段. - 旋转:每日文件,以10 MB,gzipped再旋转,最多保存了5个.
- 在伐木机完成加载前所写的记录被缓冲,可达一万.
logger.time(op, fn), (中文(简体) ),logger.startTiming(), (中文(简体) ),logger.endTiming(),以及logger.printTimings()创纪录的筑巢时间跨度.
路径( E)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)
模块有较多的代理状态路径获取器( E)getPluginsDir, (中文(简体) ), getMemoriesDir, (中文(简体) ), getCrashLogPath, (中文(简体) ), getMCPConfigPath页:1 他们都进来了 src/dirs.ts。 。 。 .
环境变量读取于 dirs数字 :
| 变量 | 目的 |
|---|---|
GJC_CONFIG_DIR | 配置目录名称( legacy) PI_CONFIG_DIR(中文(简体) ) |
GJC_CODING_AGENT_DIR | 代理目录覆盖( 遗留) PI_CODING_AGENT_DIR(中文(简体) ) |
GJC_LOG_DIR | 日志目录覆盖 |
XDG_DATA_HOME, (中文(简体) ), XDG_STATE_HOME, (中文(简体) ), XDG_CACHE_HOME | XDG 基准目录(见下文) |
<config> 以下为 ~/.gjc,或 ~/<GJC_CONFIG_DIR> 当变量设定时。 XDG 路由只在设定变量时适用于 Linux 和 macOS 财务报告和审定财务报表 $XDG_*_HOME/gjc 已经存在( e)gjc config init-xdg 创建),并且只针对默认代理目录:
| 设置 | getLogsDir() | getSessionsDir() |
|---|---|---|
| 默认代理目录, XDG 未使用 | <config>/logs | <config>/agent/sessions |
| 默认代理目录, XDG 在使用中 | $XDG_STATE_HOME/gjc/logs | $XDG_DATA_HOME/gjc/sessions |
自定义 GJC_CODING_AGENT_DIR (XDG 被忽略) | <config>/logs | $GJC_CODING_AGENT_DIR/sessions |
这些路径变量( E)GJC_CONFIG_DIR, (中文(简体) ), GJC_CODING_AGENT_DIR,以及 XDG_*_HOME) 只有在它们来自过程环境时才算出,比如你的外壳. 当前目录的 .env 无法设置它们 : Bun 加载到环境中, 但值等于 .env 条目被忽略。 如果 .env 条目用途 $ 或 backtick 扩展,即使 shell 设置了不同的值,变量也会被忽略. 在这两种情况下,都适用默认路径.
环境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
格式化(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"
同步和流
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,以及 parseJsonlLenient 覆盖 JSONL 和服务器发送事件流 .
进程
进程助手通过 ptree 财务报告和审定财务报表 procmgr 名称空间。 错误类别 AbortError, (中文(简体) ), ChildProcess, (中文(简体) ), Exception,以及 NonZeroExitError 也可以在根上导出.
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);
文件
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
错误
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,以及 hasFsCode 分类其他文件系统错误.
其他模块
| 模块 | 主要出口 |
|---|---|
color | hexToRgb, (中文(简体) ), rgbToHex, (中文(简体) ), hsvToRgb, (中文(简体) ), adjustHsv |
crash-fingerprint, (中文(简体) ), crash-journal, (中文(简体) ), crash-redaction | computeCrashFingerprint, (中文(简体) ), appendCrashEvent, (中文(简体) ), redactCrashSecrets |
fetch-retry | fetchWithRetry |
frontmatter | parseFrontmatter (回报) { frontmatter, body }, (中文(简体) ), FrontmatterError |
mermaid-ascii | renderMermaidAscii |
sanitize-text | sanitizeText, (中文(简体) ), sanitizeDisplayLine |
snowflake | Snowflake (各种身份帮助) |
tab-spacing | getDefaultTabWidth (3个默认), setDefaultTabWidth |
type-guards | isRecord, (中文(简体) ), asRecord, (中文(简体) ), toError |
which | $which |
命名空间
这些模块被导出为命名空间而不是平面名称 :
| 命名空间 | 目录 |
|---|---|
logger | 伐木和时间跨度 |
postmortem | 崩溃记录 |
procmgr | 进程活度和退出帮助 |
prompt | 快速帮助者 |
ptree | spawn, (中文(简体) ), exec,以及儿童流程课程 |
发展
cd packages/utils
bun run check # Biome + tsc
bun test
许可证
麻省理工学院