# @gobing-ai/ts-runtime 中文文档

规范地址：https://npmcn.com/package/%40gobing-ai/ts-runtime/

版本：0\.7\.1
npm 元数据更新时间：2026-10-25T00:55:16.280Z
中文译文更新时间：2026-11-16T17:47:29.274Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gobing-ai/ts-runtime
原文对照：https://npmcn.com/package/%40gobing-ai/ts-runtime/?lang=original
项目主页：https://github.com/gobing-ai/ts-libs#readme
源码仓库：https://github.com/gobing-ai/ts-libs

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：345 kB，102 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：4 个
- peer 依赖：@gobing-ai/ts-db ^0\.7\.1
- 首次发布：2026-05-29T16:58:08.070Z
- 最新版本发布：2026-10-25T00:55:15.928Z
- 近 30 天下载量：5149（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：137（近 12 个月 137 个）

## 中文简介

@gobing-ai/ts-runtime-为邦,节点和Cloudflare工人的运行时抽象.

## 安装

```sh
npm install @gobing-ai/ts-runtime
```

也可以使用：`pnpm add @gobing-ai/ts-runtime`、`yarn add @gobing-ai/ts-runtime`、`bun add @gobing-ai/ts-runtime`

## README

# @gobing-ai/ts-runtime (英语)

运行时抽象层——平台检测,文件系统,进程执行,配置, 上下文管理、路径公用事业和共享插件/能力核心。 在Node.js、 Bun 上工作过, 和Cloudflare工人 通过一个工厂模式 自动检测运行时间.

`ts-runtime` 脱钩应用程序代码与平台细节. 而不是导入 `node:fs` 或者说 `node:child_process` 消费者直接使用接口(`FileSystem`, (中文(简体) ), `ProcessExecutor`解决 `loadRuntimeFactory()` 启动时。 工厂自动检测站台并接通正确实施—— `createNodeFileSystem` (实数 `node:fs`对于节点/本, `createCfFileSystem` 给工人的 节点文件系统模块被以懒散的方式加载,因此导入软件包对于Worker 捆绑仍然安全.

## 概览

**密钥抽象 :**

| 概念 | 接口 | 包/节点程序 | 云花冲入 |
| --- | --- | --- | --- |
| 运行时间工厂 | `RuntimeFactory` → `loadRuntimeFactory()` | `nodeBunFactory` | `cloudflareWorkersFactory` |
| 文件系统 | `FileSystem` | `createNodeFileSystem()` (同步) `node:fs`(中文(简体) ) | `createCfFileSystem()` (竖起) |
| 进程执行 | `ProcessExecutor` (互动) | `NodeProcessExecutor` —— 说 `run()` 通过执行, `runStreaming()` 通过 `Bun.spawn` | 掷出 |
| 进程登记册 | `ProcessRegistry` (可选) | `InMemoryProcessRegistry` 编号 : `createInMemoryProcessRegistry()` ——列表+订阅所有产卵 | n/a(无进程执行) |
| SQL 数据库 | `createDbAdapter(config)` → `DbAdapter` | Bun SQLite 通过 `@gobing-ai/ts-db` (可选对等点) | 掷出 `D1NotConfiguredError` (D1轮待定) |
| 配置 | `Config` (佐德计划) | YAML + env vars (中文(简体) ) | CONFIG YAML blob + env vars |
| A. 背景情况 | `RuntimeContext` | 服务定位器 | 服务定位器 |
| 路径公用事业 | `SEP`, (中文(简体) ), `basenamePath`, (中文(简体) ), `dirnamePath`, (中文(简体) ), `joinPath`, (中文(简体) ), `resolvePath`, (中文(简体) ), `relativePath`,, , , , , , , , | 移动式(零) `node:*`(中文(简体) ) | 移动式(零) `node:*`(中文(简体) ) |
| Schema 验证 | `loadStructuredConfig` | JSON-Schema + YAML | JSON-Schema + YAML |
| 扩展核心`./extension`(中文(简体) ) | `CapabilityRegistry`, (中文(简体) ), `loadExtensionModules` | 信任加载模块 | —— 说 |
| Bun SQLite 边界(`./bun-sqlite`(中文(简体) ) | `Database` 再出口 | `bun:sqlite` | 无 |
| 追踪 | `SpanContext` | `{ traceId, spanId }` | `{ traceId, spanId }` |

## 建筑

```mermaid
classDiagram
    class RuntimeFactory {
        <<interface>>
        +string runtimeName
        +createFileSystem() FileSystem
        +createProcessExecutor() ProcessExecutor
        +loadConfig() Promise~Config~
        +createDbAdapter(config) Promise~DbAdapter~
    }

    class nodeBunFactory {
        +createFileSystem() createNodeFileSystem()
        +createProcessExecutor() ProcessExecutor
        +loadConfig() Promise~Config~
        +createDbAdapter() Promise~DbAdapter~
    }

    class cloudflareWorkersFactory {
        +createFileSystem() createCfFileSystem()
        +createProcessExecutor() never
        +loadConfig() Promise~Config~
        +createDbAdapter() never
    }

    class FileSystem {
        <<interface>>
        +exists(path) boolean~|~Promise~boolean~
        +readFile(path) string~|~Promise~string~
        +writeFile(path, content) void~|~Promise~void~
        +ensureDir(path) void~|~Promise~void~
        +readDir(path) string[]~|~Promise~string[]~
        +deleteFile(path) void~|~Promise~void~
        +stat(path) FileStat~|~null~|~Promise~FileStat|~
        +resolve(...segments) string
        +getProjectRoot() string
        +readFileStream(path) AsyncIterable<string>▀optional (ADR-021)
        +realPath(path) string▀optional (ADR-022)
    }

    class createNodeFileSystem {
        +readFile(path) string
        +writeFile(path, content) void
        +exists(path) boolean
        +ensureDir(path) void
        +stat(path) FileStat | null
        +getProjectRoot() string
        +readFileStream(path) AsyncIterable<string>
        +realPath(path) string
    }

    class createCfFileSystem {
        +readFile(path) never
        +writeFile(path, content) never
        +exists(path) false
        +ensureDir(path) void
        +stat(path) null
        +getProjectRoot() '/bundle'
    }

    class ProcessExecutor {
        <<interface>>
        +run(options) Promise~ProcessResult~
        +runStreaming(options) PipeProcess
    }

    class NodeProcessExecutor {
        +run(options) Promise~ProcessResult~
        +runStreaming(options) PipeProcess
    }

    class ProcessRegistry {
        <<interface>>
        +listExecutions(filter?) ProcessExecution[]
        +getExecution(id) ProcessExecution?
        +subscribe(listener) unsub
        +begin(input) string
        +update(id, patch) void
        +complete(id, update?) void
        +clear() void
    }

    class InMemoryProcessRegistry {
        +listExecutions(filter?) ProcessExecution[]
        +begin(input) string
        +complete(id, update?) void
    }

    class PipeProcess {
        <<interface>>
        +pid number?
        +stdout ReadableStream?
        +stderr ReadableStream?
        +exited Promise~number?~
        +writeStdin(input) void
        +endStdin() void
        +kill(signal?) void
    }

    class RuntimeContext {
        +RuntimeScope scope
        +RuntimeName runtimeName
        +RuntimeCapabilities capabilities
        +register(key, service) void
        +get(key) T | undefined
        +require(key) T
        +has(key) boolean
        +dispose() Promise~void~
    }

    class Config {
        +AppConfig app
        +DatabaseConfig database
        +LoggingConfig logging
    }

    class SpanContext {
        <<interface>>
        +string traceId
        +string spanId
        +Record~string,string~ baggage?
        +Record~string,string|number|boolean~ attributes?
    }

    RuntimeFactory <|.. nodeBunFactory : implements
    RuntimeFactory <|.. cloudflareWorkersFactory : implements
    FileSystem <|.. createNodeFileSystem : implements
    FileSystem <|.. createCfFileSystem : implements
    ProcessExecutor --> PipeProcess : creates
    ProcessExecutor <|.. NodeProcessExecutor : implements
    ProcessRegistry <|.. InMemoryProcessRegistry : implements
    NodeProcessExecutor ..> ProcessRegistry : optional registry
    nodeBunFactory --> createNodeFileSystem : creates
    nodeBunFactory --> NodeProcessExecutor : creates
    cloudflareWorkersFactory --> createCfFileSystem : creates
    RuntimeContext --> FileSystem : "fileSystem"
    RuntimeContext --> Config : "config"
    RuntimeContext --> ProcessExecutor : "processExecutor"
```

## 如何运作

### 1\. 运行时间选择

`loadRuntimeFactory()` 自动检测平台并返回创建正确 文件系统、 进程执行器和配置 。 使用 `createRuntimeContextFromFactory()` 到电线 一切自动:

```ts
import { createRuntimeContextFromFactory } from '@gobing-ai/ts-runtime';

const ctx = await createRuntimeContextFromFactory();
// ctx.runtimeName → 'node-bun' (auto-detected)
// ctx.capabilities → { hasFilesystem: true, hasProcessExecution: true }
// ctx.require('fileSystem') → canonical FileSystem (createNodeFileSystem)
// ctx.require('config') → Config from config.yaml
```

对于手动控制或同步代码, `createRuntimeContext()` 仍然可用 (折旧-保留后相容性):

```ts
import { createRuntimeContext } from '@gobing-ai/ts-runtime';

const ctx = createRuntimeContext({
    runtimeName: 'node-bun',
    capabilities: { hasFilesystem: true, hasProcessExecution: true, hasPersistentStorage: true },
});
```

### 2\. 服务登记

服务注册为 `RuntimeContext` 并按键访问 :

```ts
ctx.register('db', drizzleAdapter);
ctx.register('cache', redisClient);

const db = ctx.require('db'); // throws if missing
const cache = ctx.get('cache'); // undefined if missing
```

### 3\. 配置

配置从 YAML 中装入环境变量插值和 Zod 验证 :

```yaml
# config.yaml
app:
  name: my-app
  env: ${APP_ENV}
  port: ${PORT}
database:
  url: ${DATABASE_URL}
logging:
  level: debug
```

```ts
import { buildConfigFromYaml } from '@gobing-ai/ts-runtime';

const yaml = await fs.readFile('config.yaml');
const config = buildConfigFromYaml(yaml, {
    overrides: { app: { port: 8080 } },
});
// config.app.port === 8080 (overridden)
// config.logging.level === 'debug' (from YAML)
```

### 4\. 结构化配置+JSON-schema验证

`loadStructuredConfig` 读取 `.json`编号 :`.yaml` 文件和——如果它宣布一个顶级 `$schema` - 验证 回来之前要用这个计谋 此权限已检查规则和工作流程文件 `ts-rule-engine` 财务报告和审定财务报表 `ts-dual-workflow-engine`。 。 。 .

```ts
import { loadStructuredConfig } from '@gobing-ai/ts-runtime';

const config = await loadStructuredConfig('rules.yaml'); // validates against its $schema, throws on violation
const raw = await loadStructuredConfig('rules.yaml', { validateSchema: false }); // skip validation
```

A 类 `StructuredConfigSchemaError` (带有 `violations` 数组 `{ path, message }`)被扔入任意 违反计划.

#### `$schema` 参考样式

配置文件可以有三种方式来命名其方案. **优先选择捆绑的包指定符** - 没错 最安全且最有表现的默认:

| 样式 | 示例 | 决议 | 页:1 |
| --- | --- | --- | --- |
| **软件包指定符** (建议) | `$schema: "@gobing-ai/ts-rule-engine/schemas/rule-file.schema.json"` | 决心通过 `node_modules` 通过模块解析器,然后从磁盘读取 | 没有网络,没有路径猜想;活了起来/pnpm/monorepo布局. 每个货包中的Schemas船 `schemas/` (宣布为 `files`) (中文(简体) ). **引用值** - YAML 治疗领先 `@` 保留. |
| 相对路径 | `$schema: ./schemas/rule-file.schema.json` | 针对配置文件目录解析 | 本地计时器的罚款; 配置移动时不便 . |
| 远程 URL | `$schema: https://json-schema.org/.../rule-file.schema.json` | 通过 HTTP( S) 获取 - **默认关闭** | SSRF/DoS表面用于第三方配置. 打开 **两者** `{ allowRemote: true }` **财务报告和审定财务报表** (单位:千美元) `fetch` 执行——没有内置获取;呼叫者拥有超时/证书. |

```ts
// Bundled package schema (default path — no extra options needed):
//   $schema: "@gobing-ai/ts-rule-engine/schemas/rule-file.schema.json"
await loadStructuredConfig('rules.yaml');

// Remote schema is refused unless BOTH flags are present:
await loadStructuredConfig('rules.yaml', { allowRemote: true, fetch: myFetch }); // caller-supplied fetch
// { allowRemote: true } alone -> refused (no built-in fetch)
// { fetch: myFetch } alone     -> refused (no explicit opt-in)
```

> **警卫:** 远程计程器默认已禁用 。 解开捆绑的策略 `node_modules` 将验证完全保存在本地 —— 没有外出请求, 也不依赖于 schema 主机 可用性,而且恶意配置无法在内部 URL 中指向验证.

### 5\. 道路公用事业

避免运行时间的可移动路径数学 `node:path` 同样的逻辑在云花岗工人身上起作用 (ADR-008) (英语). 所有函数都使用 POSIX 风格的分隔器; Windows 驱动路径实现正常化和处理 绝对的.

```ts
import {
    SEP, basenamePath, dirnamePath, isAbsolutePath,
    joinPath, normalizeSeparators, relativePath, resolvePath,
    getProcessCwd,
} from '@gobing-ai/ts-runtime';

normalizeSeparators('C:\\Users\\x\\file');  // 'C:/Users/x/file'
SEP;                                          // '/' on POSIX, '\\' on Windows
isAbsolutePath('/abs');                       // true
dirnamePath('/a/b/c.ts');                     // '/a/b'
basenamePath('/a/b/c.ts');                    // 'c.ts'
basenamePath('/a/b/c.ts', '.ts');            // 'c'
joinPath('/a', 'b', 'c');                     // '/a/b/c'
resolvePath('/a/b', '../c');                  // '/a/c'
relativePath('/a/x', '/a/y');                 // '../y'
getProcessCwd();                              // process.cwd() or '/' on Workers
```

### 6\. 扩展核心`@gobing-ai/ts-runtime/extension`(中文(简体) )

这个 `./extension` 子路径显示一个通用域不可知扩展/能力核心,供两者使用 `ts-rule-engine` 财务报告和审定财务报表 `ts-dual-workflow-engine` (ADR-010) (英语). 它共享这一机制——一个打入的登记册 带有源元数据,一个信任加载器,和一个路径守护器——没有任何信息 有关评估者、解决者、行动或警卫。 每个引擎拥有其特定域的种类, 计划,错误类型, 和覆盖语义.

#### 能力登记处

```ts
import { CapabilityRegistry } from '@gobing-ai/ts-runtime/extension';

interface Widget { execute(): void; }
const registry = new CapabilityRegistry<Widget>('widget');

// Register built-ins and extensions with origin metadata.
registry.register('core', coreWidget, 'builtin');
registry.register('ext',  extWidget,  'extension');   // default

registry.has('core');          // true
registry.list();               // ['core', 'ext']          (insertion order)
registry.get('core').execute(); // ok
registry.get('missing');        // throws: Unknown widget: missing

// Introspect origin without throwing.
registry.getEntry('core')?.origin;   // 'builtin'
registry.entries();                   // [['core', { capability, origin: 'builtin' }], ...]
```

#### 扩展加载( 信任加载)

扩展模块是任意代码——负载器默认被禁用并失效关闭:

```ts
import { loadExtensionModules, type ExtensionRef } from '@gobing-ai/ts-runtime/extension';

const refs: ExtensionRef<'actions'>[] = [{
    kind: 'actions',
    path: './ext/slack.ts',
    baseDir: '/abs/path/to/configs',
    sourceName: 'my-config',
}];

// Throws before any import: "declares actions extension … but extensions are disabled"
await loadExtensionModules(refs, { moduleLoader: (p) => import(p) }, register);

// Explicitly opt in.
await loadExtensionModules(refs, {
    allowExtensions: true,
    moduleLoader: (p) => import(p),
}, (ref, extension) => {
    // Engine-provided callback — the loader never chooses a target registry.
    myHost.actions.register(extension.name, extension, 'extension');
});
```

装入器验证默认导出和命名 `extension` 输出。 无效的模块 以源名称、类型和路径上下文来抛出. `moduleLoader` 共有核心 无环境 `import()` 其能力.

#### 路径守护

`assertRelativeExtensionPath` 拒绝绝对路径和 `..` 负载时转弯, 独立 任何发动机的zod计划(深度防御):

```ts
import { assertRelativeExtensionPath } from '@gobing-ai/ts-runtime/extension';

assertRelativeExtensionPath('./ext/my.ts');    // ok
assertRelativeExtensionPath('/etc/evil.ts');   // throws: must be relative
assertRelativeExtensionPath('../escape.ts');   // throws: must not contain ".."
```

字符串级别后卫不能解开同义链接——内部的同义链接 `baseDir` 外出点数 那张支票 用于同链-安全禁闭(ADR-022),提供a `realPath` 罐头化剂 `LoadExtensionsOptions`数字 :

```ts
import { loadExtensionModules } from '@gobing-ai/ts-runtime/extension';
import { createNodeFileSystem } from '@gobing-ai/ts-runtime';

const fs = createNodeFileSystem('/abs/path');
await loadExtensionModules(refs, {
    allowExtensions: true,
    moduleLoader: (p) => import(p),
    realPath: fs.realPath,  // enables symlink confinement check
}, register);
```

何时 `realPath` 装入器将解析路径和 `baseDir`,拒绝 逃避声明目录的符号链接 。 缺勤时(如CF工人),检查会跳出.

### 7\. 文件系统抽象

使用 `createNodeFileSystem()` 一个真正的 `node:fs`\- 备份文件系统(节点/ Bun) 或 `createCfFileSystem()` 云花板工人的树枝:

```ts
import { createNodeFileSystem, createCfFileSystem } from '@gobing-ai/ts-runtime';

// Node.js / Bun — real filesystem (sync node:fs)
const fs = createNodeFileSystem('/path/to/project');
const content = fs.readFile('src/index.ts');     // string
fs.writeFile('output.json', JSON.stringify(data));
fs.ensureDir('tmp/cache');                       // recursive mkdir

// Cloudflare Workers — stub (throws on mutating ops)
const cffs = createCfFileSystem();
cffs.getProjectRoot();   // '/bundle'
cffs.readFile('/x');     // throws: "use D1, KV, or R2"
```

可选的流线和同义链接安全操作 :

```ts
// Stream large files line-by-line (ADR-021) — Node/Bun only.
// The JSONL importer uses this to avoid buffering multi-GB files.
if (fs.readFileStream) {
  for await (const line of fs.readFileStream('data/huge.jsonl')) {
    // process one line at a time
  }
}

// Canonical path resolution for symlink-safe extension confinement (ADR-022).
// The extension loader uses this to verify that a symlink hasn't escaped baseDir.
if (fs.realPath) {
  const real = fs.realPath('/base/extensions/linked.ts');
}
```

两者都是可选的——CF工人根节省略. JSONL进口商回归 `readFile` + 当 `readFileStream` 不存在; 扩展加载器跳过符号链接检查 `realPath` 缺席.

遗产 `getFs()` 编号 : `setFileSystem()` 全球互换, `SyncFileSystem`,和旧文件系统 课程在ADR-019中被删除. 使用 `createNodeFileSystem()`, (中文(简体) ), `createCfFileSystem()`,或 `ctx.require('fileSystem')` 换句话说.

### 8\. 数据库适配器`createDbAdapter`(中文(简体) )

工厂的 `createDbAdapter(config)` 打开一个能满足 `RuntimeDbAdapter` 合同 (运行时的子集 `@gobing-ai/ts-db`是因为 `DbAdapter`)在所配置的路径. **ts- runtime 拥有 连接; 消费者拥有计划** ——返回的适配器已连接但不会迁移. 消费者 由自己的移民组成.

```ts
import { loadRuntimeFactory } from '@gobing-ai/ts-runtime';

const factory = await loadRuntimeFactory();

if (factory.capabilities.hasSqlDatabase) {
    const adapter = await factory.createDbAdapter({ url: '.spur/spur.db' });
    // adapter is connected — apply YOUR migrations here, then use DAOs.
    adapter.close();
}
```

在云花岗工人, `capabilities.hasSqlDatabase` 实值 `false` 财务报告和审定财务报表 `createDbAdapter` 丢出已键入 `D1NotConfiguredError` ——该方法存在于界面上,因此消费者代码与前置兼容 当D1轮轮船时不需要改变.

**依赖性说明( 可选对等点) :** `@gobing-ai/ts-db` 被宣布为 **选项 `peerDependency`** 联 合 国 `ts-runtime` (ADR-012增编),非经常受扶养人——经常条目 将创造明显的循环(`ts-db` 取决于 `ts-runtime`)和强制安装 `ts-db` (加上 `drizzle-orm` 包括工人捆绑和从未碰过SQL的应用程序. 工厂界面使用结构化 `RuntimeDbAdapter` 类型( 本地定义) ts- db `DbAdapter` 通过结构分型满足; `nodeBunFactory.createDbAdapter` 负载 `ts-db` 通过a 字元动态 `import()` 在运行时间.

**谁必须安装它:** 只有消费者打电话 `nodeBunFactory.createDbAdapter` 在节点/Bun上 - 安装 `@gobing-ai/ts-db` 自己来`bun add @gobing-ai/ts-db`) (中文(简体) ). 消费者不需要它 (单位:千美元)`capabilities.hasSqlDatabase` 实值 `false`; 方法抛出 `D1NotConfiguredError`) (中文(简体) ).

**捆绑( Bundling )`Bun --compile` / 建造 / Vite :** 字面规格保留 `ts-db` 隐形袋, 这样 `Bun --compile` 可以折叠成独立的二进制. 如果您在不同的运行时间捆绑, 请标记 `@gobing-ai/ts-db` `external` 以保存动态导入.

**失败模式 :** 若为 `@gobing-ai/ts-db` 没有或没有出口 `createDbAdapter` (不兼容) 版本), `createDbAdapter` 丢出已键入 `DbModuleNotInstalledError` (附有决议) 链条为 `cause`而不是一个生的 `MODULE_NOT_FOUND`。 。 。 .

### 9\. 慷慨处置

`RuntimeContext.dispose()` 电话 `dispose()` 用于执行模式的每个注册服务:

process.on ('SIGTERM', async () {{{} ctx.dispose () 正在等待; process.exit (0); (中文(简体) ); \* ;

````

## Usage

### Install

```bash
bun add @gobing-ai/ts-runtime
````

### 基本设置( 节点/ Bun)

```ts
import { createRuntimeContextFromFactory } from '@gobing-ai/ts-runtime';

const ctx = await createRuntimeContextFromFactory();
const fs = ctx.require('fileSystem');
fs.writeFile('hello.txt', 'Hello, world!');
```

### 云花岗工人

```ts
import { createCfFileSystem, createRuntimeContext } from '@gobing-ai/ts-runtime';

export default {
    async fetch(request: Request, env: Env): Promise<Response> {
        const ctx = createRuntimeContext({
            runtimeName: 'cloudflare-workers',
            capabilities: { hasFilesystem: false, hasProcessExecution: false, hasPersistentStorage: false },
            services: { fileSystem: createCfFileSystem() },
        });
        // ...
    },
};
```

### 配置插入插入

```ts
import { buildConfigFromYaml, buildConfigFromObject } from '@gobing-ai/ts-runtime';

// From YAML file
const config = buildConfigFromYaml(yamlText);

// From plain object (programmatic config)
const config = buildConfigFromObject({
    app: { name: 'api', env: 'production', port: 3000 },
    database: { url: ':memory:' },
});
```

/ 从 YAML 文件 cont 配置 = 构建 ConfigFrom Yaml( yamlText) ;

/ 从平面对象( 程序配置) const 配置 = 构建对象({) app:{名称:"api", env:"生产",端口:3000}, 数据库 : {url: ': memory:'}, \* ;

````

### Process execution

`ProcessExecutor` is the canonical interface for process execution. `NodeProcessExecutor` is the concrete implementation wrapping `execa` (buffered) and `Bun.spawn` (streaming):

```ts
import { NodeProcessExecutor, createInMemoryProcessRegistry } from '@gobing-ai/ts-runtime';

// Optional: shared registry so every run/runStreaming is listable (spur#0264 / M1).
const registry = createInMemoryProcessRegistry();
const exec = new NodeProcessExecutor({ defaultTimeout: 30_000, registry });

// Buffered — captures stdout/stderr, no throw on non-zero
const result = await exec.run({
    command: 'git',
    args: ['status', '--short'],
    cwd: '/path/to/repo',
    rejectOnError: true,
    // Optional registry metadata (defaults: run → source 'one-shot')
    label: 'git.status',
});

console.log(result.stdout);          // 'M src/index.ts\n'
console.log(`Duration: ${result.durationMs}ms`);

// Streaming — interactive subprocess with stdin control
const proc = exec.runStreaming({
    command: 'cat',
    source: 'supervisor', // tag supervised agent loops
    agentId: 'alpha-claude',
});
proc.writeStdin('hello\n');
proc.endStdin();
const exitCode = await proc.exited; // 0

// Watch list snapshot + live subscription
console.log(registry.listExecutions());
const unsub = registry.subscribe((event) => {
    if (event.type === 'started' || event.type === 'exited') {
        console.log(event.type, event.execution.id, event.execution.command);
    }
});
unsub();
````

`rejectOnError: true` 丢出非零出口. `OutputPolicy` 控件 缓冲对流输出 . `ProcessOptions` 支持 `timeout`潜入 潜入 潜入, 最大输出, 强制强制, 可选同步 `onOutput({ stream, chunk, timestamp })` 和登记册栏`source`, (中文(简体) ), `teamId`, (中文(简体) ), `agentId`) (中文(简体) ). `onOutput` 在返回时观察活块 `ProcessResult` 保留 完全缓冲出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出 观察错误与孩子隔离。 输入相同 `ProcessRegistry` 进入每个应当执行人 出现在一个监视列表中;没有注册,行为不变.

#### 截止日期、取消和流程组封装(Unix)

在Unix,一个有限度的 `timeout` 或提供 `signal` 将运行置于执行人拥有下 进程组封装: 儿童作为进程组领袖被剥离 执行器运行一个终止序列( 组) `SIGTERM`页:1 `killGraceMs` 优待——默认 5000毫秒——然后分组 `SIGKILL`而升级是由群体活泼驱动的,从不由 领导先退出。 因此,完成就收获了在领导者存活下来的后代 持有继承的输出管道或 SQLite 写入交易, 所以 `run()` 完成为 a 屏蔽屏障:在解决后,没有留下任何拥有的后人(最有利于 SIGKILL-免疫成员——在有限度的解决后升级放弃). `runStreaming` 保留 直接儿童语义学,不提供群体阻塞.

-   `timeout: number` ——正整数截止日期为毫秒;过期报告 `outcome: 'timeout'`。 。 。 .
-   `timeout: null` - 无限制; 覆盖有限度 `defaultTimeout` 从 `ProcessExecutorConfig`。 。 。 .
-   省略 - 继承 `defaultTimeout` (这可能是 `null`(无限制).
-   `timeout: 0`负,分数, `NaN`, (中文(简体) ), `±Infinity`,或超出本地计时器范围—— 以 `TypeError` 产卵前; `killGraceMs` 必须是非负整数.
-   中止 `signal` ——报告 `outcome: 'cancelled'`;最后期限绝不是取消 反之为相. 截止和中止 输入一个升级路径, 所以呼叫者不能武装一个 对同一个孩子的竞争监督.

`ProcessResult.outcome` (单位:千美元)`'exit' | 'timeout' | 'cancelled' | 'signal' | 'error'`,别名为 `ProcessExitReason`说明运行结束的原因; `process.exited` 事件也有同样的原因. 在Windows上(并且当没有提供最后期限或信号时),execa的直接孩子超时和 取消语义应用不变:只有直接孩子被杀死,结果为 从结果中分类.

Cloudflare 工人不披露执行过程;检查 `factory.capabilities.hasProcessExecution` 先说.

这个 `ProcessExecutor` 康斯特(值别名用于 `NodeProcessExecutor`, (中文(简体) ), `BunSyncProcessExecutor`, (中文(简体) ), 财务报告和审定财务报表 `BunPipeProcessSpawner` 被保存为已贬值的后相兼容包装。 偏爱 `NodeProcessExecutor` 或者说 `nodeBunFactory.createProcessExecutor()` 在新代码.

**折旧状态(0087 R7任务):** 同步调用器现在默认为未耗用 `NodeSyncProcessExecutor` (节点) `spawnSync`(b) —— `identity.ts` 被迁移出 `BunSyncProcessExecutor` 默认. `BunSyncProcessExecutor` 财务报告和审定财务报表 `BunPipeProcessSpawner` 仍然为导出折旧,并在下一个主要版本中被删除。 进程组 控制装置在 `src/process-group.ts` (摘自: `process-executor.ts`,任务0087 R8——纯运动,行为不变.

### 扩展文本(用于遥测)

```ts
import type { SpanContext } from '@gobing-ai/ts-runtime';

function processRequest(ctx: SpanContext) {
    console.log(`Trace: ${ctx.traceId}, Span: ${ctx.spanId}`);
}
```

## 常见问题

### @gobing-ai/ts-runtime 是什么？

@gobing-ai/ts-runtime-为邦,节点和Cloudflare工人的运行时抽象\.

### 如何安装 @gobing-ai/ts-runtime？

在项目目录运行 npm install @gobing-ai/ts-runtime，或使用 pnpm add / yarn add / bun add。

### @gobing-ai/ts-runtime 支持 TypeScript 吗？

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

### @gobing-ai/ts-runtime 支持 ESM 还是 CommonJS？

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

### @gobing-ai/ts-runtime 可以商用吗？

@gobing-ai/ts-runtime 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @gobing-ai/ts-runtime 的下载量有多少？

根据 npm 官方下载统计，@gobing-ai/ts-runtime 在 2026/10/17 – 2026/11/15 这 30 天内被下载 5,149 次，日均约 172 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gobing-ai/ts-runtime 还在维护吗？

最新版本 0\.7\.1 发布于 2026/10/25（22 天前）；至今共发布 137 个版本，其中过去 12 个月发布了 137 个；首次发布于 2026/05/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

