@lingda-ai/dsh-plugin-hublink 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/lib/outbox.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * outbox:追加写 JSONL,ack 后重写剩余行。
3
+ *
4
+ * 为什么不用内存队列:插件会被重启、机器会断电。内存队列一定会丢数据,
5
+ * 而"少报几步"在 FinOps 里是最难发现、最难解释的错。
6
+ *
7
+ * 格式:一行一个信封 { eventId, at, payload },eventId 是发送前生成一次并固定下来的 UUID,
8
+ * 重发时不变 —— 服务端幂等键 (tenant, machine, session, step_seq) 因此能真正生效。
9
+ */
10
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
11
+ import { dirname } from "node:path"
12
+
13
+ export function createOutbox(path, options = {}) {
14
+ const now = options.now ?? (() => Date.now())
15
+ let dirReady = false
16
+
17
+ const ensureDir = () => {
18
+ if (dirReady) return
19
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
20
+ dirReady = true
21
+ }
22
+
23
+ return {
24
+ path,
25
+
26
+ /** 追加一批信封;返回写入条数 */
27
+ append(entries) {
28
+ if (!Array.isArray(entries) || entries.length === 0) return 0
29
+ ensureDir()
30
+ const lines = entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n"
31
+ appendFileSync(path, lines, { mode: 0o600 })
32
+ if (typeof options.onWrite === "function") options.onWrite(entries.length)
33
+ return entries.length
34
+ },
35
+
36
+ /** 读出全部信封(容错:末行被截断时丢弃该行并告警) */
37
+ read() {
38
+ if (!existsSync(path)) return { entries: [], damaged: 0 }
39
+ const raw = readFileSync(path, "utf8")
40
+ const lines = raw.split("\n").filter((line) => line.trim() !== "")
41
+ const entries = []
42
+ let damaged = 0
43
+ for (const line of lines) {
44
+ try {
45
+ entries.push(JSON.parse(line))
46
+ } catch {
47
+ damaged += 1
48
+ }
49
+ }
50
+ return { entries, damaged }
51
+ },
52
+
53
+ /** 取前 n 条发送;剩余继续留在盘上 */
54
+ claim(limit) {
55
+ const { entries, damaged } = this.read()
56
+ const batch = entries.slice(0, Math.max(1, limit))
57
+ return { batch, remaining: entries.length - batch.length, damaged }
58
+ },
59
+
60
+ /** 确认已送达:把剩余行重写回盘(原子替换) */
61
+ ack(count) {
62
+ const { entries } = this.read()
63
+ return this.replace(entries.slice(Math.max(0, count)))
64
+ },
65
+
66
+ /** 整文件替换(用于剔除本地校验失败的条目) */
67
+ replace(entries) {
68
+ ensureDir()
69
+ const tmp = `${path}.tmp`
70
+ writeFileSync(tmp, entries.map((entry) => JSON.stringify(entry)).join("\n") + (entries.length ? "\n" : ""), { mode: 0o600 })
71
+ renameSync(tmp, path)
72
+ return entries.length
73
+ },
74
+
75
+ /** 丢弃最前面的 n 条(服务端明确拒绝且无法修复时用) */
76
+ drop(count) {
77
+ return this.ack(count)
78
+ },
79
+
80
+ stats() {
81
+ const { entries, damaged } = this.read()
82
+ const bytes = existsSync(path) ? statSync(path).size : 0
83
+ const oldest = entries[0]?.at ?? null
84
+ let oldestSeconds = null
85
+ if (oldest) oldestSeconds = Math.max(0, Math.round((now() - Date.parse(oldest)) / 1000))
86
+ return { pending: entries.length, bytes, damaged, oldestSeconds }
87
+ },
88
+ }
89
+ }
package/lib/plan.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 批次规划:与服务端 `planBatch` 用同一套规则,本地先过一遍。
3
+ *
4
+ * 为什么本地也要校验:服务端整批拒绝(400/413)时,机器只会看到"没送达",
5
+ * 排查成本极高。本地先剔掉脏条目、按字节切批,能保证绝大多数投递一次成功。
6
+ */
7
+ import { randomUUID } from "node:crypto"
8
+
9
+ export const MAX_EVENTS_PER_BATCH = 200
10
+ export const MAX_BATCH_BYTES = 1_048_576
11
+ export const MAX_CLOCK_SKEW_SECONDS = 300
12
+ export const SCHEMA_VERSION = 1
13
+
14
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
15
+
16
+ /** 生成稳定事件 id:只在这里生成一次,写进 outbox 后永不改变 */
17
+ export function makeEventId() {
18
+ return randomUUID()
19
+ }
20
+
21
+ /**
22
+ * 单条校验(与 hub 端 RejectCode 对齐)
23
+ * @returns {null | string} 通过返回 null,否则返回拒绝码
24
+ */
25
+ export function validateEvent(event, options = {}) {
26
+ const now = options.now ?? Date.now()
27
+ if (!event || typeof event !== "object") return "invalid_schema"
28
+ if (!event.eventId || !UUID_RE.test(event.eventId)) return "missing_event_id"
29
+ if (!event.sessionId) return "missing_session_id"
30
+ if (!Number.isInteger(event.stepSeq) || event.stepSeq < 0) return "invalid_step_seq"
31
+ const ts = Date.parse(event.ts)
32
+ if (Number.isNaN(ts)) return "invalid_ts"
33
+ if (ts - now > MAX_CLOCK_SKEW_SECONDS * 1000) return "future_timestamp"
34
+ const inTok = event.tokens?.in ?? 0
35
+ const outTok = event.tokens?.out ?? 0
36
+ if (inTok < 0 || outTok < 0) return "negative_tokens"
37
+ return null
38
+ }
39
+
40
+ /** 按条数与字节切批:返回若干个可直接投递的批次 */
41
+ export function planBatches(entries, options = {}) {
42
+ const now = options.now ?? Date.now()
43
+ const maxEvents = Math.min(options.maxEvents ?? 200, MAX_EVENTS_PER_BATCH)
44
+ const maxBytes = options.maxBytes ?? MAX_BATCH_BYTES
45
+
46
+ const good = []
47
+ const rejected = []
48
+ for (const entry of entries) {
49
+ const code = validateEvent(entry.payload, { now })
50
+ if (code) rejected.push({ eventId: entry.eventId, code })
51
+ else good.push(entry)
52
+ }
53
+
54
+ const batches = []
55
+ let current = []
56
+ let currentBytes = 0
57
+
58
+ const envelopeBytes = (items) =>
59
+ Buffer.byteLength(JSON.stringify({ schemaVersion: SCHEMA_VERSION, batchId: "x".repeat(36), events: items.map((i) => i.payload) }))
60
+
61
+ for (const entry of good) {
62
+ const one = envelopeBytes([entry])
63
+ // 单条就超限:无法投递,记为放弃(不可能出现,除非服务端上限被改小)
64
+ if (one > maxBytes) {
65
+ rejected.push({ eventId: entry.eventId, code: "batch_too_large" })
66
+ continue
67
+ }
68
+ const candidate = current.length === 0 ? one : envelopeBytes([...current, entry])
69
+ if (current.length + 1 > maxEvents || candidate > maxBytes) {
70
+ batches.push(current)
71
+ current = [entry]
72
+ currentBytes = one
73
+ } else {
74
+ current.push(entry)
75
+ currentBytes = candidate
76
+ }
77
+ }
78
+ if (current.length > 0) batches.push(current)
79
+
80
+ return { batches, rejected, bytes: currentBytes }
81
+ }
82
+
83
+ /** 组一个可投递的 body */
84
+ export function buildBatchBody(entries, batchId = randomUUID()) {
85
+ return {
86
+ schemaVersion: SCHEMA_VERSION,
87
+ batchId,
88
+ events: entries.map((entry) => entry.payload),
89
+ }
90
+ }
package/lib/policy.js ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * 策略:拉取 + 本地缓存 + ETag。
3
+ *
4
+ * 每 5 分钟一次,绝大多数轮询会是 304(几十字节),成本可忽略。
5
+ * 缓存落盘是为了"hub 挂了也能知道上一版策略",而不是为了省流量。
6
+ */
7
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
8
+ import { dirname } from "node:path"
9
+
10
+ export function readCache(path) {
11
+ if (!existsSync(path)) return null
12
+ try {
13
+ const parsed = JSON.parse(readFileSync(path, "utf8"))
14
+ return parsed?.etag && parsed?.policy ? parsed : null
15
+ } catch {
16
+ return null
17
+ }
18
+ }
19
+
20
+ export function writeCache(path, etag, policy) {
21
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
22
+ const tmp = `${path}.tmp`
23
+ writeFileSync(tmp, JSON.stringify({ etag, policy, fetchedAt: new Date().toISOString() }, null, 2) + "\n", { mode: 0o600 })
24
+ renameSync(tmp, path)
25
+ }
26
+
27
+ /**
28
+ * 取一次策略。返回 {policy, etag, notModified}
29
+ * 304 时沿用旧缓存;网络错误时也沿用旧缓存并标记 stale,不让调度因为 hub 抖动而乱跑。
30
+ */
31
+ export async function refreshPolicy(context) {
32
+ const { client, cachePath } = context
33
+ const cached = readCache(cachePath)
34
+ let result
35
+ try {
36
+ result = await client.policy(cached?.etag)
37
+ } catch (error) {
38
+ return { policy: cached?.policy ?? null, etag: cached?.etag ?? null, stale: true, error: String(error?.message ?? error) }
39
+ }
40
+
41
+ if (result.status === 304) {
42
+ return { policy: cached?.policy ?? null, etag: cached?.etag ?? null, notModified: true }
43
+ }
44
+ if (result.status === 200 && result.json?.policy) {
45
+ writeCache(cachePath, result.json.etag, result.json.policy)
46
+ return { policy: result.json.policy, etag: result.json.etag, notModified: false }
47
+ }
48
+ return { policy: cached?.policy ?? null, etag: cached?.etag ?? null, stale: true, status: result.status }
49
+ }
50
+
51
+ /**
52
+ * 阈值判定:返回应当在本地做的动作(提示),真正阻断只有 gateway 执行人能做到。
53
+ */
54
+ export function evaluateBudget(policy, spend) {
55
+ if (!policy?.budget || policy.budget.limit === null || policy.budget.limit === undefined) {
56
+ return { state: "unlimited", ratio: null, actions: [] }
57
+ }
58
+ const limit = Number(policy.budget.limit)
59
+ if (!Number.isFinite(limit) || limit <= 0) return { state: "unlimited", ratio: null, actions: [] }
60
+ const ratio = Number(spend) / limit
61
+ const thresholds = Array.isArray(policy.budget.thresholds) ? policy.budget.thresholds : [0.8, 1.0]
62
+ const crossed = thresholds.filter((t) => ratio >= t)
63
+ if (crossed.length === 0) return { state: "ok", ratio, actions: [] }
64
+ const highest = Math.max(...crossed)
65
+ const actions = highest >= 1 ? ["warn", ...(policy.budget.actions ?? [])] : ["notice"]
66
+ return {
67
+ state: ratio >= 1 ? "exceeded" : "warning",
68
+ ratio,
69
+ actions,
70
+ executor: policy.budget.executor ?? "agent",
71
+ note: ratio >= 1 && (policy.budget.executor ?? "agent") === "agent" ? "本机只能提示,不会拦请求;要拦需切到网关执行人" : null,
72
+ }
73
+ }
package/lib/redact.js ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * 脱敏:这是整条链路上最关键的模块,因为默认的 DSH 遥测是"完整事件镜像",
3
+ * assistant/message 带全文。任何一条没被投影掉的消息,都会变成"把整个对话上传"。
4
+ *
5
+ * 做法不是"删敏感字段",而是**白名单投影**:从原始记录里只挑出允许的字段,
6
+ * 其余一律不进入 payload。这样即使上游以后新增字段,也不会默认泄漏。
7
+ */
8
+
9
+ /** 内建规则:每条规则拿到记录,返回 {keep:boolean, reason};抛异常视为不通过 */
10
+ const BUILTIN_RULES = [
11
+ {
12
+ name: "message-content-never",
13
+ // 消息类事件一律不采(它们是全文的主要载体)
14
+ test: (record) =>
15
+ /^(assistant|user|system)$/.test(String(record?.type ?? record?.kind ?? "").split("/")[0]),
16
+ reason: "message-events-not-allowed",
17
+ },
18
+ {
19
+ name: "no-free-text",
20
+ test: (record) => typeof record?.text === "string" && record.text.length > 0,
21
+ reason: "free-text-not-allowed",
22
+ },
23
+ {
24
+ name: "no-path-like",
25
+ test: (record) => {
26
+ const hay = `${record?.toolName ?? ""}${record?.command ?? ""}`
27
+ return /(\.\.\/|\/Users\/|\/home\/|[A-Za-z]:\\)/.test(hay)
28
+ },
29
+ reason: "path-like-payload",
30
+ },
31
+ ]
32
+
33
+ /**
34
+ * 投影一条 canonical 记录成"可出机器的结构"。
35
+ * 输出字段与 hub 端 `toUsageRow` 对齐,多一个字段都会被 hub 忽略,但这里仍严格限制。
36
+ */
37
+ export function projectRecord(record, options = {}) {
38
+ const allow = new Set(options.allow ?? ["model", "tokens", "cost", "tool", "configVersion", "plugin"])
39
+ const deny = new Set(options.deny ?? ["prompt", "response", "content", "filePath", "userName", "env"])
40
+
41
+ const out = {}
42
+
43
+ // 标识类:必需,不参与 allow/deny 开关
44
+ out.type = typeof record?.type === "string" ? record.type.slice(0, 64) : "usage/step"
45
+ if (typeof record?.ts === "string" || typeof record?.ts === "number") out.ts = record.ts
46
+ if (typeof record?.sessionId === "string") out.sessionId = record.sessionId.slice(0, 64)
47
+ if (Number.isInteger(record?.stepSeq)) out.stepSeq = record.stepSeq
48
+
49
+ if (allow.has("model")) {
50
+ const model = record?.model ?? record?.modelName
51
+ if (typeof model === "string" && model.length <= 64) out.model = model
52
+ }
53
+
54
+ if (allow.has("tokens")) {
55
+ const inTok = pickInt(record, ["tokens.in", "tokens.input", "inputTokens", "promptTokens"])
56
+ const outTok = pickInt(record, ["tokens.out", "tokens.output", "outputTokens", "completionTokens"])
57
+ const cacheRead = pickInt(record, ["tokens.cacheRead", "cacheReadTokens", "cachedTokens"])
58
+ if (inTok !== null || outTok !== null || cacheRead !== null) {
59
+ out.tokens = { in: inTok ?? 0, out: outTok ?? 0, cacheRead: cacheRead ?? 0 }
60
+ }
61
+ }
62
+
63
+ if (allow.has("cost")) {
64
+ const amount = pickNumber(record, ["cost.amount", "costAmount", "amount"])
65
+ const currency = record?.cost?.currency ?? record?.currency
66
+ const priceVersion = record?.cost?.priceVersion ?? record?.priceVersion
67
+ // 金额未知就不写 cost 字段,绝不写 0(hub 会把它算成"已知 0 元")
68
+ if (amount !== null && amount >= 0) {
69
+ out.cost = {
70
+ amount,
71
+ currency: typeof currency === "string" && currency.length <= 8 ? currency : "CNY",
72
+ ...(typeof priceVersion === "string" ? { priceVersion: priceVersion.slice(0, 32) } : {}),
73
+ }
74
+ }
75
+ }
76
+
77
+ if (allow.has("tool") && typeof (record?.tool ?? record?.toolName) === "string") {
78
+ out.tool = String(record?.tool ?? record?.toolName).slice(0, 64)
79
+ }
80
+
81
+ if (allow.has("configVersion") && typeof record?.configVersion === "string") {
82
+ out.configVersion = record.configVersion.slice(0, 32)
83
+ }
84
+
85
+ if (allow.has("plugin") && record?.plugin && typeof record.plugin === "object") {
86
+ out.plugin = { name: String(record.plugin.name ?? "").slice(0, 64) }
87
+ }
88
+
89
+ // deny 优先级最高:即便上游把某字段塞进了 allow,也在这里抹掉
90
+ for (const key of deny) {
91
+ if (key in out) delete out[key]
92
+ // 嵌套也不放过(只处理一层,够用且可预测)
93
+ if (out.plugin && key in out.plugin) delete out.plugin[key]
94
+ }
95
+
96
+ return out
97
+ }
98
+
99
+ /**
100
+ * 判定一条记录能否出机器。规则抛异常 = 不通过(fail-closed),
101
+ * 这与 DSH 官方 "抛异常就拦下该条、不改写本地权威日志" 的语义一致。
102
+ */
103
+ export function shouldSend(record, options = {}) {
104
+ const rules = options.rules === "none" ? [] : BUILTIN_RULES
105
+ for (const rule of rules) {
106
+ let verdict
107
+ try {
108
+ verdict = rule.test(record)
109
+ } catch (error) {
110
+ return { ok: false, reason: `${rule.name}:threw`, error: String(error?.message ?? error) }
111
+ }
112
+ if (verdict) return { ok: false, reason: `${rule.name}:${rule.reason}` }
113
+ }
114
+ return { ok: true }
115
+ }
116
+
117
+ function pickInt(record, paths) {
118
+ for (const path of paths) {
119
+ const value = readPath(record, path)
120
+ if (Number.isFinite(value)) {
121
+ const n = Math.trunc(value)
122
+ return n >= 0 ? n : null
123
+ }
124
+ }
125
+ return null
126
+ }
127
+
128
+ function pickNumber(record, paths) {
129
+ for (const path of paths) {
130
+ const value = readPath(record, path)
131
+ if (typeof value === "number" && Number.isFinite(value)) return value
132
+ if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value)
133
+ }
134
+ return null
135
+ }
136
+
137
+ function readPath(obj, path) {
138
+ let cur = obj
139
+ for (const key of path.split(".")) {
140
+ if (cur == null) return undefined
141
+ cur = cur[key]
142
+ }
143
+ return cur
144
+ }
145
+
146
+ export { BUILTIN_RULES }
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@lingda-ai/dsh-plugin-hublink",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "description": "DSH 插件:把本机用量上报到灵港(LingPort)hub。outbox + 批量 + 幂等键,凭证只落 0600 文件,脱敏规则强制生效,拉策略走 ETag。零运行时依赖。",
7
+ "keywords": [
8
+ "dsh",
9
+ "dsh-plugin",
10
+ "deepseek-harness",
11
+ "telemetry",
12
+ "finops",
13
+ "usage-reporting",
14
+ "lingport"
15
+ ],
16
+ "author": "LingDaAi",
17
+ "homepage": "https://gitee.com/linzhengtong/dsh-plugin-hublink#readme",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/lingda-ai/dsh-plugin-hublink.git"
21
+ },
22
+ "bugs": {
23
+ "url": "https://gitee.com/linzhengtong/dsh-plugin-hublink/issues"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "main": "./lib/index.js",
29
+ "exports": {
30
+ ".": "./lib/index.js",
31
+ "./config": "./lib/config.js",
32
+ "./outbox": "./lib/outbox.js",
33
+ "./redact": "./lib/redact.js",
34
+ "./package.json": "./package.json"
35
+ },
36
+ "bin": {
37
+ "hublink": "./bin/hublink.js"
38
+ },
39
+ "files": [
40
+ "lib",
41
+ "bin",
42
+ "cordis.patch.yml",
43
+ "README.md",
44
+ "docs/*.md"
45
+ ],
46
+ "engines": {
47
+ "node": ">=22.6"
48
+ },
49
+ "dsh": {
50
+ "bundle": {
51
+ "patch": "./cordis.patch.yml"
52
+ },
53
+ "catalog": {
54
+ "category": "other",
55
+ "summary": {
56
+ "en": "Reports local DSH usage to a LingPort hub: append-only outbox, batched idempotent ingest, machine key in a 0600 credentials file, allowlist redaction enforced before anything leaves the machine, and policy pulled with ETag. No runtime dependencies.",
57
+ "zh": "把本机用量上报到灵港 hub:outbox 追加写 + 批量幂等投递,机器密钥只落 0600 凭证文件,脱敏白名单先于出机器生效,策略拉取走 ETag。零运行时依赖。"
58
+ },
59
+ "capabilities": [
60
+ "session",
61
+ "fs",
62
+ "network"
63
+ ]
64
+ }
65
+ },
66
+ "peerDependencies": {
67
+ "@deepseek-ai/cordis": "*"
68
+ },
69
+ "scripts": {
70
+ "test": "node --test test/*.test.mjs",
71
+ "e2e": "node --test test/e2e.test.mjs"
72
+ }
73
+ }