dsh-project-flow 0.0.0-stage → 0.8.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/CHANGELOG.md +189 -0
- package/LICENSE +128 -0
- package/README.md +422 -2
- package/aesthetic-library.mjs +288 -0
- package/aesthetic-seeds.mjs +373 -0
- package/aesthetic.mjs +273 -0
- package/assets/icon-180.png +0 -0
- package/assets/icon-256.png +0 -0
- package/assets/icon-512.png +0 -0
- package/client.js +1079 -0
- package/cordis.patch.yml +48 -0
- package/desktop.mjs +100 -0
- package/docs/COMMERCIAL.md +79 -0
- package/docs/DETAIL.md +279 -0
- package/docs/FEATURES.md +345 -0
- package/docs/LAUNCH.md +148 -0
- package/docs/MOMENTS.md +118 -0
- package/docs/RELEASE-0.3.0.md +52 -0
- package/docs/USAGE.md +232 -0
- package/domains.mjs +306 -0
- package/evidence.mjs +504 -0
- package/gate.mjs +389 -0
- package/icon.svg +12 -0
- package/index.js +5863 -0
- package/locale/en.json +24 -0
- package/locale/zh.json +24 -0
- package/package.json +85 -3
- package/prices.mjs +215 -0
- package/watchdog.mjs +583 -0
package/watchdog.mjs
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 执行守护器:三个熔断,各自独立,互不干扰。
|
|
3
|
+
*
|
|
4
|
+
* 次数熔断 —— Execution_Log.md 里同一个错出现 N 次,判为死循环
|
|
5
|
+
* 活性巡检 —— 一段时间内既没写文件也没有 API 返回,判为静默挂死
|
|
6
|
+
* 预算熔断 —— 每次 API 调用前查累计花费,超了硬断
|
|
7
|
+
*
|
|
8
|
+
* 设计上刻意不碰 runPipeline 的流程逻辑:它只对外提供一个 signal、
|
|
9
|
+
* 一个 beforeAttempt、一个 afterStage。熔断时 abort signal,主流程
|
|
10
|
+
* 那边一取消,runStage 自然收尾。
|
|
11
|
+
*
|
|
12
|
+
* 纯 Node,无外部依赖,不读 ctx。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { readFile, readdir, stat } from 'node:fs/promises'
|
|
16
|
+
import { join } from 'node:path'
|
|
17
|
+
import {
|
|
18
|
+
BUILTIN_PRICE,
|
|
19
|
+
FALLBACK_PRICE,
|
|
20
|
+
parseOverrideTable,
|
|
21
|
+
priceFor,
|
|
22
|
+
resolvePriceTable as resolvePriceTableFrom,
|
|
23
|
+
worstPrice as worstPriceFrom,
|
|
24
|
+
} from './prices.mjs'
|
|
25
|
+
|
|
26
|
+
export const FAULT = {
|
|
27
|
+
REPEAT: 'FAULT_HUMAN_INTERVENTION_REQUIRED',
|
|
28
|
+
SILENT: 'FAULT_SILENT_HANG',
|
|
29
|
+
BUDGET: 'FAULT_BUDGET_EXCEEDED',
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class WatchdogFault extends Error {
|
|
33
|
+
constructor(code, detail) {
|
|
34
|
+
super(`[${code}] ${detail}`)
|
|
35
|
+
this.name = 'WatchdogFault'
|
|
36
|
+
this.code = code
|
|
37
|
+
this.detail = detail
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 价目表的唯一实现在 prices.mjs。
|
|
43
|
+
*
|
|
44
|
+
* 这里只做转发,不再自己维护一份——以前 watchdog 和 index.js 各存一套价,
|
|
45
|
+
* 空表时的处理还不一样,同一个项目能报出两个差好几倍的钱数。
|
|
46
|
+
* 现在两边都从这里走,改价只改 prices.mjs 一处。
|
|
47
|
+
*/
|
|
48
|
+
export function resolvePriceTable(raw, models) {
|
|
49
|
+
return resolvePriceTableFrom(raw, models)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 表里最贵的一档。查不到模型的价钱时用它兜底,宁可估高。 */
|
|
53
|
+
export function worstPrice(table) {
|
|
54
|
+
return worstPriceFrom(table)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 内置已知价,给老调用方留的名字。 */
|
|
58
|
+
const DEFAULT_PRICE = BUILTIN_PRICE
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 美元折人民币的默认汇率。
|
|
62
|
+
*
|
|
63
|
+
* 价目表里全是美元/百万 token,用户的账单是人民币。
|
|
64
|
+
* 只在这个值没被配置覆盖时才用它——真正生效的是 settings.cnyRate
|
|
65
|
+
* (cordis.patch.yml 里默认 7,可以用 /flow-set 或 project-flow.json 改)。
|
|
66
|
+
*
|
|
67
|
+
* 这里**必须**接受外部传入,不能自己写死:以前这里固定 7.2,
|
|
68
|
+
* 而配置里是 7,同一个项目在 /flow-cost 和证据包里会报出两个不同的钱数。
|
|
69
|
+
*/
|
|
70
|
+
export const CNY_RATE = 7.2
|
|
71
|
+
|
|
72
|
+
/** 心跳扫描跳过这些目录:不让守护器自己的日志给自己当心跳。 */
|
|
73
|
+
const SKIP_DIRS = new Set([
|
|
74
|
+
'.project-flow', '.git', '.hg', '.svn',
|
|
75
|
+
'node_modules', '.venv', 'venv', '__pycache__',
|
|
76
|
+
'dist', 'build', 'target', '.next',
|
|
77
|
+
])
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 把一行日志归成一个错误指纹。
|
|
81
|
+
*
|
|
82
|
+
* 规则刻意放宽,否则同一个错因为行号偏移或对象名不同就认不出来,永远到不了阈值:
|
|
83
|
+
* - 行号一律抹掉
|
|
84
|
+
* - 中文错误描述后面的具体对象名(模块名、文件名)也抹掉,只留错误类别
|
|
85
|
+
* - 错误码先转大写再匹配,免得大小写让它分成两类
|
|
86
|
+
*/
|
|
87
|
+
export function fingerprint(line) {
|
|
88
|
+
if (typeof line !== 'string') return ''
|
|
89
|
+
const text = line.trim()
|
|
90
|
+
if (text === '') return ''
|
|
91
|
+
const hits = []
|
|
92
|
+
|
|
93
|
+
// 错误码只认 errno 白名单,大小写都算(ENOENT 和 enoent 是同一个东西)。
|
|
94
|
+
// 不能用「E + 3~10 个大写字母」这种形状匹配:整行转大写之后,EVIDENCE、EXPORT、
|
|
95
|
+
// EXECUTION 这类普通词全满足这个形状,会被当成错误码计数,正常运行攒够三次就误熔断。
|
|
96
|
+
const code = /\b(ENOENT|EACCES|EPERM|EEXIST|ENOTDIR|EISDIR|ENOSPC|EMFILE|ENFILE|ETIMEDOUT|ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|EADDRINUSE|EADDRNOTAVAIL|EPIPE|EAGAIN|EINTR|EINVAL|ENOMEM|ENOTEMPTY|ELOOP|ENAMETOOLONG|EROFS|EXDEV|EBUSY|EIO|ENODEV|ENXIO|ESPIPE|EOVERFLOW|ENOTSUP|EOPNOTSUPP|ESRCH|ECHILD)\b/iu.exec(text)
|
|
97
|
+
if (code !== null) hits.push(code[1].toLowerCase())
|
|
98
|
+
|
|
99
|
+
const rules = [
|
|
100
|
+
/(?:Error|Exception|错误|失败|异常)[::]\s*([^\n]{0,100})/u,
|
|
101
|
+
/([\w./-]+\.\w+):\d+/u, // 文件:行号 → 只留文件
|
|
102
|
+
/(command not found|permission denied|timed out|no such file|模块不存在|命令不存在|权限不足)/iu,
|
|
103
|
+
/(cannot find module|is not a function|is not defined|undefined is not)/iu,
|
|
104
|
+
]
|
|
105
|
+
for (const re of rules) {
|
|
106
|
+
const m = re.exec(text)
|
|
107
|
+
if (m === null) continue
|
|
108
|
+
const raw = (m[1] ?? m[0]).trim().toLowerCase().replace(/:\d+/gu, '')
|
|
109
|
+
// 去掉尾部挂着的英文标识符:「模块不存在 webpack」和「模块不存在 vite」是同一类
|
|
110
|
+
const core = raw.replace(/[\s::]*[a-z0-9_.\-/[\]]+$/u, '').trim()
|
|
111
|
+
hits.push((core === '' ? raw : core).slice(0, 80))
|
|
112
|
+
}
|
|
113
|
+
return hits.join('|')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 次数熔断:盯 Execution_Log.md。
|
|
118
|
+
*
|
|
119
|
+
* 靠 offset 只看新增内容。每次读整份的话,同一句话会被重复计数,
|
|
120
|
+
* 第二轮返工就误熔断。
|
|
121
|
+
*/
|
|
122
|
+
export class RepeatBreaker {
|
|
123
|
+
#logPath
|
|
124
|
+
#offset = 0
|
|
125
|
+
#seen = new Map()
|
|
126
|
+
#limit
|
|
127
|
+
#tripped
|
|
128
|
+
|
|
129
|
+
constructor({ logPath, limit = 3 }) {
|
|
130
|
+
this.#logPath = logPath
|
|
131
|
+
this.#limit = limit
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 每阶结束后调一次。返回命中的指纹和次数,没命中返回 undefined。 */
|
|
135
|
+
async check() {
|
|
136
|
+
if (this.#tripped !== undefined) return this.#tripped
|
|
137
|
+
const text = await readFile(this.#logPath, 'utf8').catch(() => '')
|
|
138
|
+
if (text.length <= this.#offset) return undefined
|
|
139
|
+
const fresh = text.slice(this.#offset)
|
|
140
|
+
this.#offset = text.length
|
|
141
|
+
|
|
142
|
+
for (const line of fresh.split(/\r?\n/u)) {
|
|
143
|
+
const key = fingerprint(line)
|
|
144
|
+
if (key === '') continue
|
|
145
|
+
const n = (this.#seen.get(key) ?? 0) + 1
|
|
146
|
+
this.#seen.set(key, n)
|
|
147
|
+
if (n >= this.#limit) {
|
|
148
|
+
this.#tripped = { key, count: n }
|
|
149
|
+
return this.#tripped
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 导出统计,写进 state.json 供 project_status 看。 */
|
|
156
|
+
summary() {
|
|
157
|
+
const top = [...this.#seen.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)
|
|
158
|
+
return top.map(([key, n]) => ({ key, count: n }))
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 活性巡检:三条信号,取较新的那条算「活着」。
|
|
164
|
+
*
|
|
165
|
+
* 文件写入 —— 扫工作区 mtime
|
|
166
|
+
* 子会话输出 —— 流式收到一段就 touch 一次
|
|
167
|
+
* API 返回 —— 每阶结束 beat 一次
|
|
168
|
+
*
|
|
169
|
+
* 第二条(touch)是补的一个洞:以前只有「每阶结束」才 beat,一阶跑一小时,
|
|
170
|
+
* 中间那一个小时在探针眼里跟卡死没区别。实测踩过——实施子会话一直在吐 token、
|
|
171
|
+
* 一直在写渲染图,累计 260k token / 114 步,却因为单阶超过 900 秒被判了
|
|
172
|
+
* FAULT_SILENT_HANG 掐掉。真正的静默是「连一个 token 都不再吐」,
|
|
173
|
+
* 只有接到了流上才分得出来。
|
|
174
|
+
*
|
|
175
|
+
* 跳掉 .project-flow 是关键:那里面 run.log 一直在写,
|
|
176
|
+
* 算进来等于心跳永远新鲜,这个熔断就废了。
|
|
177
|
+
*/
|
|
178
|
+
export class LivenessProbe {
|
|
179
|
+
#cwd
|
|
180
|
+
#windowMs
|
|
181
|
+
#lastFileWrite = 0
|
|
182
|
+
#lastBeat = Date.now()
|
|
183
|
+
#lastTouch = 0
|
|
184
|
+
#timer
|
|
185
|
+
#onSilent
|
|
186
|
+
#fired = false
|
|
187
|
+
|
|
188
|
+
constructor({ cwd, windowMs, onSilent }) {
|
|
189
|
+
this.#cwd = cwd
|
|
190
|
+
this.#windowMs = windowMs
|
|
191
|
+
this.#onSilent = onSilent
|
|
192
|
+
// 间隔跟着窗口走:窗口小就查得勤,窗口大就不折腾。
|
|
193
|
+
// 下限 200ms 是为了测试能验到判定本身,不是为了让线上跑这么快。
|
|
194
|
+
const interval = Math.min(15000, Math.max(200, Math.floor(windowMs / 4)))
|
|
195
|
+
this.#timer = setInterval(() => void this.#tick(), interval)
|
|
196
|
+
this.#timer.unref?.()
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
setWindow(ms) {
|
|
200
|
+
if (typeof ms === 'number' && ms > 0) this.#windowMs = ms
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
beat() {
|
|
204
|
+
this.#lastBeat = Date.now()
|
|
205
|
+
this.#fired = false
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* 子会话还在出东西:吐一段文本、跑完一次工具、回了一帧流。
|
|
210
|
+
* 这是「活着」最直接的证据,比文件 mtime 更早、更灵敏。
|
|
211
|
+
*/
|
|
212
|
+
touch() {
|
|
213
|
+
this.#lastTouch = Date.now()
|
|
214
|
+
if (this.#fired === true) this.#fired = false
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
get idleMs() {
|
|
218
|
+
return Date.now() - Math.max(this.#lastFileWrite, this.#lastBeat, this.#lastTouch)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async #tick() {
|
|
222
|
+
if (this.#fired) return
|
|
223
|
+
const newest = await newestMtime(this.#cwd, 0)
|
|
224
|
+
if (newest > this.#lastFileWrite) this.#lastFileWrite = newest
|
|
225
|
+
if (this.idleMs > this.#windowMs) {
|
|
226
|
+
this.#fired = true
|
|
227
|
+
this.#onSilent(Math.round(this.idleMs / 1000))
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
dispose() {
|
|
232
|
+
clearInterval(this.#timer)
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 工作区里最新的文件 mtime。限深限目录,别把整个盘扫一遍。 */
|
|
237
|
+
async function newestMtime(dir, depth) {
|
|
238
|
+
if (depth > 6) return 0
|
|
239
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
|
|
240
|
+
let newest = 0
|
|
241
|
+
for (const entry of entries) {
|
|
242
|
+
if (SKIP_DIRS.has(entry.name)) continue
|
|
243
|
+
const full = join(dir, entry.name)
|
|
244
|
+
if (entry.isDirectory()) {
|
|
245
|
+
const sub = await newestMtime(full, depth + 1)
|
|
246
|
+
if (sub > newest) newest = sub
|
|
247
|
+
continue
|
|
248
|
+
}
|
|
249
|
+
const info = await stat(full).catch(() => undefined)
|
|
250
|
+
if (info !== undefined && info.mtimeMs > newest) newest = info.mtimeMs
|
|
251
|
+
}
|
|
252
|
+
return newest
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* 预算熔断。
|
|
257
|
+
*
|
|
258
|
+
* 拿不到真实 usage,按字符估:中文约 1.5 字一 token,英文约 4 字符,
|
|
259
|
+
* 取 2.5 字符一 token 是个折中。估偏的方向不确定,所以上限要设得紧一点。
|
|
260
|
+
*/
|
|
261
|
+
export class BudgetBreaker {
|
|
262
|
+
#limitUsd
|
|
263
|
+
#price
|
|
264
|
+
#input = 0
|
|
265
|
+
#output = 0
|
|
266
|
+
#models = []
|
|
267
|
+
#cnyRate
|
|
268
|
+
/** 用户配置的价目表(已解析),查不到的模型靠它走族估算。 */
|
|
269
|
+
#overrides = {}
|
|
270
|
+
/**
|
|
271
|
+
* 按模型分开记账:model → { input, output }。
|
|
272
|
+
*
|
|
273
|
+
* 以前只有一个总数,出账时拿「用过的最贵那档单价」去乘全部 token——
|
|
274
|
+
* 规划用 kimi($0.60/$2.40)、实施用 flash($0.14/$0.28),
|
|
275
|
+
* 结果实施那几百万 token 也按 kimi 的价算,报出来的钱能虚高好几倍。
|
|
276
|
+
* 用户要的是「按各个模型的费率统计」,那就必须分开存、分开算。
|
|
277
|
+
*/
|
|
278
|
+
#byModel = new Map()
|
|
279
|
+
#current = ''
|
|
280
|
+
|
|
281
|
+
constructor({ limitUsd, priceTable, cnyRate }) {
|
|
282
|
+
this.#limitUsd = limitUsd
|
|
283
|
+
// 单测和直接 new 时不给价目表,就退回内置默认,别让花费恒为 0
|
|
284
|
+
this.#price = priceTable !== undefined && Object.keys(priceTable).length > 0
|
|
285
|
+
? priceTable
|
|
286
|
+
: DEFAULT_PRICE
|
|
287
|
+
// 用户配置的那部分单独留一份:查不到的模型要靠它走族估算
|
|
288
|
+
this.#overrides = parseOverrideTable(priceTable)
|
|
289
|
+
// 汇率跟着配置走。不传才退回内置默认,绝不在两处各写一个数。
|
|
290
|
+
this.#cnyRate = Number.isFinite(cnyRate) && cnyRate > 0 ? cnyRate : CNY_RATE
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
useModel(model) {
|
|
294
|
+
if (typeof model === 'string' && model !== '' && !this.#models.includes(model)) {
|
|
295
|
+
this.#models.push(model)
|
|
296
|
+
}
|
|
297
|
+
// 当前正在记账的模型:countInput / countOutput 落到它头上。
|
|
298
|
+
this.#current = typeof model === 'string' ? model : ''
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 取某一档模型的行;没有就现建一行。 */
|
|
302
|
+
#row(model) {
|
|
303
|
+
const key = model === '' ? '(未知)' : model
|
|
304
|
+
let row = this.#byModel.get(key)
|
|
305
|
+
if (row === undefined) {
|
|
306
|
+
row = { input: 0, output: 0 }
|
|
307
|
+
this.#byModel.set(key, row)
|
|
308
|
+
}
|
|
309
|
+
return row
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
#priceOf(model) {
|
|
313
|
+
// 表里有就用表里的;没有就现算——内置 → 型号族估算 → 最贵兜底。
|
|
314
|
+
// 这一步让「换任何模型都有价」成立:不再只有那三个代表型号才有数。
|
|
315
|
+
const hit = this.#price[model]
|
|
316
|
+
if (hit !== undefined) return hit
|
|
317
|
+
const priced = priceFor(model, this.#overrides)
|
|
318
|
+
return { input: priced.input, output: priced.output }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** 按用过的模型取最贵的那档,保守估。 */
|
|
322
|
+
#effective() {
|
|
323
|
+
if (this.#models.length === 0) return FALLBACK_PRICE
|
|
324
|
+
let worst = { input: 0, output: 0 }
|
|
325
|
+
for (const model of this.#models) {
|
|
326
|
+
const price = this.#price[model] ?? FALLBACK_PRICE
|
|
327
|
+
worst = {
|
|
328
|
+
input: Math.max(worst.input, price.input),
|
|
329
|
+
output: Math.max(worst.output, price.output),
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return worst
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** 每次 attempt 前累加这一轮的输入成本。 */
|
|
336
|
+
countInput(promptChars) {
|
|
337
|
+
const n = Math.ceil((promptChars ?? 0) / 2.5)
|
|
338
|
+
this.#input += n
|
|
339
|
+
this.#row(this.#current).input += n
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** 每次 attempt 结束后累加输出成本。 */
|
|
343
|
+
countOutput(replyChars) {
|
|
344
|
+
const n = Math.ceil((replyChars ?? 0) / 2.5)
|
|
345
|
+
this.#output += n
|
|
346
|
+
this.#row(this.#current).output += n
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* 逐模型账单:每个模型用自己的费率算自己的 token。
|
|
351
|
+
* 这是「按各个模型的费率统计」那个要求的落点。
|
|
352
|
+
*/
|
|
353
|
+
get breakdown() {
|
|
354
|
+
const rows = []
|
|
355
|
+
for (const [model, row] of this.#byModel) {
|
|
356
|
+
const price = this.#priceOf(model)
|
|
357
|
+
const usd = (row.input / 1e6) * price.input + (row.output / 1e6) * price.output
|
|
358
|
+
rows.push({
|
|
359
|
+
model,
|
|
360
|
+
inputTokens: row.input,
|
|
361
|
+
outputTokens: row.output,
|
|
362
|
+
totalTokens: row.input + row.output,
|
|
363
|
+
priceInput: price.input,
|
|
364
|
+
priceOutput: price.output,
|
|
365
|
+
estimatedUsd: Number(usd.toFixed(6)),
|
|
366
|
+
estimatedCny: Number((usd * this.#cnyRate).toFixed(4)),
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
rows.sort((a, b) => b.estimatedUsd - a.estimatedUsd)
|
|
370
|
+
return rows
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** 全项目累计的美元花费:逐模型加总,不是拿最贵单价套总数。 */
|
|
374
|
+
get spentUsd() {
|
|
375
|
+
let usd = 0
|
|
376
|
+
for (const row of this.breakdown) usd += row.estimatedUsd
|
|
377
|
+
return usd
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** 全项目累计人民币花费。 */
|
|
381
|
+
get spentCny() {
|
|
382
|
+
return Number((this.spentUsd * this.#cnyRate).toFixed(4))
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** 实际生效的汇率。快照要带它,别让读的人以为用的是别的数。 */
|
|
386
|
+
get cnyRate() {
|
|
387
|
+
return this.#cnyRate
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* 累计的 token 估算。完成证据包的 cost_incurred.input_tokens / output_tokens
|
|
392
|
+
* 直接取这个——没有它证据包每次都抛 undefined。
|
|
393
|
+
*/
|
|
394
|
+
get tokens() {
|
|
395
|
+
return { input: this.#input, output: this.#output }
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** 超了就抛。onAttempt 里调用,等于每次 API 调用前查一次。 */
|
|
399
|
+
assert() {
|
|
400
|
+
const spent = this.spentUsd
|
|
401
|
+
if (spent >= this.#limitUsd) {
|
|
402
|
+
throw new WatchdogFault(
|
|
403
|
+
FAULT.BUDGET,
|
|
404
|
+
`累计约 $${spent.toFixed(4)}(¥${this.spentCny.toFixed(2)}),已到上限 $${this.#limitUsd}(按字符估算,不是账单精确值)`,
|
|
405
|
+
)
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* 聚合器。对外只有四个方法,主流程除了换成它的 signal 之外不用改别的。
|
|
412
|
+
*/
|
|
413
|
+
export class Watchdog {
|
|
414
|
+
#repeat
|
|
415
|
+
#liveness
|
|
416
|
+
#budget
|
|
417
|
+
#controller = new AbortController()
|
|
418
|
+
#fault
|
|
419
|
+
#onTrip
|
|
420
|
+
|
|
421
|
+
constructor({ cwd, logPath, settings, onTrip }) {
|
|
422
|
+
this.#onTrip = onTrip
|
|
423
|
+
this.#repeat = new RepeatBreaker({
|
|
424
|
+
logPath,
|
|
425
|
+
limit: settings.maxRepeatErrors ?? 3,
|
|
426
|
+
})
|
|
427
|
+
this.#liveness = new LivenessProbe({
|
|
428
|
+
cwd,
|
|
429
|
+
windowMs: settings.silentMsBuild ?? 900000,
|
|
430
|
+
onSilent: seconds => this.#trip(FAULT.SILENT, `连续 ${seconds} 秒既没写文件也没有 API 返回,判定静默挂死`),
|
|
431
|
+
})
|
|
432
|
+
this.#budget = new BudgetBreaker({
|
|
433
|
+
limitUsd: settings.budgetUsd ?? 10,
|
|
434
|
+
priceTable: parsePriceTable(settings.priceTable),
|
|
435
|
+
cnyRate: settings.cnyRate,
|
|
436
|
+
})
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** 传给 runStage 的 signal。熔断时它被 abort,子会话当场收工。 */
|
|
440
|
+
get signal() {
|
|
441
|
+
return this.#controller.signal
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
get fault() {
|
|
445
|
+
return this.#fault
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
get spentUsd() {
|
|
449
|
+
return this.#budget.spentUsd
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** 累计人民币花费,逐模型加总后折算。 */
|
|
453
|
+
get spentCny() {
|
|
454
|
+
return this.#budget.spentCny
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** 逐模型账单。收尾时写进 state.json,也是 /flow-cost 的输出。 */
|
|
458
|
+
get breakdown() {
|
|
459
|
+
return this.#budget.breakdown
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** 累计 token 估算,完成证据包用。 */
|
|
463
|
+
get tokens() {
|
|
464
|
+
return this.#budget.tokens
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** 进某一阶时切静默窗口:规划短、实施和质检长。 */
|
|
468
|
+
beginStage(stage, model) {
|
|
469
|
+
this.#liveness.beat()
|
|
470
|
+
this.#currentStage = stage
|
|
471
|
+
const settings = this.#windowByStage(stage)
|
|
472
|
+
if (settings !== undefined) this.#liveness.setWindow(settings)
|
|
473
|
+
if (typeof model === 'string') this.#budget.useModel(model)
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* 子会话有产出就把心跳顶一下。runStage 每收到一段流、每结束一步都调它。
|
|
478
|
+
* 熔断已经触发过就不再动——否则 abort 之后还在吐的尾巴会把状态洗白。
|
|
479
|
+
*/
|
|
480
|
+
touch() {
|
|
481
|
+
if (this.#fault !== undefined) return
|
|
482
|
+
this.#liveness.touch()
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
#windowByStage(stage) {
|
|
486
|
+
if (stage === 2) return this.#silentPlan
|
|
487
|
+
if (stage === 3) return this.#silentBuild
|
|
488
|
+
if (stage === 4) return this.#silentCheck
|
|
489
|
+
return undefined
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
#silentPlan = 300000
|
|
493
|
+
#silentBuild = 900000
|
|
494
|
+
#silentCheck = 900000
|
|
495
|
+
|
|
496
|
+
/** 配三个窗口。 */
|
|
497
|
+
setWindows({ plan, build, check }) {
|
|
498
|
+
this.#silentPlan = plan ?? this.#silentPlan
|
|
499
|
+
this.#silentBuild = build ?? this.#silentBuild
|
|
500
|
+
this.#silentCheck = check ?? this.#silentCheck
|
|
501
|
+
// 探针一开始是按构造时的 silentMsBuild 起的;如果这时已经进了某一阶,
|
|
502
|
+
// 光改字段不改探针,正在跑的这一阶还留着旧窗口——配置改了不生效最难查。
|
|
503
|
+
// 已经把窗口切到当前阶段的,就用这个阶段的窗口回写一次。
|
|
504
|
+
if (this.#currentStage !== undefined) {
|
|
505
|
+
const window = this.#windowByStage(this.#currentStage)
|
|
506
|
+
if (window !== undefined) this.#liveness.setWindow(window)
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
#currentStage
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* 每次 API 调用前。先查预算(超了直接抛),再累加这次 attempt 的输入成本。
|
|
514
|
+
* 抛出来的 WatchdogFault 会被 runStage 的调用方接下,不会进重试。
|
|
515
|
+
*/
|
|
516
|
+
beforeAttempt(promptText) {
|
|
517
|
+
this.#budget.assert()
|
|
518
|
+
this.#budget.countInput(typeof promptText === 'string' ? promptText.length : 0)
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** 每阶结束后:记心跳、记输出成本、看一眼日志有没有死循环迹象。 */
|
|
522
|
+
async afterStage(outcome) {
|
|
523
|
+
// 已经熔断过了就不再累加:探针 dispose 之后 beat() 没有意义,
|
|
524
|
+
// 再往上抛错只会盖掉真正的熔断原因。
|
|
525
|
+
if (this.#fault !== undefined) return
|
|
526
|
+
this.#liveness.beat()
|
|
527
|
+
this.#budget.countOutput(typeof outcome?.text === 'string' ? outcome.text.length : 0)
|
|
528
|
+
|
|
529
|
+
const hit = await this.#repeat.check()
|
|
530
|
+
if (hit !== undefined) {
|
|
531
|
+
this.#trip(
|
|
532
|
+
FAULT.REPEAT,
|
|
533
|
+
`Execution_Log.md 里同一个错出现 ${hit.count} 次(${hit.key}),判定死循环`,
|
|
534
|
+
)
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* 给 state.json 用的快照。
|
|
540
|
+
*
|
|
541
|
+
* 带上人民币和逐模型账单:这两个数以前只在收尾写证据包时算一次,
|
|
542
|
+
* 中途停住(熔断、手动停)就再也看不到了——用户问「这单花了多少」
|
|
543
|
+
* 只能翻证据包,而证据包只在 PASS 之后才有。现在每阶结束都会落盘。
|
|
544
|
+
*/
|
|
545
|
+
snapshot() {
|
|
546
|
+
const tokens = this.tokens
|
|
547
|
+
return {
|
|
548
|
+
spentUsd: Number(this.spentUsd.toFixed(4)),
|
|
549
|
+
spentCny: this.spentCny,
|
|
550
|
+
cnyRate: this.#budget.cnyRate,
|
|
551
|
+
tokens,
|
|
552
|
+
totalTokens: tokens.input + tokens.output,
|
|
553
|
+
breakdown: this.breakdown,
|
|
554
|
+
repeats: this.#repeat.summary(),
|
|
555
|
+
trippedAt: this.#fault === undefined ? undefined : new Date().toISOString(),
|
|
556
|
+
code: this.#fault?.code,
|
|
557
|
+
detail: this.#fault?.detail,
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
#trip(code, detail) {
|
|
562
|
+
if (this.#fault !== undefined) return
|
|
563
|
+
this.#fault = new WatchdogFault(code, detail)
|
|
564
|
+
try {
|
|
565
|
+
this.#onTrip?.(this.#fault)
|
|
566
|
+
} catch {
|
|
567
|
+
// 回调失败不影响熔断本身
|
|
568
|
+
}
|
|
569
|
+
this.#controller.abort(this.#fault)
|
|
570
|
+
this.dispose()
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
dispose() {
|
|
574
|
+
this.#liveness.dispose()
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** 配置里的价目表是 JSON 字符串;写坏了就用内置默认,别让插件起不来。 */
|
|
579
|
+
function parsePriceTable(raw) {
|
|
580
|
+
// 统一走 resolvePriceTable:价目表的合并规则只该有一份实现,
|
|
581
|
+
// 否则「预算熔断用的价」和「预估用的价」迟早又会分家。
|
|
582
|
+
return resolvePriceTable(raw)
|
|
583
|
+
}
|