@lingda-ai/dsh-plugin-replay 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # 黑匣子 · dsh-plugin-replay
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
+ > 灵搭「空港」套件的记录岗位。把一次会话还原成**时间轴上的每一步**:
4
+ > 做了什么、花了多少、成没成。只记结构,不记内容;默认全本地。
5
+
6
+ 装上之后,右侧栏多一个「黑匣子」页签。三个视图:
7
+
8
+ | 视图 | 回答的问题 |
9
+ |---|---|
10
+ | **时间轴** | 这一次会话,每一步干了什么、花了多少、哪一步失败了 |
11
+ | **热点** | 钱花在谁身上——按"谁触发的模型调用"归因,按模型看调用量 |
12
+ | **对比** | 两次会话并排:步数、成本、失败数差在哪,结论由规则给出 |
13
+
14
+ ## 安装
15
+
16
+ ```bash
17
+ # 在 DSH profile 目录里
18
+ dsh plugin add @lingda-ai/dsh-plugin-replay
19
+ ```
20
+
21
+ 或写进 profile 的 `dsh.profile.bundles`:
22
+
23
+ ```json
24
+ { "dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-base", "@lingda-ai/dsh-plugin-replay"] } } }
25
+ ```
26
+
27
+ 面板是右栏 tab(`replay.blackbox`),最窄 300px 可用。
28
+
29
+ ## 它记什么、不记什么
30
+
31
+ **记**(结构):
32
+
33
+ - 每一步的坐标:轮 `turn` / 步 `step`
34
+ - 动作类型:模型调用 / 工具调用 / 上下文压缩
35
+ - 计量:输入、缓存命中、缓存写、输出 token
36
+ - 金额:四档计价(未缓存输入 / 缓存命中 / 缓存写 / 输出),算不出就留 `null` + 原因
37
+ - 成败:工具是否报错、错误码、耗时
38
+ - 归因:这一步的钱是被哪个工具的结果"推"出来的(与账本同一算法)
39
+ - 会话元数据:标题、工作区目录名、起止时间
40
+
41
+ **不记**(内容,这是硬边界):
42
+
43
+ | 不记 | 原因 |
44
+ |---|---|
45
+ | prompt / completion 文本 | 内容即隐私,回放不需要 |
46
+ | 工具参数与返回值 | 参数里常带代码与路径 |
47
+ | 错误 message | 常含绝对路径与代码片段,只保留错误码 |
48
+ | 绝对路径 | 只留最后一级目录名 |
49
+ | git email 等身份 | 默认不落盘 |
50
+
51
+ 未在内置白名单里的工具名会被哈希成 `tool#a1b2c3`,避免私有工具名外泄;
52
+ 账本等内置工具保留真名,否则热点视图没有意义。
53
+
54
+ ## 落盘
55
+
56
+ ```
57
+ ~/.dsh/ops/replay/<会话id>.jsonl # 每会话一个文件,追加写
58
+ ```
59
+
60
+ - 热路径零 IO:事件先入队,500ms 合并写一次
61
+ - 单会话超过 2000 步后不再逐条记,改为每 10 步合成一行(`op:"aggr"`)
62
+ - 单文件超过 8MB 封盘,写一条截断标记
63
+ - 默认保留 90 天,按文件修改时间裁剪(不读内容)
64
+ - 会话结束时写一条 `sum` 行(列表页与"已收场"的唯一依据)
65
+
66
+ 行格式见 [docs/replay-contract.md](docs/replay-contract.md)。
67
+
68
+ ## 权限与兼容
69
+
70
+ | 项 | 事实 |
71
+ |---|---|
72
+ | 落盘路径 | `~/.dsh/ops/replay/`,只写这一个目录 |
73
+ | 网络 | **无任何外网请求**,只提供本机 `GET /dsh-ops/api` 只读接口 |
74
+ | 写入范围 | 只写自己目录;不写 profile、不写配置、不改宿主状态 |
75
+ | 读取范围 | 可选读取 `~/.dsh/ledger/pricing.json`(账本的费率覆盖文件);不存在就用内置价表 |
76
+ | 宿主接口 | `session/event`、`session/disposed`、`webServer.register`;缺一个就降级,不会半死不活 |
77
+ | Node | ≥ 22.6 |
78
+ | 计价 | 与账本同源(官方页面 2026-11-19);算不出的模型显示 `—`,绝不用 0 冒充 |
79
+
80
+ **为什么读账本的 pricing.json**:两个插件对同一会话报出两个金额是信任级事故。
81
+ 黑匣子不依赖账本的代码(保持单包可装),但共用同一份费率覆盖文件——改价只有一处。
82
+
83
+ ## 与其它两件工具的关系
84
+
85
+ - **账本**:管"这一会话花了多少"。黑匣子管"这些钱是哪一步、哪个动作产生的",金额口径完全一致。
86
+ - **塔台**:管"谁在跑、谁卡住"。黑匣子管"跑过的这一次到底发生了什么"。
87
+
88
+ 三者共用一个目录习惯:`~/.dsh/<产品>/`。
89
+
90
+ ## 开发
91
+
92
+ ```bash
93
+ node --test test/*.test.mjs # 36 项断言,含隐私门禁
94
+ node scripts/check-listing.mjs # 收录前离线自检
95
+ node scripts/verify-real-host.mjs --profile replay-check # 真机链路
96
+ ```
97
+
98
+ 测试里最重要的一组是 `test/privacy.test.mjs`:塞满密钥、绝对路径、SQL、代码片段的事件进去,
99
+ 然后读**落盘原文**逐个确认这些东西不在文件里。这组失败就不该发版。
100
+
101
+ ## 许可
102
+
103
+ Apache-2.0 © LingDaAi
@@ -0,0 +1,7 @@
1
+ # @lingda-ai/dsh-plugin-replay —— 黑匣子:会话回放
2
+ #
3
+ # 一个 insert 行即可挂载。Host 半订阅 session/event 落盘 span/sum,
4
+ # 并提供 /dsh-ops/api 只读查询;Client 半在右侧栏注册 replay.blackbox tab。
5
+ - insert:
6
+ - id: lingda-replay
7
+ name: '@lingda-ai/dsh-plugin-replay'
@@ -0,0 +1,81 @@
1
+ # 回放数据契约 v1(供其它插件与工具只读消费)
2
+
3
+ 文件:`~/.dsh/ops/replay/<safeSessionId>.jsonl`,一行一个 JSON 对象,追加写。
4
+ `v: 1`,**只增字段、不删字段**;破坏性变更会提升 `v`。
5
+
6
+ ## 三种行
7
+
8
+ | `t` | 含义 | 何时写 |
9
+ |---|---|---|
10
+ | `span` | 一步 | 事件到达并入队后,500ms 内合并落盘 |
11
+ | `sum` | 会话合计 | 会话结束(`session/disposed`)时写一条,文件末尾 |
12
+ | `trunc` | 截断标记 | 单文件达到 8MB 上限时写一次,之后不再追加 |
13
+
14
+ ## span 行
15
+
16
+ ```jsonc
17
+ {
18
+ "v": 1,
19
+ "t": "span",
20
+ "sid": "session-bc835d33",
21
+ "at": 1795243411871, // 毫秒时间戳
22
+ "turn": 16, // 无轮次概念的全局事件可缺省
23
+ "step": 14,
24
+ "op": "model.call", // model.call | tool.call | compaction | aggr
25
+ "model": "deepseek-v4-flash", // 仅 model.call
26
+ "tool": "read_file", // 仅 tool.call;白名单外为 "tool#a1b2c3"
27
+ "driver": "read_file", // 仅 model.call:上一步谁的结果推动了这次调用
28
+ "meas": [{ "unit": "token.input", "value": 2288 }],
29
+ "cost": { "amount": 0.0126, "currency": "CNY" }, // 算不出时为 null
30
+ "costReason": null, // "no-rate" | "usage-incomplete" | "no-usage"
31
+ "saved": 0.0039, // 缓存命中的相对节省(同费率口径);不可算为 null
32
+ "durMs": 1820, // 仅 tool.call:call → result 的耗时;结果未回为 null
33
+ "ok": true, // 仅 tool.call:成败;结果未回为 null
34
+ "errCode": null, // 只存错误码,绝不存 message
35
+ "eid": "9f3c1a7b2d4e5f60", // 幂等键
36
+ "aggr": 10 // 仅 op="aggr":被合并的原始条数
37
+ }
38
+ ```
39
+
40
+ `op="aggr"` 表示"早期明细已被折叠":超过 2000 步后每 10 步合成一行,
41
+ `cost` 与 `meas` 为这 10 步之和。读到 `aggr` 的消费方应显示"已折叠 N 步",
42
+ 而不是把它当成一步。
43
+
44
+ ## sum 行
45
+
46
+ ```jsonc
47
+ {
48
+ "v": 1, "t": "sum", "sid": "session-…",
49
+ "at": 1795243875205,
50
+ "title": "右侧栏插件整改",
51
+ "cwdName": "dsh-plugin-tower",
52
+ "startedAt": 1795239000000, "endedAt": 1795243875205,
53
+ "turns": 18, "steps": 138, "calls": 141, "failures": 2,
54
+ "cost": { "amount": 1.6538, "currency": "CNY", "knownEntries": 138, "unknownEntries": 0 },
55
+ "saved": { "amount": 65.07, "currency": "CNY" },
56
+ "tokens": { "input": 55953, "output": 135001, "cacheRead": 66393600, "cacheWrite": 0 },
57
+ "topDrivers": [{ "key": "read_file", "amount": 0.42, "calls": null }],
58
+ "outcome": "completed", // completed | failed
59
+ "eventsSeen": 412, "eventsDeduped": 0,
60
+ "truncated": false,
61
+ "redact": "v1"
62
+ }
63
+ ```
64
+
65
+ ## 消费方约定
66
+
67
+ 1. **只读**:不写这个目录、不 import 本包。文件不在或 `v !== 1` 就当"没有这个能力",
68
+ 不要当成 0 或把错误抛给用户。
69
+ 2. **金额不可加总跨口径**:`cost.amount` 只包含已知费率的条目;
70
+ `cost.unknownEntries > 0` 时,展示必须带"其中 N 条费率未知",否则读者会以为合计就是全部。
71
+ 3. **`cost: null` 不等于 0**:它是"算不出来"。不要用同类均值补,也不要在图上当 0 画。
72
+ 4. **`aggr` 不是一步**:占比、单步均价这类指标要按 `aggr` 的 `aggr` 字段还原权重。
73
+ 5. **`ok: null` 是"结果未知"**:会话被中断时会出现,不要算作成功,也不要算作失败。
74
+ 6. **不要把 `tool#xxxxxx` 还原**:它是被刻意哈希的私有工具名,原值不在文件里。
75
+
76
+ ## 稳定性
77
+
78
+ - 新增字段只追加,语义不变。
79
+ - `saved`、`driver`、`aggr` 为 0.1.0 起就有的字段;更早的版本不存在该文件格式。
80
+ - 已知取舍:`sum` 只在会话正常结束时写。进程被强杀时会话只有 `span` 没有 `sum`,
81
+ 消费方应据此显示"进行中/未收场",而不是"数据缺失"。
package/index.js ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @lingda-ai/dsh-plugin-replay —— Host 半。
3
+ *
4
+ * 职责三件,都很窄:
5
+ * 1. 订阅 `session/event`,把事件投影成回放行(span),入队后合并写盘;
6
+ * 2. 会话结束写一条 sum 行(列表页与"已收场"的唯一依据);
7
+ * 3. 提供只读 `GET /dsh-ops/api`(sessions / replay / hotspot / compare)。
8
+ *
9
+ * 硬约束(沿用账本与塔台用事故换来的三条):
10
+ * - 采集只订阅,不 emit、不修改事件;
11
+ * - 热路径零 IO,任何异常都吞掉并计数,绝不让宿主的主流程失败;
12
+ * - 缺服务就降级(没有 webServer 就不注册路由),不半死不活。
13
+ */
14
+ import { createReplayStore, defaultReplayDir } from './lib/store.js'
15
+ import { createProjector } from './lib/projector.js'
16
+ import { loadRates, defaultPricingPath } from './lib/rates.js'
17
+ import { createApi, handleRequest, API_PREFIX } from './lib/route.js'
18
+
19
+ export const name = '@lingda-ai/dsh-plugin-replay'
20
+
21
+ /**
22
+ * 不强制依赖任何服务。
23
+ *
24
+ * 这一点与塔台不同:塔台没有 webServer 就完全没用,所以它 inject 了。
25
+ * 黑匣子的**核心是记录**,面板只是读法。没有 webServer 时它仍然应该安静地记账
26
+ * (比如 acp / 纯终端 profile),否则"没装 web 前端"会变成"什么都没记"。
27
+ * 路由能力在 apply 里按存在性注册。
28
+ */
29
+ export const inject = []
30
+
31
+ const SERVICE_KEY = 'replay'
32
+
33
+ export function apply(ctx, config = {}) {
34
+ const store = createReplayStore({
35
+ dir: config.dir ?? defaultReplayDir(),
36
+ maxSpans: config.maxSpans,
37
+ maxBytes: config.maxBytes,
38
+ flushMs: config.flushMs,
39
+ retentionDays: config.retentionDays,
40
+ })
41
+ const rates = loadRates({ pricingPath: config.pricingPath ?? defaultPricingPath() })
42
+ const projector = createProjector({ rates, toolWhitelist: config.toolWhitelist })
43
+ const api = createApi({ store })
44
+
45
+ // 启动即清理过期分片:按文件名与 mtime,不读内容。
46
+ try {
47
+ store.prune()
48
+ } catch {}
49
+
50
+ /** 会话结束:把未完成的工具调用补成"结果未知",再写 sum。 */
51
+ function closeSession(session) {
52
+ const sid = session?.id
53
+ if (typeof sid !== 'string' || sid.length === 0) return
54
+ try {
55
+ const tail = projector.flushPending(sid)
56
+ if (tail.length > 0) store.append(sid, tail)
57
+ const meta = projector.metaOf(sid) ?? {}
58
+ const summary = store.summarize(sid)
59
+ const totals = summary?.totals ?? null
60
+ const startedAt = meta.firstAt ?? totals?.firstAt ?? null
61
+ const endedAt = meta.lastAt ?? totals?.lastAt ?? Date.now()
62
+ const sum = {
63
+ at: endedAt,
64
+ title: meta.title ?? null,
65
+ cwdName: meta.cwdName ?? null,
66
+ startedAt,
67
+ endedAt,
68
+ turns: totals?.turns ?? 0,
69
+ steps: totals?.steps ?? 0,
70
+ calls: totals?.calls ?? 0,
71
+ failures: totals?.failures ?? 0,
72
+ cost: totals?.cost ?? { amount: null, currency: null, knownEntries: 0, unknownEntries: 0 },
73
+ saved: totals?.saved ?? { amount: null, currency: null },
74
+ tokens: totals?.tokens ?? null,
75
+ topDrivers: summary?.byTool?.slice(0, 5) ?? [],
76
+ outcome: totals && totals.failures > 0 ? 'failed' : 'completed',
77
+ eventsSeen: meta.emitted ?? 0,
78
+ eventsDeduped: meta.deduped ?? 0,
79
+ truncated: summary?.truncated === true,
80
+ redact: 'v1',
81
+ }
82
+ store.writeSum(sid, sum)
83
+ } catch {
84
+ /* 收口失败不影响别的会话 */
85
+ } finally {
86
+ projector.forget(sid)
87
+ }
88
+ }
89
+
90
+ try {
91
+ ctx.on('session/event', (session, event) => {
92
+ try {
93
+ const sid = session?.id ?? session?.sessionId
94
+ const rows = projector.onEvent(sid, event, session)
95
+ if (rows.length > 0) store.append(sid, rows)
96
+ } catch {
97
+ /* 单条事件解析失败:跳过,不影响后续 */
98
+ }
99
+ })
100
+ } catch {
101
+ /* 老宿主没有该事件:面板仍可看历史文件,只是不再新增 */
102
+ }
103
+
104
+ try {
105
+ ctx.on('session/disposed', (session) => closeSession(session))
106
+ } catch {}
107
+
108
+ const route = {
109
+ kind: 'prefix',
110
+ path: API_PREFIX,
111
+ handler: (req, res) => handleRequest(api, req, res),
112
+ }
113
+
114
+ const cleanup = () => {
115
+ try {
116
+ store.close()
117
+ } catch {}
118
+ }
119
+
120
+ // 路由:有 webServer 才有 HTTP 查询(面板要用),没有就只做落盘。
121
+ try {
122
+ const webServer = typeof ctx.get === 'function' ? ctx.get('webServer') : ctx.webServer
123
+ if (webServer && typeof webServer.register === 'function') {
124
+ if (typeof ctx.effect === 'function') ctx.effect(() => webServer.register(route))
125
+ else {
126
+ webServer.register(route)
127
+ ctx.on('dispose', cleanup)
128
+ }
129
+ }
130
+ } catch {
131
+ /* 没有路由能力:只做落盘,不提供服务 */
132
+ }
133
+
134
+ if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
135
+ else ctx.on('dispose', cleanup)
136
+
137
+ // 给同进程的其它插件/工具一个只读入口(可选消费,不承诺稳定)。
138
+ try {
139
+ if (typeof ctx.provide === 'function') {
140
+ ctx.provide(SERVICE_KEY, { read: store.read, summarize: store.summarize, list: store.listSessions })
141
+ }
142
+ } catch {}
143
+ }
144
+
145
+ /** 仅供离线测试:不参与宿主装配。 */
146
+ export const __internal = { API_PREFIX, defaultReplayDir }