@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/LICENSE +202 -0
- package/README.md +105 -2
- package/bin/hublink.js +240 -0
- package/cordis.patch.yml +15 -0
- package/docs/ops.md +56 -0
- package/lib/collect.js +157 -0
- package/lib/config.js +98 -0
- package/lib/credentials.js +72 -0
- package/lib/flush.js +79 -0
- package/lib/http.js +97 -0
- package/lib/index.js +157 -0
- package/lib/outbox.js +89 -0
- package/lib/plan.js +90 -0
- package/lib/policy.js +73 -0
- package/lib/redact.js +146 -0
- package/package.json +71 -4
package/lib/collect.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 采集:把上游记录变成 outbox 信封。
|
|
3
|
+
*
|
|
4
|
+
* 两条路径:
|
|
5
|
+
* A. 官方 `ctx.sessionTelemetry` 后端(推荐)——emit 进来的每条 canonical 事件就是一信封。
|
|
6
|
+
* B. 回退:读 ledger 的只读服务(listSessions/summarize),按小时对齐后补采。
|
|
7
|
+
*
|
|
8
|
+
* 两条路径都走同一个 `toEnvelope`:脱敏 → 投影 → 校验 → 生成稳定 eventId。
|
|
9
|
+
* 这样"有没有官方 seam"不影响数据口径,只影响颗粒度。
|
|
10
|
+
*/
|
|
11
|
+
import { makeEventId, validateEvent } from "./plan.js"
|
|
12
|
+
import { projectRecord, shouldSend } from "./redact.js"
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 记录 → 信封。返回 null 表示不该发(被规则拦下或校验不过)。
|
|
16
|
+
*/
|
|
17
|
+
export function toEnvelope(record, options = {}) {
|
|
18
|
+
const verdict = shouldSend(record, { rules: options.rules })
|
|
19
|
+
if (!verdict.ok) {
|
|
20
|
+
if (typeof options.onReject === "function") options.onReject(verdict.reason, record)
|
|
21
|
+
return null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const projected = projectRecord(record, options)
|
|
25
|
+
const payload = {
|
|
26
|
+
eventId: makeEventId(),
|
|
27
|
+
sessionId: projected.sessionId ?? "unknown-session",
|
|
28
|
+
stepSeq: Number.isInteger(projected.stepSeq) ? projected.stepSeq : nextSeq(projected.sessionId),
|
|
29
|
+
ts: normalizeTs(projected.ts ?? record?.ts, options.now ?? Date.now()),
|
|
30
|
+
tokens: projected.tokens ?? { in: 0, out: 0, cacheRead: 0 },
|
|
31
|
+
...(projected.cost ? { cost: projected.cost } : {}),
|
|
32
|
+
...(projected.model ? { model: projected.model } : {}),
|
|
33
|
+
attribution: buildAttribution(projected),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const code = validateEvent(payload, { now: options.now ?? Date.now() })
|
|
37
|
+
if (code) {
|
|
38
|
+
if (typeof options.onReject === "function") options.onReject(code, record)
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return { eventId: payload.eventId, at: new Date(options.now ?? Date.now()).toISOString(), payload }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 归因只保留六个允许键,避免上游塞进任意结构 */
|
|
46
|
+
function buildAttribution(projected) {
|
|
47
|
+
const attribution = {}
|
|
48
|
+
if (projected.tool) attribution.tool = projected.tool
|
|
49
|
+
if (projected.plugin?.name) attribution.plugin = projected.plugin.name
|
|
50
|
+
if (projected.configVersion) attribution.configVersion = projected.configVersion
|
|
51
|
+
return attribution
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 时间戳非法时用当前时间兜底,避免整条被拒(数据还可以用,只是时间精度差) */
|
|
55
|
+
function normalizeTs(ts, now) {
|
|
56
|
+
const parsed = typeof ts === "number" ? ts : Date.parse(String(ts ?? ""))
|
|
57
|
+
if (Number.isFinite(parsed)) {
|
|
58
|
+
// 未来时间(时钟漂移)压回当前时间,避免被服务端按 future_timestamp 拒掉
|
|
59
|
+
const skewOk = parsed <= now + 60_000
|
|
60
|
+
return new Date(skewOk ? parsed : now).toISOString()
|
|
61
|
+
}
|
|
62
|
+
return new Date(now).toISOString()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 同一进程内按 session 递增加 seq(换来的是"至少能排序",不是严格真实步数) */
|
|
66
|
+
const seqCounters = new Map()
|
|
67
|
+
function nextSeq(sessionId) {
|
|
68
|
+
const key = String(sessionId ?? "unknown-session")
|
|
69
|
+
const current = seqCounters.get(key) ?? 0
|
|
70
|
+
seqCounters.set(key, current + 1)
|
|
71
|
+
return current
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function resetSeqCounters() {
|
|
75
|
+
seqCounters.clear()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 官方 sessionTelemetry 后端。
|
|
80
|
+
*
|
|
81
|
+
* 契约三成员 emit / flush / shutdown,与 DSH 侧一致:
|
|
82
|
+
* emit(record) 非阻塞入队(这里同步写盘,保证断电不丢)
|
|
83
|
+
* flush() 立即推一批
|
|
84
|
+
* shutdown() flush 后返回
|
|
85
|
+
*
|
|
86
|
+
* `sharing: "full"` 是必须的——feedback-only 只覆盖反馈面板,拿不到 step 粒度用量。
|
|
87
|
+
* 但 full 意味着"默认镜像全部事件",所以脱敏规则在这里是**前置条件**,不是可选项。
|
|
88
|
+
*/
|
|
89
|
+
export function createTelemetryBackend(context) {
|
|
90
|
+
const { outbox, rules = "builtin", now = () => Date.now(), logger = () => {} } = context
|
|
91
|
+
const rejected = { count: 0, lastReason: null }
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
name: "lingport-hublink",
|
|
95
|
+
sharing: "full",
|
|
96
|
+
|
|
97
|
+
emit(record) {
|
|
98
|
+
try {
|
|
99
|
+
const envelope = toEnvelope(record, {
|
|
100
|
+
rules,
|
|
101
|
+
now: now(),
|
|
102
|
+
onReject: (reason) => {
|
|
103
|
+
rejected.count += 1
|
|
104
|
+
rejected.lastReason = reason
|
|
105
|
+
},
|
|
106
|
+
})
|
|
107
|
+
if (!envelope) return false
|
|
108
|
+
outbox.append([envelope])
|
|
109
|
+
return true
|
|
110
|
+
} catch (error) {
|
|
111
|
+
// 绝不让采集异常冒泡到宿主(会打断会话)
|
|
112
|
+
logger(`采集异常已吞掉:${String(error?.message ?? error)}`)
|
|
113
|
+
return false
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
|
|
117
|
+
flush() {
|
|
118
|
+
return typeof context.flush === "function" ? context.flush() : undefined
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
shutdown() {
|
|
122
|
+
return this.flush()
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
stats() {
|
|
126
|
+
return { rejected: rejected.count, lastReason: rejected.lastReason }
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 回退采集:从 ledger 的会话快照补一步(只在没有官方 seam 的宿主用)。
|
|
133
|
+
* 明确标注质量:这类数据只有会话级总量,没有逐 step,所以 stepSeq 用 0,attribution 留空。
|
|
134
|
+
*/
|
|
135
|
+
export async function collectFromLedger(ledgerService, options = {}) {
|
|
136
|
+
if (!ledgerService) return []
|
|
137
|
+
const since = options.since ?? new Date(Date.now() - 3600_000).toISOString()
|
|
138
|
+
const sessions = await ledgerService.listSessions?.({ since })
|
|
139
|
+
if (!Array.isArray(sessions)) return []
|
|
140
|
+
const envelopes = []
|
|
141
|
+
for (const session of sessions) {
|
|
142
|
+
const envelope = toEnvelope(
|
|
143
|
+
{
|
|
144
|
+
type: "usage/session",
|
|
145
|
+
sessionId: session.id ?? session.sessionId,
|
|
146
|
+
stepSeq: 0,
|
|
147
|
+
ts: session.lastAt ?? session.updatedAt ?? new Date().toISOString(),
|
|
148
|
+
tokens: { in: session.tokensIn, out: session.tokensOut, cacheRead: session.tokensCacheRead },
|
|
149
|
+
cost: session.cost,
|
|
150
|
+
model: session.model,
|
|
151
|
+
},
|
|
152
|
+
options,
|
|
153
|
+
)
|
|
154
|
+
if (envelope) envelopes.push(envelope)
|
|
155
|
+
}
|
|
156
|
+
return envelopes
|
|
157
|
+
}
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 配置:读 settings 里的一段,做严格校验与默认值填充。
|
|
3
|
+
*
|
|
4
|
+
* 原则:宁可启动失败,也不要"带着半套配置静默跑"——半套配置最常见的后果是
|
|
5
|
+
* 凭证路径写错导致密钥落进机库备份,或者 hubUrl 写错导致 spool 无限增长。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_CONFIG = {
|
|
9
|
+
hubUrl: null,
|
|
10
|
+
tenantId: null,
|
|
11
|
+
machineId: null,
|
|
12
|
+
credentialsPath: "~/.dsh/credentials/hublink.json",
|
|
13
|
+
spoolPath: "~/.dsh/telemetry/hublink-outbox.jsonl",
|
|
14
|
+
policyCachePath: "~/.dsh/telemetry/hublink-policy.json",
|
|
15
|
+
flushIntervalSeconds: 60,
|
|
16
|
+
policyIntervalSeconds: 300,
|
|
17
|
+
batchSize: 100,
|
|
18
|
+
requestTimeoutMs: 10_000,
|
|
19
|
+
maxRetries: 5,
|
|
20
|
+
collect: {
|
|
21
|
+
allow: ["model", "tokens", "cost", "tool", "configVersion", "plugin"],
|
|
22
|
+
deny: ["prompt", "response", "content", "filePath", "userName", "env"],
|
|
23
|
+
sampleRate: 1,
|
|
24
|
+
},
|
|
25
|
+
redactionRules: "builtin",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const REQUIRED = ["hubUrl", "machineId"]
|
|
29
|
+
void REQUIRED
|
|
30
|
+
|
|
31
|
+
/** 把 `~/x` 展开成绝对路径;不依赖 process.env.HOME 以外的变量 */
|
|
32
|
+
export function expandHome(p, home = process.env.HOME ?? "") {
|
|
33
|
+
if (typeof p !== "string" || p.length === 0) return p
|
|
34
|
+
if (p === "~") return home
|
|
35
|
+
if (p.startsWith("~/")) return `${home}${p.slice(1)}`
|
|
36
|
+
return p
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 校验并归一化配置。
|
|
41
|
+
* @returns {{ok: true, config: object} | {ok: false, errors: string[]}}
|
|
42
|
+
*/
|
|
43
|
+
export function normalizeConfig(input = {}, options = {}) {
|
|
44
|
+
const home = options.home ?? process.env.HOME ?? ""
|
|
45
|
+
const errors = []
|
|
46
|
+
const config = {
|
|
47
|
+
...DEFAULT_CONFIG,
|
|
48
|
+
...input,
|
|
49
|
+
collect: { ...DEFAULT_CONFIG.collect, ...(input.collect ?? {}) },
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (typeof config.hubUrl !== "string" || config.hubUrl.trim() === "") {
|
|
53
|
+
errors.push("hubUrl 必填,例如 http://10.0.0.8:3000/extension/agentops/api/openapi")
|
|
54
|
+
} else {
|
|
55
|
+
try {
|
|
56
|
+
const url = new URL(config.hubUrl)
|
|
57
|
+
if (!/^https?:$/.test(url.protocol)) errors.push("hubUrl 只支持 http/https")
|
|
58
|
+
// 去掉尾斜杠,后面统一拼 /ingest /policy /enroll
|
|
59
|
+
config.hubUrl = config.hubUrl.replace(/\/+$/, "")
|
|
60
|
+
} catch {
|
|
61
|
+
errors.push(`hubUrl 不是合法 URL:${config.hubUrl}`)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (typeof config.machineId !== "string" || config.machineId.trim() === "") {
|
|
66
|
+
errors.push("machineId 必填(建议用主机名+短哈希,稳定不变)")
|
|
67
|
+
} else if (!/^[A-Za-z0-9._-]{3,64}$/.test(config.machineId)) {
|
|
68
|
+
errors.push("machineId 只允许字母数字 . _ -,长度 3–64")
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (config.batchSize < 1 || config.batchSize > 200) {
|
|
72
|
+
errors.push("batchSize 必须在 1–200 之间(服务端硬上限 200 条/批)")
|
|
73
|
+
}
|
|
74
|
+
if (!(config.collect.sampleRate >= 0 && config.collect.sampleRate <= 1)) {
|
|
75
|
+
errors.push("collect.sampleRate 必须在 0–1 之间")
|
|
76
|
+
}
|
|
77
|
+
if (!Array.isArray(config.collect.allow) || !Array.isArray(config.collect.deny)) {
|
|
78
|
+
errors.push("collect.allow / collect.deny 必须是数组")
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
config.credentialsPath = expandHome(config.credentialsPath, home)
|
|
82
|
+
config.spoolPath = expandHome(config.spoolPath, home)
|
|
83
|
+
config.policyCachePath = expandHome(config.policyCachePath, home)
|
|
84
|
+
|
|
85
|
+
// 凭证与 spool 同目录,就必然被同一份备份/rsync 带走,直接拒绝启动
|
|
86
|
+
const dirname = (p) => p.replace(/[^/]+$/, "")
|
|
87
|
+
if (dirname(config.credentialsPath) === dirname(config.spoolPath)) {
|
|
88
|
+
errors.push("credentialsPath 不能与 spoolPath 同目录(凭证会被备份带走)")
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (errors.length > 0) return { ok: false, errors }
|
|
92
|
+
return { ok: true, config }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 从 dsh settings 结构里取本插件那段(兼容 `hublink` 与 `@lingda-ai/dsh-plugin-hublink` 两种写法) */
|
|
96
|
+
export function pickConfig(settings = {}) {
|
|
97
|
+
return settings.hublink ?? settings["@lingda-ai/dsh-plugin-hublink"] ?? {}
|
|
98
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 凭证:机器密钥只存在一个 0600 文件里。
|
|
3
|
+
*
|
|
4
|
+
* 三条硬约束:
|
|
5
|
+
* 1. 目录 0700、文件 0600(同机其他用户读不到)
|
|
6
|
+
* 2. 写入用 tmp + rename(断电不会留下半截 JSON)
|
|
7
|
+
* 3. 默认放在 ~/.dsh/credentials/,不在机库备份范围、不进 git
|
|
8
|
+
*/
|
|
9
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"
|
|
10
|
+
import { dirname } from "node:path"
|
|
11
|
+
|
|
12
|
+
export function loadCredentials(path) {
|
|
13
|
+
if (!existsSync(path)) return null
|
|
14
|
+
try {
|
|
15
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"))
|
|
16
|
+
if (!parsed?.key || !parsed?.machineId) return null
|
|
17
|
+
return parsed
|
|
18
|
+
} catch {
|
|
19
|
+
return null
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function saveCredentials(path, payload) {
|
|
24
|
+
const dir = dirname(path)
|
|
25
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
26
|
+
try {
|
|
27
|
+
chmodSync(dir, 0o700)
|
|
28
|
+
} catch {
|
|
29
|
+
/* 某些挂载点不支持 chmod,忽略 */
|
|
30
|
+
}
|
|
31
|
+
const body = {
|
|
32
|
+
version: 1,
|
|
33
|
+
hubUrl: payload.hubUrl,
|
|
34
|
+
tenantId: payload.tenantId ?? null,
|
|
35
|
+
machineId: payload.machineId,
|
|
36
|
+
keyId: payload.keyId ?? null,
|
|
37
|
+
key: payload.key,
|
|
38
|
+
enrolledAt: payload.enrolledAt ?? new Date().toISOString(),
|
|
39
|
+
}
|
|
40
|
+
const tmp = `${path}.tmp`
|
|
41
|
+
writeFileSync(tmp, JSON.stringify(body, null, 2) + "\n", { mode: 0o600 })
|
|
42
|
+
chmodSync(tmp, 0o600)
|
|
43
|
+
renameSync(tmp, path)
|
|
44
|
+
chmodSync(path, 0o600)
|
|
45
|
+
return body
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function deleteCredentials(path) {
|
|
49
|
+
if (existsSync(path)) unlinkSync(path)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 只用于展示:永远不打印完整密钥 */
|
|
53
|
+
export function maskCredentials(credentials) {
|
|
54
|
+
if (!credentials) return { enrolled: false }
|
|
55
|
+
const key = String(credentials.key ?? "")
|
|
56
|
+
return {
|
|
57
|
+
enrolled: true,
|
|
58
|
+
machineId: credentials.machineId,
|
|
59
|
+
keyId: credentials.keyId,
|
|
60
|
+
keyHint: key.length > 8 ? `${key.slice(0, 6)}…${key.slice(-4)}` : "…",
|
|
61
|
+
hubUrl: credentials.hubUrl,
|
|
62
|
+
enrolledAt: credentials.enrolledAt,
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 权限自检:给 doctor 用 */
|
|
67
|
+
export function checkPermissions(path) {
|
|
68
|
+
if (!existsSync(path)) return { ok: false, reason: "missing" }
|
|
69
|
+
const mode = statSync(path).mode & 0o777
|
|
70
|
+
if (mode !== 0o600) return { ok: false, reason: `mode=${mode.toString(8)}(应为 600)` }
|
|
71
|
+
return { ok: true, mode: "600" }
|
|
72
|
+
}
|
package/lib/flush.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 一次投递:从 outbox 取批 → 投 → 按结果落账。
|
|
3
|
+
*
|
|
4
|
+
* 幂等键在服务端,这里的责任只有一条:**同一批重发时 eventId 不变**。
|
|
5
|
+
* eventId 在写入 outbox 时生成并固定,所以"重发"天然幂等。
|
|
6
|
+
*/
|
|
7
|
+
import { buildBatchBody, planBatches } from "./plan.js"
|
|
8
|
+
import { backoffSeconds, classify } from "./http.js"
|
|
9
|
+
|
|
10
|
+
export async function flushOnce(context) {
|
|
11
|
+
const { outbox, client, batchSize = 100, maxAttempts = 3, sleep, logger = () => {} } = context
|
|
12
|
+
const { entries } = outbox.read()
|
|
13
|
+
if (entries.length === 0) return { sent: 0, accepted: 0, duplicated: 0, dropped: 0, pending: 0 }
|
|
14
|
+
|
|
15
|
+
const { batches, rejected } = planBatches(entries, { maxEvents: batchSize })
|
|
16
|
+
let accepted = 0
|
|
17
|
+
let duplicated = 0
|
|
18
|
+
let dropped = rejected.length
|
|
19
|
+
let sent = 0
|
|
20
|
+
|
|
21
|
+
// 本地校验失败的直接扣掉(它们永远无法送达,留着只会堵住队列)
|
|
22
|
+
if (rejected.length > 0) {
|
|
23
|
+
const dropIds = new Set(rejected.map((item) => item.eventId))
|
|
24
|
+
outbox.replace(entries.filter((entry) => !dropIds.has(entry.eventId)))
|
|
25
|
+
logger(`本地校验丢弃 ${rejected.length} 条:${rejected.map((r) => r.code).join(",")}`)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
for (const batch of batches) {
|
|
29
|
+
sent += batch.length
|
|
30
|
+
const body = buildBatchBody(batch)
|
|
31
|
+
let attempt = 1
|
|
32
|
+
let done = false
|
|
33
|
+
while (!done) {
|
|
34
|
+
const result = await client.ingest(body)
|
|
35
|
+
const verdict = classify(result)
|
|
36
|
+
if (verdict.action === "ok") {
|
|
37
|
+
accepted += verdict.accepted ?? batch.length
|
|
38
|
+
duplicated += verdict.duplicated ?? 0
|
|
39
|
+
outbox.drop(batch.length)
|
|
40
|
+
done = true
|
|
41
|
+
break
|
|
42
|
+
}
|
|
43
|
+
if (verdict.action === "reauth") {
|
|
44
|
+
// 不丢数据:留着等重新纳管后继续投
|
|
45
|
+
return { sent, accepted, duplicated, dropped, pending: outbox.stats().pending, needsReenroll: true }
|
|
46
|
+
}
|
|
47
|
+
if (verdict.action === "drop") {
|
|
48
|
+
logger(`整批被拒(${verdict.code ?? "400"}),丢弃 ${batch.length} 条`)
|
|
49
|
+
outbox.drop(batch.length)
|
|
50
|
+
dropped += batch.length
|
|
51
|
+
done = true
|
|
52
|
+
break
|
|
53
|
+
}
|
|
54
|
+
if (verdict.action === "split" && batch.length > 1) {
|
|
55
|
+
// 拆半重投:前半批继续走外层逻辑
|
|
56
|
+
const half = Math.ceil(batch.length / 2)
|
|
57
|
+
const front = batch.slice(0, half)
|
|
58
|
+
const back = batch.slice(half)
|
|
59
|
+
const frontResult = await client.ingest(buildBatchBody(front))
|
|
60
|
+
if (classify(frontResult).action === "ok") {
|
|
61
|
+
accepted += frontResult.json?.accepted ?? front.length
|
|
62
|
+
duplicated += frontResult.json?.duplicated ?? 0
|
|
63
|
+
outbox.drop(front.length)
|
|
64
|
+
}
|
|
65
|
+
// back 留给下一轮
|
|
66
|
+
return { sent, accepted, duplicated, dropped, pending: outbox.stats().pending, split: true }
|
|
67
|
+
}
|
|
68
|
+
if (attempt >= maxAttempts) {
|
|
69
|
+
return { sent, accepted, duplicated, dropped, pending: outbox.stats().pending, failed: true }
|
|
70
|
+
}
|
|
71
|
+
const wait = verdict.action === "backoff" ? verdict.retryAfter : backoffSeconds(attempt)
|
|
72
|
+
logger(`投递失败(status=${result.status}),${wait}s 后重试(第 ${attempt} 次)`)
|
|
73
|
+
if (typeof sleep === "function") await sleep(wait * 1000)
|
|
74
|
+
attempt += 1
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return { sent, accepted, duplicated, dropped, pending: outbox.stats().pending }
|
|
79
|
+
}
|
package/lib/http.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP:三个端点 + 明确的失败分类。
|
|
3
|
+
*
|
|
4
|
+
* 分类比"重试几次"更重要:
|
|
5
|
+
* - 401/403:密钥失效或被吊销 → 不能重试,必须重新纳管(数据留在 outbox 不能丢)
|
|
6
|
+
* - 413:批次太大 → 拆半重投
|
|
7
|
+
* - 400:整批被拒 → 丢掉这一批并记账,不能让 spool 卡死
|
|
8
|
+
* - 429:按 Retry-After 退避
|
|
9
|
+
* - 5xx / 网络错误:指数退避重试
|
|
10
|
+
*/
|
|
11
|
+
export const PATHS = {
|
|
12
|
+
ingest: "/ingest",
|
|
13
|
+
enroll: "/enroll",
|
|
14
|
+
policy: "/policy",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function createClient(options) {
|
|
18
|
+
const { hubUrl, key, timeoutMs = 10_000, fetchImpl = globalThis.fetch } = options
|
|
19
|
+
|
|
20
|
+
async function request(path, init = {}) {
|
|
21
|
+
const url = `${hubUrl}${path}`
|
|
22
|
+
const controller = new AbortController()
|
|
23
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
24
|
+
try {
|
|
25
|
+
const response = await fetchImpl(url, {
|
|
26
|
+
...init,
|
|
27
|
+
signal: controller.signal,
|
|
28
|
+
headers: {
|
|
29
|
+
...(init.headers ?? {}),
|
|
30
|
+
...(key ? { "x-api-key": key } : {}),
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
const text = await response.text()
|
|
34
|
+
let json = null
|
|
35
|
+
if (text) {
|
|
36
|
+
try {
|
|
37
|
+
json = JSON.parse(text)
|
|
38
|
+
} catch {
|
|
39
|
+
json = { raw: text.slice(0, 200) }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return { status: response.status, headers: response.headers, json }
|
|
43
|
+
} finally {
|
|
44
|
+
clearTimeout(timer)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
hubUrl,
|
|
50
|
+
|
|
51
|
+
async ingest(body) {
|
|
52
|
+
return request(PATHS.ingest, {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: { "content-type": "application/json" },
|
|
55
|
+
body: JSON.stringify(body),
|
|
56
|
+
})
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
async policy(ifNoneMatch) {
|
|
60
|
+
return request(PATHS.policy, {
|
|
61
|
+
method: "GET",
|
|
62
|
+
headers: ifNoneMatch ? { "if-none-match": ifNoneMatch } : {},
|
|
63
|
+
})
|
|
64
|
+
},
|
|
65
|
+
|
|
66
|
+
async enroll(payload) {
|
|
67
|
+
return request(PATHS.enroll, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers: { "content-type": "application/json" },
|
|
70
|
+
body: JSON.stringify(payload),
|
|
71
|
+
})
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 把一次 HTTP 结果归成动作 */
|
|
77
|
+
export function classify(result) {
|
|
78
|
+
const status = result.status
|
|
79
|
+
const code = result.json?.code ?? result.json?.data?.code ?? null
|
|
80
|
+
if (status === 202) return { action: "ok", duplicated: result.json?.duplicated ?? 0, accepted: result.json?.accepted ?? 0 }
|
|
81
|
+
if (status === 200) return { action: "ok" }
|
|
82
|
+
if (status === 304) return { action: "not-modified" }
|
|
83
|
+
if (status === 413) return { action: "split" }
|
|
84
|
+
if (status === 401 || status === 403) return { action: "reauth", code }
|
|
85
|
+
if (status === 429) {
|
|
86
|
+
const retryAfter = Number(result.headers?.get?.("retry-after") ?? 0)
|
|
87
|
+
return { action: "backoff", retryAfter: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : 5 }
|
|
88
|
+
}
|
|
89
|
+
if (status === 400) return { action: "drop", code, message: result.json?.message }
|
|
90
|
+
if (status >= 500) return { action: "retry", status }
|
|
91
|
+
return { action: "retry", status }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 指数退避序列(秒) */
|
|
95
|
+
export function backoffSeconds(attempt, base = 2, cap = 300) {
|
|
96
|
+
return Math.min(cap, base ** Math.max(0, attempt - 1))
|
|
97
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hublink:把本机用量上报到灵港(LingPort)hub 的采集端。
|
|
3
|
+
*
|
|
4
|
+
* 三件事,且只有三件:
|
|
5
|
+
* 1. 采(走官方 sessionTelemetry seam,脱敏规则前置)
|
|
6
|
+
* 2. 存(append-only outbox,断电不丢)
|
|
7
|
+
* 3. 送(批量 + 幂等 eventId,失败分类处理,密钥只存 0600)
|
|
8
|
+
*
|
|
9
|
+
* 刻意不做:面板、图表、额度拦截。拦截必须在 LLM 网关,插件侧拦不住;
|
|
10
|
+
* 面板由 hub 控制台与空港套件负责,这里重复做只会造成"两个金额"。
|
|
11
|
+
*/
|
|
12
|
+
import { createTelemetryBackend, collectFromLedger } from "./lib/collect.js"
|
|
13
|
+
import { normalizeConfig } from "./lib/config.js"
|
|
14
|
+
import { loadCredentials } from "./lib/credentials.js"
|
|
15
|
+
import { flushOnce } from "./lib/flush.js"
|
|
16
|
+
import { createClient } from "./lib/http.js"
|
|
17
|
+
import { createOutbox } from "./lib/outbox.js"
|
|
18
|
+
import { refreshPolicy, evaluateBudget } from "./lib/policy.js"
|
|
19
|
+
|
|
20
|
+
export const name = "@lingda-ai/dsh-plugin-hublink"
|
|
21
|
+
export const inject = []
|
|
22
|
+
|
|
23
|
+
export function apply(ctx, rawConfig = {}) {
|
|
24
|
+
const normalized = normalizeConfig(rawConfig)
|
|
25
|
+
const logger = (message) => {
|
|
26
|
+
try {
|
|
27
|
+
ctx.logger?.info?.(`[hublink] ${message}`)
|
|
28
|
+
} catch {
|
|
29
|
+
/* 宿主没有 logger 就算了 */
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!normalized.ok) {
|
|
34
|
+
// 配置不完整就不启动:宁可显式失败,也不要半套配置静默上传
|
|
35
|
+
logger(`配置未就绪,采集未启动:${normalized.errors.join(";")}`)
|
|
36
|
+
return {
|
|
37
|
+
status: () => ({ ready: false, errors: normalized.errors }),
|
|
38
|
+
flush: async () => ({ ready: false }),
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const config = normalized.config
|
|
43
|
+
const credentials = loadCredentials(config.credentialsPath)
|
|
44
|
+
if (!credentials) {
|
|
45
|
+
logger(`未纳管:缺少 ${config.credentialsPath},先跑 hublink enroll`)
|
|
46
|
+
return {
|
|
47
|
+
status: () => ({ ready: false, errors: ["not-enrolled"] }),
|
|
48
|
+
flush: async () => ({ ready: false }),
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const outbox = createOutbox(config.spoolPath)
|
|
53
|
+
const client = createClient({ hubUrl: config.hubUrl, key: credentials.key, timeoutMs: config.requestTimeoutMs })
|
|
54
|
+
const telemetry = createTelemetryBackend({
|
|
55
|
+
outbox,
|
|
56
|
+
rules: config.redactionRules,
|
|
57
|
+
logger,
|
|
58
|
+
flush: () => runFlush(),
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
let lastFlush = null
|
|
62
|
+
let lastPolicy = null
|
|
63
|
+
let budgetState = null
|
|
64
|
+
let timer = null
|
|
65
|
+
let policyTimer = null
|
|
66
|
+
|
|
67
|
+
async function runFlush() {
|
|
68
|
+
try {
|
|
69
|
+
lastFlush = await flushOnce({ outbox, client, batchSize: config.batchSize, logger })
|
|
70
|
+
return lastFlush
|
|
71
|
+
} catch (error) {
|
|
72
|
+
lastFlush = { error: String(error?.message ?? error) }
|
|
73
|
+
return lastFlush
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function runPolicy() {
|
|
78
|
+
try {
|
|
79
|
+
lastPolicy = await refreshPolicy({ client, cachePath: config.policyCachePath })
|
|
80
|
+
budgetState = evaluateBudget(lastPolicy.policy, lastFlush?.acceptedCost ?? 0)
|
|
81
|
+
return lastPolicy
|
|
82
|
+
} catch (error) {
|
|
83
|
+
lastPolicy = { error: String(error?.message ?? error) }
|
|
84
|
+
return lastPolicy
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// 官方 seam 优先;宿主没有就降级,并明确在 status 里标出来
|
|
89
|
+
let seam = "none"
|
|
90
|
+
if (typeof ctx.inject === "function") {
|
|
91
|
+
ctx.inject(["sessionTelemetry"], (inner) => {
|
|
92
|
+
const service = inner.sessionTelemetry ?? (typeof inner.get === "function" ? inner.get("sessionTelemetry") : null)
|
|
93
|
+
if (!service) return
|
|
94
|
+
const register = service.register ?? service.addBackend ?? service.use
|
|
95
|
+
if (typeof register !== "function") {
|
|
96
|
+
logger("sessionTelemetry 存在但没有 register/addBackend,保持回退模式")
|
|
97
|
+
return
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
service.register(telemetry)
|
|
101
|
+
seam = "sessionTelemetry"
|
|
102
|
+
logger("已挂载 sessionTelemetry 后端(sharing=full,脱敏规则已前置)")
|
|
103
|
+
} catch (error) {
|
|
104
|
+
logger(`挂载 sessionTelemetry 失败,降级:${String(error?.message ?? error)}`)
|
|
105
|
+
}
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
// 回退:只读消费 ledger,按小时补采会话级总量
|
|
109
|
+
ctx.inject(["ledger"], (inner) => {
|
|
110
|
+
const ledger = inner.ledger ?? (typeof inner.get === "function" ? inner.get("ledger") : null)
|
|
111
|
+
if (!ledger || seam !== "none") return
|
|
112
|
+
seam = "ledger"
|
|
113
|
+
logger("未找到 sessionTelemetry,降级为 ledger 会话级补采(无逐 step 粒度)")
|
|
114
|
+
const tick = async () => {
|
|
115
|
+
try {
|
|
116
|
+
const envelopes = await collectFromLedger(ledger, { rules: config.redactionRules })
|
|
117
|
+
if (envelopes.length > 0) outbox.append(envelopes)
|
|
118
|
+
} catch (error) {
|
|
119
|
+
logger(`ledger 补采失败:${String(error?.message ?? error)}`)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (typeof inner.effect === "function") inner.effect(() => {
|
|
123
|
+
timer = setInterval(tick, config.flushIntervalSeconds * 1000)
|
|
124
|
+
return () => clearInterval(timer)
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
} else {
|
|
128
|
+
logger("宿主不支持 ctx.inject,仅本地 spool 可用")
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
timer = setInterval(() => runFlush(), config.flushIntervalSeconds * 1000)
|
|
132
|
+
policyTimer = setInterval(() => runPolicy(), config.policyIntervalSeconds * 1000)
|
|
133
|
+
runPolicy()
|
|
134
|
+
|
|
135
|
+
const dispose = () => {
|
|
136
|
+
if (timer) clearInterval(timer)
|
|
137
|
+
if (policyTimer) clearInterval(policyTimer)
|
|
138
|
+
}
|
|
139
|
+
if (typeof ctx.effect === "function") ctx.effect(() => dispose)
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
status: () => ({
|
|
143
|
+
ready: true,
|
|
144
|
+
machineId: credentials.machineId,
|
|
145
|
+
hubUrl: config.hubUrl,
|
|
146
|
+
seam,
|
|
147
|
+
outbox: outbox.stats(),
|
|
148
|
+
telemetry: telemetry.stats(),
|
|
149
|
+
lastFlush,
|
|
150
|
+
policy: lastPolicy?.policy ? { version: lastPolicy.policy.version, etag: lastPolicy.etag } : null,
|
|
151
|
+
budget: budgetState,
|
|
152
|
+
}),
|
|
153
|
+
flush: runFlush,
|
|
154
|
+
policy: runPolicy,
|
|
155
|
+
dispose,
|
|
156
|
+
}
|
|
157
|
+
}
|