@lingda-ai/dsh-plugin-ledger 0.1.3 → 0.1.5

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.
@@ -0,0 +1,248 @@
1
+ /**
2
+ * @lingda-ai/ledger —— 浏览器半(右侧栏 tab)**源码**
3
+ *
4
+ * 注意:本文件不是发布产物。发布入口是 `lib/client.js`,由
5
+ * `node scripts/build-client.mjs` 从本文件 + panel-view.js + panel-path.js +
6
+ * tool-size.js 打包成宿主要求的 loader 形态(`window.__ModuleLoader__.load`)。
7
+ * 手工改 `lib/client.js` 会在下次构建时被覆盖。
8
+ *
9
+ * 为什么必须有这一步(真机崩溃换来的):
10
+ * dsh-client-modules 的 Node 半侧把每个包的 `client.js` **原样拼接**成一个
11
+ * combo 脚本(`/plugins/??a/client.js,b/client.js&rev=…`),浏览器按 classic
12
+ * script 解析。所以客户端入口里不能出现任何 `import` / `export` 语句,
13
+ * 否则整页抛 `SyntaxError: Cannot use import statement outside a module`,
14
+ * 连宿主一起带崩。0.1.4 就是直接发布了 ESM 源码,一重启就崩。
15
+ *
16
+ * 已核实的契约(源码逐条对过,勿凭记忆改):
17
+ *
18
+ * 1) 类型登记 @ dsh-client-ui-sidebar-right
19
+ * ctx.sidebarRightTabs.register(definition) → disposer
20
+ * definition: { id, kind, title(address), priority?, patterns?, canOpen?, guide?, multiple?, keepMounted? }
21
+ * guide entry: { id, order, title(), description?(), icon?, commandId? }
22
+ *
23
+ * 2) 正文/标题 seat @ 同一包(keyed,session scope,key = type.id)
24
+ * - 'sidebar.right.pane.tab'
25
+ * - 'sidebar.right.pane.tab.title'
26
+ * 宿主自带的注册形态(sidebar-right 自己的 guide 就是这么写的):
27
+ * ctx.slots.inject('<seat>', () => ctx.slots.register({ name: '<seat>', key: ID }, Component))
28
+ *
29
+ * 3) React 来自宿主模块表(`require("react")`)。本文件在 Node 侧(单测、脚本)
30
+ * 走动态 import('react');打进 client.js 后由构建产物通过 __setReactLoader
31
+ * 注入 factory 拿到的 require。两条路都失败时退回"只登记类型、不挂正文"。
32
+ *
33
+ * 取数通道(已接,细节见 docs/spikes.md C-3):
34
+ * 数据在 Host 的 ctx.ledger 上,浏览器进程拿不到;Host 把只读快照写成
35
+ * 工作区里的 JSON,这里用 `ctx.remote.workspaceFiles` 的 stat/read 读回。
36
+ * 接入点集中在 createFetchView() 一处。
37
+ *
38
+ * 约定(dsh-client-modules):客户端模块是 lazy factory,副作用只能发生在 apply() 内。
39
+ */
40
+
41
+ /** 本实现的身份,也是两个 keyed seat 的 key。 */
42
+ const LEDGER_ID = '@lingda-ai/ledger'
43
+ /** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
44
+ const LEDGER_KIND = 'ledger.cost'
45
+
46
+ /** 面板用到的 seat 名,抽出来避免字符串散落。 */
47
+ const SEAT_BODY = 'sidebar.right.pane.tab'
48
+ const SEAT_TITLE = 'sidebar.right.pane.tab.title'
49
+
50
+ /**
51
+ * React 取用方式:默认走动态 import(Node 侧单测/脚本)。
52
+ * 构建成 client.js 后,产物在 factory 里用宿主模块表的 `require('react')` 覆盖它——
53
+ * 浏览器里没有裸 `import('react')` 能解析的相对路径,动态 import 必然失败。
54
+ * @type {() => Promise<any>}
55
+ */
56
+ // #region react-loader-default
57
+ let reactLoader = async () => {
58
+ const mod = await import('react')
59
+ return mod.default ?? mod ?? null
60
+ }
61
+ // #endregion react-loader-default
62
+
63
+ /** 只给构建产物用:把 React 换成宿主模块表给的 require。 */
64
+ export function __setReactLoader(fn) {
65
+ if (typeof fn === 'function') reactLoader = fn
66
+ }
67
+
68
+ import { panelRelativePath } from './panel-path.js'
69
+ import {
70
+ makeLedgerBody,
71
+ makeLedgerTitle,
72
+ renderPayload,
73
+ formatAmount,
74
+ formatTokens,
75
+ formatShare,
76
+ formatClock,
77
+ shortId,
78
+ sourceLabel,
79
+ } from './panel-view.js'
80
+
81
+
82
+ /** 会话 id 太长时截断成 chip 能放下的样子。 */
83
+
84
+ /**
85
+ * 面板取数的唯一注入点:读 Host 落在工作区里的只读快照。
86
+ *
87
+ * 通道已核实(@deepseek-ai/dsh-api-workspace-files 的生成 remote 声明):
88
+ * list(scopeId, path, signal?) → RemoteResult<WorkspaceDirectoryListing>
89
+ * stat(scopeId, path, signal?) → RemoteResult<WorkspaceFileStat>(带 absolutePath)
90
+ * read(scopeId, absolutePath, range, signal?) → RemoteResult<WorkspaceFileText>
91
+ * 相对路径以 Session 的 cwd 为基准,所以客户端**不需要知道**工作区绝对路径:
92
+ * 先用相对路径 stat 换出 absolutePath,再 read。
93
+ *
94
+ * 返回形状:
95
+ * null → 还没有快照(Host 未开启或尚未落盘)
96
+ * { error: '...' } → 通道/解析失败,面板显示原因
97
+ * payload → Host 写的 JSON(version / totals / topSources / sources)
98
+ *
99
+ * @param {any} ctx - 浏览器侧 cordis 上下文
100
+ * @returns {(sessionId: string, opts?: { signal?: AbortSignal }) => Promise<any>}
101
+ */
102
+ export function createFetchView(ctx) {
103
+ return async function fetchView(sessionId, opts = {}) {
104
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return null
105
+ const files = ctx?.remote?.workspaceFiles
106
+ if (!files || typeof files.stat !== 'function' || typeof files.read !== 'function') {
107
+ return { error: '宿主未提供 workspaceFiles 通道' }
108
+ }
109
+ const relative = panelRelativePath(sessionId)
110
+
111
+ let stat
112
+ try {
113
+ stat = await files.stat(sessionId, relative, opts.signal)
114
+ } catch (error) {
115
+ return { error: stringifyError(error) }
116
+ }
117
+ if (!stat?.ok) return null // 文件不存在=尚未落盘,不是错误
118
+ const absolutePath = stat.value?.absolutePath
119
+ if (typeof absolutePath !== 'string') return null
120
+ // 快照可能被写坏/过大:超过上限直接拒绝,避免把整份文件拖进内存
121
+ const bytes = stat.value?.bytes
122
+ if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
123
+
124
+ let page
125
+ try {
126
+ page = await files.read(sessionId, absolutePath, { offset: 0, limit: 400 }, opts.signal)
127
+ } catch (error) {
128
+ return { error: stringifyError(error) }
129
+ }
130
+ if (!page?.ok) return { error: '读取快照失败' }
131
+ const text = page.value?.text
132
+ if (typeof text !== 'string') return { error: '快照内容为空' }
133
+ if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
134
+
135
+ try {
136
+ const parsed = JSON.parse(text)
137
+ return parsed && typeof parsed === 'object' ? parsed : { error: '快照格式无法识别' }
138
+ } catch {
139
+ return { error: '快照不是合法 JSON(可能正写到一半)' }
140
+ }
141
+ }
142
+ }
143
+
144
+ /** 把任意抛出物变成一句话。 */
145
+ function stringifyError(error) {
146
+ if (error instanceof Error) return error.message
147
+ if (typeof error === 'string') return error
148
+ return '未知错误'
149
+ }
150
+
151
+ /** CNY 用 ¥,其它币种保留原符号 + 代码。 */
152
+
153
+ /**
154
+ * 正文组件。用 createElement 而不引 JSX,避免给独立仓库引入构建链。
155
+ * @param {any} React - 宿主的 React
156
+ * @param {(sid: string, opts?: object) => Promise<any>} fetchView
157
+ */
158
+
159
+ /**
160
+ * 渲染已取到的快照。
161
+ *
162
+ * 从组件里抽出来是为了可测:SSR 不跑 effect,组件首帧永远是"读取中",
163
+ * 只有把渲染当纯函数,才能在测试里断言四档金额、明细、预算条真的画出来了。
164
+ * @param {any} React
165
+ * @param {any} view - 快照 payload
166
+ * @param {string|null} sessionId
167
+ * @param {any} head - 已在组件侧建好的头部(含刷新按钮)
168
+ */
169
+
170
+ /** 一行 label / value,两个渲染入口共用。 */
171
+
172
+ /** 标题组件:chip 上的实时文案(不做金额,避免每次事件都改布局)。 */
173
+
174
+ /** @param {import('@deepseek-ai/cordis').Context} ctx */
175
+ export async function apply(ctx) {
176
+ const tabs = ctx.sidebarRightTabs
177
+ if (!tabs || typeof tabs.register !== 'function') return
178
+
179
+ const definition = {
180
+ id: LEDGER_ID,
181
+ kind: LEDGER_KIND,
182
+ title: () => '账本',
183
+ priority: 'extension',
184
+ guide: [
185
+ {
186
+ id: 'ledger.cost',
187
+ order: 10,
188
+ title: () => '账本',
189
+ description: () => '本会话的 token 用量与成本归因',
190
+ },
191
+ ],
192
+ // 切会话不重建面板体:成本是常驻读数,重建会丢滚动位置
193
+ keepMounted: true,
194
+ }
195
+
196
+ const disposeTab = tabs.register(definition)
197
+ const disposeClose =
198
+ typeof ctx.sidebarRight?.registerCloseHandler === 'function'
199
+ ? ctx.sidebarRight.registerCloseHandler(LEDGER_KIND, () => {})
200
+ : null
201
+
202
+ // 正文与标题:宿主把 seat 声明在 sidebar-right 里,先 inject 再 register
203
+ let disposeBody = null
204
+ let disposeTitle = null
205
+ const slots = ctx.slots
206
+ if (typeof slots?.inject === 'function' && typeof slots.register === 'function') {
207
+ let React = null
208
+ try {
209
+ React = await reactLoader()
210
+ } catch {
211
+ React = null // 宿主没给 React:保持无正文的降级态
212
+ }
213
+ if (React !== null) {
214
+ const fetchView = createFetchView(ctx)
215
+ disposeBody = slots.inject(SEAT_BODY, () =>
216
+ slots.register({ name: SEAT_BODY, key: LEDGER_ID }, makeLedgerBody(React, fetchView)),
217
+ )
218
+ disposeTitle = slots.inject(SEAT_TITLE, () =>
219
+ slots.register({ name: SEAT_TITLE, key: LEDGER_ID }, makeLedgerTitle(React)),
220
+ )
221
+ }
222
+ }
223
+
224
+ const cleanup = () => {
225
+ disposeTitle?.()
226
+ disposeBody?.()
227
+ disposeClose?.()
228
+ disposeTab()
229
+ }
230
+ if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
231
+ else ctx.on('dispose', cleanup)
232
+ }
233
+
234
+ /**
235
+ * 测试可见的内部件。实现都在 panel-view.js(纯展示),
236
+ * 这里重导出,是为了让断言只认 `client.js` 一个入口。
237
+ */
238
+ export const __internal = {
239
+ makeLedgerBody,
240
+ makeLedgerTitle,
241
+ renderPayload,
242
+ formatAmount,
243
+ formatTokens,
244
+ formatShare,
245
+ formatClock,
246
+ shortId,
247
+ sourceLabel,
248
+ }
package/lib/config.js ADDED
@@ -0,0 +1,74 @@
1
+ import { BUILTIN_RATES } from './pricing-table.js'
2
+
3
+ /**
4
+ * 配置默认值。
5
+ *
6
+ * 取舍原则:
7
+ * - 会改变 Agent 行为质量的开关(预算降级、事实推送)默认 **关闭**;
8
+ * - 只读观测(账本)默认开启,但容量有界;
9
+ * - 任何"猜"的字段都不给默认值,宁可为 null。
10
+ */
11
+ export const DEFAULT_CONFIG = Object.freeze({
12
+ ledger: {
13
+ capacity: 2000, // 每个会话保留的账本条目数
14
+ maxSessions: 64, // 同时保留状态的会话上限(LRU 淘汰)
15
+ },
16
+ pricing: {
17
+ currency: 'CNY',
18
+ // 内置官方价(来源与日期见 pricing-table.js),用户配置按单模型深合并覆盖。
19
+ // "provider/model" 或 "model" → {input,output,cacheRead,cacheWrite},单位 元/token
20
+ rates: BUILTIN_RATES,
21
+ // 费率覆盖文件:null = 用默认 ~/.dsh/ledger/pricing.json(不存在就纯用内置价)。
22
+ // 文件里写 元/百万,整条生效或整条拒绝,见 pricing-file.js 的取舍说明。
23
+ file: null,
24
+ },
25
+ budget: {
26
+ limit: null, // null = 不启用预算
27
+ threshold: 0.8, // 触发投递的比例
28
+ downgrade: null, // {provider, model, maxTokens} | null,默认关闭
29
+ },
30
+ trace: {
31
+ enabled: false, // 行为流水默认关闭(隐私优先)
32
+ capacity: 5000,
33
+ maxTextLength: 200, // 摘要截断长度
34
+ // 落盘是二次副作用,必须显式再开一层;开启后写 <cwd>/.dsh/ledger/<sid>.trace.jsonl
35
+ file: {
36
+ enabled: false,
37
+ maxBytes: 4194304, // 单文件 4MB 封顶
38
+ },
39
+ },
40
+ attribution: {
41
+ toolOwners: {}, // 工具名 → 所属插件(唯一可得的归因依据,见 docs/spikes.md)
42
+ },
43
+ // 右侧栏面板的数据通道:Host 把只读快照落成 JSON,浏览器半用 workspace 文件 remote 读回。
44
+ // 默认关闭——写盘是外部副作用,不该由观测默认产生。
45
+ panel: {
46
+ enabled: false,
47
+ dir: '.dsh/ledger', // 相对 process.cwd();也可给绝对路径
48
+ intervalMs: 3000, // 同一会话两次落盘的最小间隔
49
+ maxBytes: 262144, // 超过则只写 totals + topSources
50
+ },
51
+ })
52
+
53
+ function merge(base, patch) {
54
+ if (!patch || typeof patch !== 'object') return base
55
+ const out = { ...base }
56
+ for (const [key, value] of Object.entries(patch)) {
57
+ const current = base[key]
58
+ if (value && typeof value === 'object' && !Array.isArray(value) && current && typeof current === 'object' && !Array.isArray(current)) {
59
+ out[key] = merge(current, value)
60
+ } else if (value !== undefined) {
61
+ out[key] = value
62
+ }
63
+ }
64
+ return out
65
+ }
66
+
67
+ export function resolveConfig(raw) {
68
+ return merge(DEFAULT_CONFIG, raw)
69
+ }
70
+
71
+ /** 预算是否真的可用:有 limit 才算,避免 limit=0 被当成"启用" */
72
+ export function budgetEnabled(config) {
73
+ return typeof config?.budget?.limit === 'number' && config.budget.limit > 0
74
+ }
package/lib/guard.js ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Budget Guard。
3
+ *
4
+ * P-3 探针修正(源码证据见 docs/spikes.md):
5
+ * 原设计想在 agent/request 里把 budget_pressure 塞进"请求参数"让模型读到。
6
+ * 源码事实是:该 waterfall 的返回类型是 LlmCallConfig
7
+ * { provider, model, reasoningEffort?, temperature?, maxTokens?, stop? }
8
+ * 且注释明确 "this waterfall cannot mutate messages"。
9
+ * → 因此 **prompt 事实注入不能走 agent/request**,只能走可持久化的日志通道。
10
+ *
11
+ * 拆分后的两条通道:
12
+ * 通道 A(事实/推送):agent 可读的 budget 事实 → 由宿主注入一个 UserMessage
13
+ * (经 agent.inject,属于 logged channel),**默认关闭**,
14
+ * 需要宿主提供 messageFactory,插件自身不猜消息结构。
15
+ * 通道 B(决策/降级):agent/request 返回替换的 LlmCallConfig(只改路由与预算),
16
+ * 这是真·原生能力,默认关闭。
17
+ *
18
+ * 两条通道都遵守:绝不 throwing、绝不短路 next()。
19
+ */
20
+ import { budgetEnabled } from './config.js'
21
+
22
+ export function createBudgetGuard({ store, config, deliver }) {
23
+ const threshold = config?.budget?.threshold ?? 0.8
24
+ const limit = config?.budget?.limit ?? null
25
+ const downgrade = config?.budget?.downgrade ?? null
26
+ const armed = new Map() // sessionId → 是否已在本轮超限中投递过
27
+
28
+ function spentOf(sessionId) {
29
+ const totals = store.totals(sessionId)
30
+ // 只按已知金额判断;有未知条目时该会话不可判预算
31
+ if (totals.cost.amount === null || totals.cost.unknownEntries > 0) return null
32
+ return totals.cost.amount
33
+ }
34
+
35
+ function evaluate(sessionId, turn, step) {
36
+ if (!budgetEnabled(config)) return null
37
+ const spent = spentOf(sessionId)
38
+ if (spent === null) return null
39
+ const ratio = spent / limit
40
+ if (ratio < threshold) {
41
+ // 回滞:低于 90% 阈值才重新武装,避免在阈值附近反复投递
42
+ if (ratio < threshold * 0.9) armed.delete(sessionId)
43
+ return null
44
+ }
45
+ if (armed.get(sessionId) === true) return null
46
+ armed.set(sessionId, true)
47
+ return {
48
+ spent,
49
+ limit,
50
+ // 币种来自计价层,不在展示层假设
51
+ currency: store.totals(sessionId).cost.currency ?? null,
52
+ remainingRatio: Math.max(0, 1 - ratio),
53
+ suggestion: 'consider_compaction_or_model_downgrade',
54
+ asOfStep: { turn, step },
55
+ }
56
+ }
57
+
58
+ /** 每条账本条目后调用;仅在跨越阈值那一次投递 */
59
+ function onEntry(sessionId, entry) {
60
+ try {
61
+ const fact = evaluate(sessionId, entry.turn, entry.step)
62
+ if (!fact) return
63
+ deliver?.(sessionId, fact)
64
+ } catch {
65
+ // 投递失败不影响采集
66
+ }
67
+ }
68
+
69
+ /** agent/request waterfall:只做降级,不做事实注入 */
70
+ async function onRequest(payload, next) {
71
+ const config0 = await next()
72
+ try {
73
+ if (!downgrade || !budgetEnabled(config)) return config0
74
+ if (!downgrade.provider && !downgrade.model) return config0
75
+ const sessionId = payload?.agent?.session?.id
76
+ if (!sessionId) return config0
77
+ const spent = spentOf(sessionId)
78
+ if (spent === null || spent / limit < threshold) return config0
79
+
80
+ // 已超阈值且用户显式启用降级:替换路由。字段来自 LlmCallConfig,逐项覆盖即可。
81
+ return {
82
+ ...config0,
83
+ provider: downgrade.provider ?? config0.provider,
84
+ model: downgrade.model ?? config0.model,
85
+ maxTokens: downgrade.maxTokens ?? config0.maxTokens,
86
+ }
87
+ } catch {
88
+ // 降级失败必须回退到原配置,宁可超预算也不能让请求崩掉
89
+ return config0
90
+ }
91
+ }
92
+
93
+ /**
94
+ * 会话结束要释放按会话索引的状态。
95
+ * armed 只存 boolean,但它按会话无界增长——长跑进程里就是一条缓慢的内存泄漏。
96
+ */
97
+ function forget(sessionId) {
98
+ armed.delete(sessionId)
99
+ }
100
+
101
+ return { onEntry, onRequest, evaluate, forget }
102
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * 身份线索:跨工具、跨仓库都成立的那几个"事实"。
3
+ *
4
+ * 为什么现在就要做(哪怕只有 DSH 一个 adapter):
5
+ * `actor` / `project` 是**唯一真正时间不可逆**的字段——采集时不记,那段历史就永远缺这个维度,
6
+ * 后面做团队视图再想按人/按项目聚合,只能从零开始积累。字段名可以改,幂等键可以换代,
7
+ * 没采到的线索补不回来。
8
+ *
9
+ * 三个硬约束:
10
+ * 1. 绝不在热路径上 fork 子进程(不许调 `git config`)——只同步读几十字节的配置文件;
11
+ * 2. 绝不把绝对路径写进账本(用户目录结构属于隐私),项目键用 git remote 归一化,兜底用 basename + 短 hash;
12
+ * 3. 任何一步失败都不抛错,最差返回 null——身份是增强信息,不是运行前提。
13
+ */
14
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
15
+ import { createHash } from 'node:crypto'
16
+ import { homedir, hostname } from 'node:os'
17
+ import { join } from 'node:path'
18
+
19
+ /** 只匹配 `[user]` 段里的 email;不解析完整 ini,够用且不会误伤其它段 */
20
+ const EMAIL_LINE = /^\s*email\s*=\s*(.+)$/im
21
+ const REMOTE_LINE = /^\s*url\s*=\s*(.+)$/im
22
+ const DEVICE_ID = /^[0-9a-f]{16}$/
23
+
24
+ function readText(path) {
25
+ try {
26
+ return readFileSync(path, 'utf8')
27
+ } catch {
28
+ return null
29
+ }
30
+ }
31
+
32
+ function emailIn(text) {
33
+ const match = text?.match(EMAIL_LINE)
34
+ return match ? match[1].trim() : null
35
+ }
36
+
37
+ /**
38
+ * git remote 归一成 `host/owner/repo`。
39
+ * 认 `git@host:owner/repo.git`、`https://user:pass@host/owner/repo.git`、`ssh://host/owner/repo` 三种写法。
40
+ */
41
+ export function normalizeRemote(raw) {
42
+ if (typeof raw !== 'string' || raw.trim() === '') return null
43
+ let text = raw.trim().replace(/\.git$/i, '')
44
+ text = text.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '') // 去协议
45
+ text = text.replace(/^[^@/]*@/, '') // 去 user:pass@ 与 git@
46
+ text = text.replace(/^([^:/]+):/, '$1/') // host:owner/repo → host/owner/repo
47
+ const parts = text.split('/').filter(Boolean)
48
+ if (parts.length < 3) return null // 至少 host/owner/repo,不足就认不出来
49
+ return parts.slice(0, 3).join('/').toLowerCase()
50
+ }
51
+
52
+ function remoteIn(text) {
53
+ const match = text?.match(REMOTE_LINE)
54
+ return match ? normalizeRemote(match[1]) : null
55
+ }
56
+
57
+ /** 机器标识:优先持久化到 ~/.dsh/ledger/device-id;写不了就用 hostname 派生一个稳定值,绝不用随机数 */
58
+ function readOrCreateDeviceId() {
59
+ const dir = join(homedir(), '.dsh', 'ledger')
60
+ const path = join(dir, 'device-id')
61
+ const existing = readText(path)?.trim()
62
+ if (existing && DEVICE_ID.test(existing)) return existing
63
+
64
+ const id = createHash('sha1').update(`${hostname()}|${process.platform}|${process.arch}`).digest('hex').slice(0, 16)
65
+ try {
66
+ mkdirSync(dir, { recursive: true })
67
+ writeFileSync(path, `${id}\n`)
68
+ } catch {
69
+ // 无写权限时仍然返回同一个稳定 id,只是不落盘
70
+ }
71
+ return id
72
+ }
73
+
74
+ /**
75
+ * @param {{globalGitConfig?: string, maxCwd?: number, deviceId?: string}} [options]
76
+ */
77
+ export function createIdentity(options = {}) {
78
+ const globalConfig = options.globalGitConfig ?? join(homedir(), '.gitconfig')
79
+ const maxCwd = Math.max(2, Number(options.maxCwd ?? 64))
80
+ const byCwd = new Map()
81
+ let deviceId = null
82
+
83
+ function deviceIdOf() {
84
+ // 显式注入的 id 优先(测试与多设备场景),否则读/建 ~/.dsh/ledger/device-id
85
+ if (deviceId === null) deviceId = typeof options.deviceId === 'string' && DEVICE_ID.test(options.deviceId) ? options.deviceId : readOrCreateDeviceId()
86
+ return deviceId
87
+ }
88
+
89
+ function resolve(cwd) {
90
+ if (typeof cwd !== 'string' || cwd === '') {
91
+ return { actor: null, project: null, deviceId: deviceIdOf() }
92
+ }
93
+ const cached = byCwd.get(cwd)
94
+ if (cached !== undefined) return cached
95
+
96
+ const localConfig = readText(join(cwd, '.git', 'config'))
97
+ const localEmail = emailIn(localConfig)
98
+ const globalEmail = localEmail === null ? emailIn(readText(globalConfig)) : null
99
+
100
+ let actor = null
101
+ if (localEmail !== null) actor = { email: localEmail.toLowerCase(), source: 'git-local' }
102
+ else if (globalEmail !== null) actor = { email: globalEmail.toLowerCase(), source: 'git-global' }
103
+
104
+ // 项目键:git remote 最稳(跨机器、跨目录重命名都一致);没有 remote 就退到目录名 + 路径短 hash
105
+ const remote = remoteIn(localConfig)
106
+ const project = remote !== null
107
+ ? { key: remote, source: 'git-remote' }
108
+ : { key: `dir/${cwd.split(/[\\/]/).filter(Boolean).pop() ?? 'root'}-${createHash('sha1').update(cwd).digest('hex').slice(0, 6)}`, source: 'cwd' }
109
+
110
+ const value = Object.freeze({ actor, project: Object.freeze(project), deviceId: deviceIdOf() })
111
+
112
+ // 有界缓存:cwd 数量在团队规模内不会失控,超出淘汰最旧即可
113
+ if (byCwd.size >= maxCwd) byCwd.delete(byCwd.keys().next().value)
114
+ byCwd.set(cwd, value)
115
+ return value
116
+ }
117
+
118
+ return { resolve, deviceId: deviceIdOf, normalizeRemote, stats: () => ({ cwdCount: byCwd.size }) }
119
+ }