dsh-runtime-log 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,53 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.2 - 2026-11-20
6
+
7
+ - 写入性能:drain 每周期将待写队列拼为单次批量写,替代逐条顺序 appendFile;在途记账改为条数与字节,行为与故障路径不变。
8
+ - 脱敏增强:新增 URL userinfo(`scheme://user:pass@host`)、凭据关键词后引号值、停用词保护的关键词后空格裸值三类规则;README 同步更新覆盖范围与残余缺口。
9
+ - Windows 权限:启动时检测日志目录位于 `%PUBLIC%` 之下并限频告警;README 说明 `0o600` 模式位在 Windows 上不生效、权限继承目录 ACL。
10
+ - 保留策略:`closing` 集合加入上限(4096),淘汰项回落到保守保护方向,不会被误删;注册表注释明确其去重用途而非安全边界。
11
+ - 修复 acquire 路径上 rootState exporter 的无效分配。
12
+
13
+ ## 0.1.1 - 2026-11-17
14
+
15
+ - 修复常见环境变量及请求头凭据脱敏漏项和正常诊断文本误脱敏;名称截断会标记记录。
16
+ - 修复 Windows 目录别名及 worker_threads 同 PID 未知 run 的活动保护,并避免 maxFiles 较大时启动即清理少量旧日志。
17
+ - 旧运行清理与 writer drain 共用 `drainTimeoutMs` 期限;扫描未结算时,关闭中的 run 继续受保护直到清理结束。
18
+ - 本地 profile 验收改为独占随机临时目录,仅清理本次创建的文件。
19
+ - 公开安装包附带 MIT LICENSE;测试与验收资料仍仅保留本地。
20
+ - 明确记录 Node 24 原生 Error 堆栈访问器的安全限制与保留策略非硬配额边界。
21
+ - v0.1.0 标签及已发布附件保持原样。
22
+
23
+ ## 0.1.0 - 2026-11-11
24
+
25
+ 首个本地发布版本,源码以 ES module 直接运行,无编译步骤和第三方运行时依赖。
26
+
27
+ - 本地保存 Cordis WARN/ERROR,过滤 INFO/DEBUG。
28
+ - 有界编码队列与在途容量、严格 UTF-8 单条/单段上限、文件轮转及旧运行清理。
29
+ - 处理重复 fiber、跨 root 序号、关闭超时及异步清理竞态。
30
+ - 安全读取原始值与原生 Error,常见凭据模式尽力脱敏。
31
+ - 已在真实 desktop profile 安装、完整重启并验证日志落盘。
32
+
33
+ ### 兼容范围
34
+
35
+ - DSH:仅 0.2.2-rc.1;Cordis:由宿主提供的 4.1.0。
36
+ - Node.js:>=24.16.0 <25,实测 24.16.0 与 24.21.0。
37
+ - 平台:Windows x64;其它版本或平台不在本次支持声明内。
38
+
39
+ ### 已知限制
40
+
41
+ - 不收集全部 console、stdout/stderr、工具结果或历史 session。
42
+ - 惰性/accessor Error 堆栈可能不可用;自由文本脱敏不保证完全覆盖。
43
+ - 异常退出可损失末尾缓冲;超时的 run 保留到进程退出。
44
+ - 16 文件为默认的尽力保留目标,活跃或状态不明的进程日志优先保护。
45
+
46
+ ### 复现发布
47
+
48
+ 以下为原 v0.1.0 标签的发布复现步骤,该历史标签包含测试资料;在其源码目录执行:
49
+
50
+ npm pack --ignore-scripts
51
+ git archive --format=zip --prefix=dsh-runtime-log-0.1.0/ --output=dsh-runtime-log-0.1.0-source.zip v0.1.0
52
+
53
+ 源码和发布包均不包含运行日志、profile 配置、凭据或临时测试产物。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 翁铱樊
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # Temporary Holding Version
1
+ # dsh-runtime-log
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 为 DeepSeek Harness(DSH)提供本地 Cordis `WARN` / `ERROR` 日志留存,便于在重启后排查运行问题。日志以 JSONL 写入本机,并用有界队列、文件轮转及旧运行清理限制资源占用。
4
+
5
+ [GitHub Release](https://github.com/WforEvery/dsh-runtime-log/releases) · [npm](https://www.npmjs.com/package/dsh-runtime-log) · [变更记录](CHANGELOG.md) · [问题反馈](https://github.com/WforEvery/dsh-runtime-log/issues) · [MIT 许可证](LICENSE)
6
+
7
+ > 当前修复版本为 **0.1.2**。这是第三方 DSH 插件,不是 DeepSeek 官方产品。它只在下列支持环境中发布和验证;部署前请阅读隐私及限制说明。
8
+
9
+ ## 功能
10
+
11
+ - 通过 Cordis logger exporter 接收 WARN 和 ERROR,异步写入本地 JSONL 文件;INFO / DEBUG 不保存。
12
+ - 限制队列记录数、队列字节数及单条编码大小,到达单段文件上限时轮转。
13
+ - 按运行实例区分文件,并在启动时尝试清理可确认已关闭的旧运行日志。
14
+ - 对常见凭据文本格式进行尽力脱敏;不遍历或序列化任意参数对象。
15
+ - 只使用 Node.js 内置模块,无第三方运行时依赖;插件本身不发起网络请求或上传日志。
16
+
17
+ ## 兼容性
18
+
19
+ 以下为 **0.1.2 的支持声明**,并非对其它版本或平台的兼容承诺。
20
+
21
+ | 组件 | 支持范围 | 已验证环境 |
22
+ | --- | --- | --- |
23
+ | DSH | **仅 `0.2.2-rc.1`** | 0.1.2 本地冒烟验收;0.1.1 隔离宿主验收;0.1.0 曾通过真实桌面完整重启 |
24
+ | Cordis | **`4.1.0`** | 由上述 DSH 版本提供 |
25
+ | Node.js | **`>=24.16.0 <25`** | `24.16.0`、DSH 自带的 `24.21.0` |
26
+ | 操作系统与架构 | **Windows x64** | Windows 桌面宿主 |
27
+
28
+ Node.js 区间对应 Node 24 发行线,区间内并非每个补丁版本都逐一测试。其它 DSH / Cordis 版本、Node.js 20–23 或 25+、macOS、Linux 和 Windows ARM64 均不在支持范围内。
29
+
30
+ 宿主门禁信息位于 [package.json](package.json):`engines.node`、`engines.dsh`、`dsh.bundle.platforms`、`os` 与 `cpu`。 [cordis.patch.yml](cordis.patch.yml) 只负责将插件 bundle 插入 profile,不承载版本门禁。升级 DSH 前应重新核对兼容性。
31
+
32
+ ## 安装
33
+
34
+ 需要能管理目标 DSH profile 及其依赖的环境。开始前确认 profile,并备份其依赖清单、锁文件和用户 patch。
35
+
36
+ 1. 在目标 profile 目录安装指定版本:
37
+
38
+ ```powershell
39
+ pnpm add dsh-runtime-log@0.1.2 --ignore-scripts
40
+ ```
41
+
42
+ 2. 在该 profile 的 `dsh.profile.bundles` 中添加 `dsh-runtime-log`,保留原有 bundle:
43
+
44
+ ```json
45
+ {
46
+ "dsh": {
47
+ "profile": {
48
+ "bundles": ["existing-bundle", "dsh-runtime-log"]
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ 3. 在 profile 目录安装依赖并完整退出、重新启动 DSH:
55
+
56
+ ```powershell
57
+ pnpm install --ignore-scripts
58
+ ```
59
+
60
+ 4. 确认目标 profile 加载了该 bundle,再检查日志目录是否生成运行文件。插件包声明了 DSH 版本和 Windows x64 限制,宿主可能拒绝不兼容环境。
61
+
62
+ 插件运行时不会修改 profile。安装和 profile 组合属于宿主管理操作;本插件不会自动启用或更改其它 bundle。
63
+
64
+ ## 配置
65
+
66
+ 不提供配置时使用下表默认值。默认日志目录为 `$DSH_HOME/runtime-log`;未设置有效的 `DSH_HOME` 时为 `~/.dsh/runtime-log`,Windows 上通常位于 `%USERPROFILE%/.dsh/runtime-log`。
67
+
68
+ | 字段 | 默认值 | 范围与含义 |
69
+ | --- | --- | --- |
70
+ | `directory` | 默认日志目录 | 绝对路径,支持 `~`、`~/` 和 `~\`;相对路径回退默认目录 |
71
+ | `maxFileBytes` | `5242880`(5 MiB) | 单段文件上限,64 KiB–100 MiB |
72
+ | `maxFiles` | `4` | 每次运行保留段数,2–32,包含当前段 |
73
+ | `maxQueueRecords` | `2000` | 待写及在写记录合计上限,1–50000 |
74
+ | `maxQueueBytes` | `1048576`(1 MiB) | 待写及在写编码字节合计上限,4 KiB–16 MiB |
75
+ | `maxEntryBytes` | `16384`(16 KiB) | 单条记录编码上限,256 B–`min(256 KiB, maxQueueBytes)` |
76
+ | `flushIntervalMs` | `200` | 批量写入周期,25–60000 ms |
77
+ | `drainTimeoutMs` | `1000` | 卸载时等待排空的期限,25–10000 ms |
78
+
79
+ 数值配置要求安全整数;超出范围会被限制到允许边界,类型无效时使用默认值。单条记录的实际大小还受队列和文件上限约束。
80
+
81
+ 可在用户 patch 中按 bundle 的 `id` 覆盖设置:
82
+
83
+ ```yaml
84
+ - id: dsh-runtime-log
85
+ config:
86
+ directory: "D:/dsh-logs"
87
+ maxFileBytes: 5242880
88
+ maxFiles: 4
89
+ maxQueueRecords: 2000
90
+ maxQueueBytes: 1048576
91
+ maxEntryBytes: 16384
92
+ flushIntervalMs: 200
93
+ drainTimeoutMs: 1000
94
+ ```
95
+
96
+ 路径仅为示例,目录必须允许 DSH 宿主写入。用户 patch 中的 `config` 整体替换较早层配置;未填写字段由插件补默认值。同一进程内,相同日志目录共享写入器,首次创建时的参数生效。建议同一目录只配置一套参数。
97
+
98
+ ## 日志与保留
99
+
100
+ 文件名为 `host-<pid>-<uuid>.jsonl`,轮转段使用 `.1`、`.2` 等后缀。默认每次运行最多保留 4 段,每段最多 5 MiB。
101
+
102
+ 每行是一条 UTF-8 JSON 记录:
103
+
104
+ ```json
105
+ {"time":"2026-01-01T00:00:00.000Z","level":"warn","name":"example-plugin","message":"Example warning"}
106
+ ```
107
+
108
+ | 字段 | 含义 |
109
+ | --- | --- |
110
+ | `time` | UTC ISO 8601 接收时间 |
111
+ | `level` | `warn` 或 `error` |
112
+ | `name` | logger 名称;超长名称会截断并标记记录 |
113
+ | `message` | 有界格式化并尽力脱敏后的消息 |
114
+ | `stack` | 可选堆栈;不可安全读取时写入 `[Stack unavailable]` |
115
+ | `truncated` | 内容被截断时为 `true` |
116
+
117
+ 普通对象不展开为完整结构,通常用 `[Object]` 等标记表示。为避免执行用户自定义的 getter 或 `Error.prepareStackTrace`,插件只读取可安全取得的数据属性。**在支持范围内的 Node 24 中,标准原生 Error 的 `stack` 是 accessor,通常会记录为 `[Stack unavailable]`,而不保存真实堆栈。**这是有意的安全与可诊断性取舍,不表示日志中必定包含错误堆栈。
118
+
119
+ 启动和停止时,插件尝试写入 `dsh-runtime-log` WARN marker,消息分别以 `[plugin-event:start]` 和 `[plugin-event:stop]` 开头。Marker 与业务日志共用队列,队列压力下也可能丢失;停止 marker 中的计数是关闭前快照,不是最终排空结果。插件卸载可等待启动时的日志清理,但写入排空和清理共用 `drainTimeoutMs` 截止时间;期限内未完成则卸载返回,关闭中的 run 继续受保护,直到清理最终结算。
120
+
121
+ 启动时的旧运行清理以 **16 个可识别日志文件** 为尽力目标:不同 PID 的旧运行需要确认进程已退出;同一 PID 的旧运行需要由当前 isolate 确认已完全关闭。只处理严格匹配命名规则的常规文件,并按旧运行组的时间由早到晚清理。当前、关闭中及状态未知的运行均受保护;来自其它 worker isolate、无法确认关闭状态的同 PID run 会保守保留。当前首段尚未出现在扫描中时,只为它预留一个文件位置,不预留未来轮转段。16 个文件是尽力目标而非硬磁盘配额;并发活动进程、慢扫描、worker isolate 或后续轮转都可能使目录暂时超过目标,单纯增大 `maxFiles` 不会再让旧运行预算归零。
122
+
123
+ ## 隐私与限制
124
+
125
+ - **覆盖范围有限。** 仅保存插件加载后经过 Cordis logger 的 WARN / ERROR;不会收集全部 `console`、stdout / stderr、工具结果或会话历史,也不追补加载前的记录。
126
+ - **脱敏并非秘密清除保证。** 插件会处理已知凭据格式,但任意自由文本、未知编码、截断边界或尚未识别的格式仍可能含秘密。显式 `Authorization` / `Proxy-Authorization` 字段从 scheme 到该行末尾整体遮盖,同一行后续的无关诊断文本也可能被隐藏;Cookie 与 Set-Cookie 字段整体遮盖。为减少英文诊断误报,scheme 规则保留 `Basic authentication failed` 和 `Bearer authentication required` 两类已识别文案。URL userinfo(`scheme://user:pass@host`)中的 `user:pass@` 整段遮盖,仅识别冒号形式,`host:port` 不受影响。凭据关键词(password / token / secret 等)后直接跟随的引号值会遮盖;后跟空格裸值时也遮盖,但为保持诊断可读,裸值若以常见英文停用词开头(如 `password is required`、`token was invalid`)则跳过——代价是以停用词开头或无凭据关键词的值仍可能漏过。插件不会主动读取会话或凭据,其他组件传给 logger 的文本仍可能包含敏感信息。
127
+ - **Windows 文件权限继承目录 ACL。** 插件创建文件使用的 `0o600` 模式位在 Windows 上不生效,日志文件的实际权限完全继承目录 ACL。请勿将 `directory` 配置到 `%PUBLIC%` 等公共或共享位置;插件在创建写入器时检测到目录位于 `%PUBLIC%` 之下会向 stderr 输出限频告警。建议日志目录仅当前用户可读。
128
+ - **日志可能丢失。** 队列满时会丢弃记录,超长内容会截断;强制结束、断电、关闭超时或 I/O 错误都可能使末尾记录缺失。异步写入不提供崩溃持久性保证。
129
+ - **写入错误会停用对应写入器。** 文件创建、写入或轮转失败后不会无限重试,会尝试向 stderr 输出限频提示。需修复目录或磁盘问题后重载插件或重启宿主。
130
+ - **日志按敏感诊断材料保管。** 文件为本地文本,插件不加密。分享前应人工检查并删除令牌、Cookie、个人信息及其它敏感内容;使用合适的目录权限。
131
+ - **不是安全审计或恢复系统。** 请勿将其作为审计完整性、故障恢复或安全隔离的唯一依据。
132
+
133
+ ## 卸载
134
+
135
+ 从目标 profile 的 bundle 列表和依赖清单移除本包,按 profile 流程更新依赖后完整退出并重启 DSH。卸载不会自动删除现有日志;确认宿主已不再写入后,可自行归档或清理。
136
+
137
+ ## 问题反馈
138
+
139
+ 请在 [GitHub Issues](https://github.com/WforEvery/dsh-runtime-log/issues) 提交插件、DSH、Cordis 与 Node.js 版本、系统架构、复现步骤及经过人工检查的最小日志片段。请勿上传完整 profile、会话存档或凭据。兼容范围以实测和发布说明为准。
140
+
141
+ ## 许可证
142
+
143
+ 本项目采用 [MIT License](LICENSE)。软件按现状(AS IS)提供,不附带明示或默示担保;具体授权、免责和责任限制以许可证全文为准。
@@ -0,0 +1,7 @@
1
+ # dsh-runtime-log bundle layer.
2
+ # Add "dsh-runtime-log" to a profile's dsh.profile.bundles list and fully
3
+ # restart DSH. This project never edits a real profile.
4
+ - insert:
5
+ - id: dsh-runtime-log
6
+ name: dsh-runtime-log
7
+ config: {}
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "dsh-runtime-log",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Local Cordis WARN/ERROR persistence for DSH with bounded queue, rotation and cross-run retention.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "cordis.patch.yml",
14
+ "README.md",
15
+ "CHANGELOG.md",
16
+ "LICENSE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=24.16.0 <25",
20
+ "dsh": "0.2.2-rc.1"
21
+ },
22
+ "dsh": {
23
+ "bundle": {
24
+ "patch": "./cordis.patch.yml",
25
+ "platforms": [
26
+ "win32"
27
+ ]
28
+ }
29
+ },
30
+ "dependencies": {},
31
+ "os": [
32
+ "win32"
33
+ ],
34
+ "cpu": [
35
+ "x64"
36
+ ],
37
+ "license": "MIT",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "https://github.com/WforEvery/dsh-runtime-log.git"
41
+ }
42
+ }
package/src/index.js ADDED
@@ -0,0 +1,284 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { types } from 'node:util';
6
+ import { createLogSink } from './log-sink.js';
7
+ import { pruneRuns } from './retention.js';
8
+
9
+ export const name = 'dsh-runtime-log';
10
+ export const MAX_TOTAL_FILES = 16;
11
+ export const DEFAULTS = Object.freeze({
12
+ directory: '', maxFileBytes: 5 * 1024 * 1024, maxFiles: 4,
13
+ maxQueueRecords: 2000, maxQueueBytes: 1024 * 1024,
14
+ maxEntryBytes: 16 * 1024, flushIntervalMs: 200, drainTimeoutMs: 1000,
15
+ });
16
+ // Shared across plugin copies so one process owns one sink per directory.
17
+ // This is a deduplication registry, not a security boundary: Symbol.for is
18
+ // reachable by any same-process code, which could equally delete log files
19
+ // directly. Every consumer already fails safe against a tampered registry
20
+ // (shape-checked in registry(), conservative retention on unexpected shapes).
21
+ const REGISTRY_KEY = Symbol.for('dsh.runtime-log.registry');
22
+ const DEDUP_LIMIT = 4096;
23
+ const MAX_CLOSED_RUN_BASES = 4096;
24
+ // Defensive cap against unbounded growth across repeated drain timeouts.
25
+ // Eviction is safe in the conservative direction: a timed-out run removed
26
+ // from `closing` is never added to closedRunBases, so isRunActive falls back
27
+ // to its "active" answer and the run stays protected from pruning.
28
+ const MAX_CLOSING_STATES = 4096;
29
+ const FALLBACK_INTERVAL_MS = 30_000;
30
+ let lastFallbackAt = 0;
31
+
32
+ function reportFailure() {
33
+ const now = Date.now();
34
+ if (now - lastFallbackAt < FALLBACK_INTERVAL_MS) return;
35
+ lastFallbackAt = now;
36
+ try { process.stderr.write('[dsh-runtime-log] local log write failed; check the configured log directory.\n'); } catch {}
37
+ }
38
+ // On Windows the 0o600 creation mode has no effect and file access follows the
39
+ // directory ACL, so a log directory under %PUBLIC% exposes logs to every
40
+ // local account. Warn once per interval when the configured directory is there.
41
+ const PUBLIC_WARN_INTERVAL_MS = 30_000;
42
+ let lastPublicWarnAt = 0;
43
+ function warnIfPubliclyReadable() {
44
+ const now = Date.now();
45
+ if (now - lastPublicWarnAt < PUBLIC_WARN_INTERVAL_MS) return;
46
+ lastPublicWarnAt = now;
47
+ try { process.stderr.write('[dsh-runtime-log] log directory is under a public location; local logs may be readable by other accounts. Configure a private directory.\n'); } catch {}
48
+ }
49
+ function isUnderPublicRoot(directory, env) {
50
+ try {
51
+ const publicRoot = env?.PUBLIC;
52
+ if (typeof publicRoot !== 'string' || !publicRoot.trim()) return false;
53
+ const root = path.resolve(expandHome(publicRoot, os.homedir())).toLowerCase();
54
+ const dir = path.resolve(directory).toLowerCase();
55
+ return dir === root || dir.startsWith(root + '\\') || dir.startsWith(root + '/');
56
+ } catch { return false; }
57
+ }
58
+ function expandHome(value, home) {
59
+ if (typeof value !== 'string') return value;
60
+ if (value === '~') return home;
61
+ return value.startsWith('~/') || value.startsWith('~\\') ? path.join(home, value.slice(2)) : value;
62
+ }
63
+ function resolveHome(env, home) {
64
+ let configured;
65
+ try { configured = env?.DSH_HOME; } catch {}
66
+ const selected = typeof configured === 'string' && configured.trim() ? configured : path.join(home, '.dsh');
67
+ return path.resolve(expandHome(selected, home));
68
+ }
69
+ export function resolveDirectory(configured, env = process.env, home = os.homedir()) {
70
+ if (typeof configured === 'string' && configured.trim()) {
71
+ const expanded = expandHome(configured, home);
72
+ if (path.isAbsolute(expanded)) return path.resolve(expanded);
73
+ }
74
+ return path.join(resolveHome(env, home), 'runtime-log');
75
+ }
76
+ function dataField(object, key) {
77
+ try {
78
+ if (!object || typeof object !== 'object' || types.isProxy(object)) return undefined;
79
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
80
+ return descriptor && Object.hasOwn(descriptor, 'value') ? descriptor.value : undefined;
81
+ } catch { return undefined; }
82
+ }
83
+ function bounded(value, fallback, min, max) {
84
+ return Number.isSafeInteger(value) ? Math.max(min, Math.min(max, value)) : fallback;
85
+ }
86
+ function normalize(raw) {
87
+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) && !types.isProxy(raw) ? raw : null;
88
+ const field = key => dataField(source, key);
89
+ const queueBytes = bounded(field('maxQueueBytes'), DEFAULTS.maxQueueBytes, 4096, 16 * 1024 * 1024);
90
+ let directory;
91
+ try { directory = resolveDirectory(field('directory')); } catch { directory = path.join(os.tmpdir(), 'dsh-runtime-log'); }
92
+ return {
93
+ directory,
94
+ maxFileBytes: bounded(field('maxFileBytes'), DEFAULTS.maxFileBytes, 64 * 1024, 100 * 1024 * 1024),
95
+ maxFiles: bounded(field('maxFiles'), DEFAULTS.maxFiles, 2, 32),
96
+ maxQueueRecords: bounded(field('maxQueueRecords'), DEFAULTS.maxQueueRecords, 1, 50_000),
97
+ maxQueueBytes: queueBytes,
98
+ maxEntryBytes: bounded(field('maxEntryBytes'), Math.min(DEFAULTS.maxEntryBytes, queueBytes), 256, Math.min(256 * 1024, queueBytes)),
99
+ flushIntervalMs: bounded(field('flushIntervalMs'), DEFAULTS.flushIntervalMs, 25, 60_000),
100
+ drainTimeoutMs: bounded(field('drainTimeoutMs'), DEFAULTS.drainTimeoutMs, 25, 10_000),
101
+ };
102
+ }
103
+ function canonicalize(directory) {
104
+ const resolved = path.resolve(directory);
105
+ const realpath = typeof realpathSync.native === 'function' ? realpathSync.native : realpathSync;
106
+ try { return path.resolve(realpath(resolved)); } catch {}
107
+ let current = resolved;
108
+ const suffix = [];
109
+ for (let i = 0; i < 64; i++) {
110
+ const parent = path.dirname(current);
111
+ if (parent === current) break;
112
+ suffix.unshift(path.basename(current));
113
+ current = parent;
114
+ try { return path.resolve(path.join(realpath(current), ...suffix)); } catch {}
115
+ }
116
+ return resolved;
117
+ }
118
+ function registry() {
119
+ try {
120
+ const found = globalThis[REGISTRY_KEY];
121
+ if (found?.sinks instanceof Map) {
122
+ if (!(found.closing instanceof Set)) found.closing = new Set();
123
+ if (!(found.closedRunBases instanceof Set)) found.closedRunBases = new Set();
124
+ return found;
125
+ }
126
+ } catch {}
127
+ const value = { sinks: new Map(), closing: new Set(), closedRunBases: new Set() };
128
+ try { Object.defineProperty(globalThis, REGISTRY_KEY, { value, configurable: true, writable: true }); } catch {}
129
+ return value;
130
+ }
131
+ function makeExporter(state, rootState) {
132
+ return { export(message) {
133
+ try {
134
+ if (!message || typeof message !== 'object' || types.isProxy(message)) return;
135
+ const type = dataField(message, 'type');
136
+ if (type !== 'warn' && type !== 'error') return;
137
+ const sequence = dataField(message, 'sn');
138
+ if (Number.isSafeInteger(sequence)) {
139
+ if (rootState.seen.has(sequence)) return;
140
+ rootState.seen.add(sequence);
141
+ rootState.order.push(sequence);
142
+ if (rootState.order.length > DEDUP_LIMIT) rootState.seen.delete(rootState.order.shift());
143
+ }
144
+ state.sink.capture(message);
145
+ } catch { reportFailure(); }
146
+ } };
147
+ }
148
+ function makeState(directory, config, reg) {
149
+ if (isUnderPublicRoot(directory, process.env)) warnIfPubliclyReadable();
150
+ const filePath = path.join(directory, 'host-' + process.pid + '-' + randomUUID() + '.jsonl');
151
+ const sink = createLogSink({ filePath, ...config, onError: reportFailure });
152
+ const state = { directory, filePath, sink, refs: 0, roots: new Map(), retention: null, drainTimeoutMs: config.drainTimeoutMs };
153
+ // Run UUIDs are unique inside this process, so activity is matched by the run
154
+ // basename instead of by directory string. Two case spellings of a Windows
155
+ // directory that did not exist at apply time become different registry keys
156
+ // while still naming one real directory; a string comparison would let a
157
+ // live aliased run be treated as dead and deleted.
158
+ const activeFilePaths = [
159
+ ...Array.from(reg.sinks.values()).map(item => item.filePath),
160
+ ...Array.from(reg.closing).map(item => item.filePath),
161
+ ];
162
+ const isRunActive = (pid, base) => {
163
+ if (pid !== process.pid) return false;
164
+ for (const item of reg.sinks.values()) {
165
+ if (path.basename(item.filePath) === base) return true;
166
+ }
167
+ for (const item of reg.closing) {
168
+ if (path.basename(item.filePath) === base) return true;
169
+ }
170
+ if (reg.closedRunBases.has(base)) return false;
171
+ // This same PID may belong to a worker isolate whose registry is not visible
172
+ // here. Only runs this isolate has fully settled may be pruned.
173
+ return true;
174
+ };
175
+ // Target the files that actually exist: reserve one slot only while the
176
+ // current run has not written its first segment, never all future rotations.
177
+ state.retention = Promise.resolve().then(() => pruneRuns({
178
+ directory, currentFilePath: filePath, activeFilePaths,
179
+ maxTotalFiles: MAX_TOTAL_FILES, reserveCurrentRun: true,
180
+ currentProcessPid: process.pid, pruneCurrentProcessRuns: true, isRunActive,
181
+ })).catch(() => null);
182
+ return state;
183
+ }
184
+ function lifecycle(state, phase, stats) {
185
+ const parts = ['[plugin-event:' + phase + ']'];
186
+ if (stats) {
187
+ parts.push('accepted=' + stats.accepted, 'written=' + stats.written, 'dropped=' + stats.dropped,
188
+ 'lost=' + stats.lost, 'errors=' + stats.errors, 'rotations=' + stats.rotations,
189
+ 'buffered=' + stats.buffered.records, 'inFlight=' + stats.inFlight.records,
190
+ 'disabled=' + stats.disabled, 'timedOut=' + stats.timedOut);
191
+ }
192
+ state.sink.capture({ type: 'warn', name, args: [parts.join(' ')] });
193
+ }
194
+ async function closeState(reg, state) {
195
+ const closeDeadline = Date.now() + state.drainTimeoutMs;
196
+ if (reg.sinks.get(state.directory) === state) reg.sinks.delete(state.directory);
197
+ reg.closing.add(state);
198
+ // Bounded defense: an evicted timed-out run falls back to isRunActive's
199
+ // conservative answer (never positively closed, never pruned).
200
+ if (reg.closing.size > MAX_CLOSING_STATES) reg.closing.delete(reg.closing.values().next().value);
201
+ let snapshot;
202
+ try { snapshot = state.sink.stats(); } catch {}
203
+ lifecycle(state, 'stop', snapshot);
204
+ let definitelySettled = false;
205
+ try {
206
+ await state.sink.close();
207
+ const finalStats = state.sink.stats();
208
+ definitelySettled = finalStats.timedOut !== true && finalStats.inFlight?.records === 0;
209
+ } catch { reportFailure(); }
210
+ // Retention may block on a slow or unavailable filesystem. Do not let that
211
+ // background scan extend the Cordis disposer beyond the sink's close deadline.
212
+ // Keep the run in `closing` until the scan settles, then record that this
213
+ // isolate has positively established it as closed and eligible for pruning.
214
+ if (definitelySettled) {
215
+ const rememberClosedRun = () => {
216
+ if (!reg.closing.delete(state)) return;
217
+ const base = path.basename(state.filePath);
218
+ reg.closedRunBases.delete(base);
219
+ reg.closedRunBases.add(base);
220
+ if (reg.closedRunBases.size > MAX_CLOSED_RUN_BASES) {
221
+ reg.closedRunBases.delete(reg.closedRunBases.values().next().value);
222
+ }
223
+ };
224
+ const retentionSettled = Promise.resolve(state.retention).then(rememberClosedRun, rememberClosedRun);
225
+ const remainingMs = Math.max(0, closeDeadline - Date.now());
226
+ if (remainingMs > 0) {
227
+ let deadlineTimer;
228
+ await Promise.race([retentionSettled, new Promise((resolve) => { deadlineTimer = setTimeout(resolve, remainingMs); })]);
229
+ if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);
230
+ } else {
231
+ void retentionSettled;
232
+ }
233
+ }
234
+ // A timeout cannot cancel an issued OS call; keep its run protected until process exit.
235
+ }
236
+ function acquire(ctx, config) {
237
+ const reg = registry();
238
+ const directory = canonicalize(config.directory);
239
+ let state = reg.sinks.get(directory);
240
+ if (!state) {
241
+ state = makeState(directory, config, reg);
242
+ reg.sinks.set(directory, state);
243
+ lifecycle(state, 'start');
244
+ }
245
+ state.refs++;
246
+ let root = ctx;
247
+ try { if (ctx.root && (typeof ctx.root === 'object' || typeof ctx.root === 'function')) root = ctx.root; } catch {}
248
+ let rootState = state.roots.get(root);
249
+ if (!rootState) {
250
+ rootState = { refs: 0, seen: new Set(), order: [], exporter: null };
251
+ state.roots.set(root, rootState);
252
+ rootState.exporter = makeExporter(state, rootState);
253
+ }
254
+ rootState.refs++;
255
+ let logger;
256
+ let disposeExporter;
257
+ try {
258
+ logger = ctx.logger;
259
+ disposeExporter = logger.exporter(rootState.exporter);
260
+ } catch {
261
+ rootState.refs--;
262
+ if (rootState.refs === 0) state.roots.delete(root);
263
+ state.refs--;
264
+ if (state.refs === 0) void closeState(reg, state).catch(() => {});
265
+ return () => {};
266
+ }
267
+ let releasePromise;
268
+ return () => {
269
+ if (releasePromise) return releasePromise;
270
+ releasePromise = (async () => {
271
+ try { disposeExporter?.(); } catch { reportFailure(); }
272
+ rootState.refs--;
273
+ if (rootState.refs <= 0 && state.roots.get(root) === rootState) state.roots.delete(root);
274
+ state.refs--;
275
+ if (state.refs <= 0) await closeState(reg, state);
276
+ })();
277
+ return releasePromise;
278
+ };
279
+ }
280
+ export function apply(ctx, rawConfig) {
281
+ let config;
282
+ try { config = normalize(rawConfig); } catch { config = normalize(null); }
283
+ try { ctx.effect(() => acquire(ctx, config), name); } catch { reportFailure(); }
284
+ }