@thincoder/core 0.11.4 → 0.12.1
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 +33 -0
- package/abort-provenance.mjs +23 -0
- package/advisor/citations.mjs +5 -1
- package/advisor/compaction.mjs +13 -10
- package/advisor/history.mjs +6 -1
- package/advisor/loop.mjs +35 -10
- package/advisor/messages.mjs +31 -43
- package/advisor/project-context.mjs +49 -45
- package/advisor/run.mjs +82 -26
- package/advisor.mjs +40 -11
- package/agent/assemble.mjs +5 -5
- package/agent/chat-call.mjs +21 -1
- package/agent/completion.mjs +1 -20
- package/agent/dispatch-gates.mjs +8 -3
- package/agent/dispatch-run.mjs +131 -20
- package/agent/dispatch.mjs +23 -22
- package/agent/family-tools.mjs +4 -7
- package/agent/goal-judge.mjs +99 -0
- package/agent/goal-state.mjs +96 -0
- package/agent/helpers.mjs +13 -4
- package/agent/offload.mjs +1 -1
- package/agent/planning-graph-guardrail.mjs +224 -0
- package/agent/planning-prompt.mjs +179 -0
- package/agent/planning-step.mjs +460 -173
- package/agent/post-turn.mjs +23 -33
- package/agent/record-results.mjs +8 -5
- package/agent/run-stages.mjs +22 -41
- package/agent/run-start.mjs +26 -19
- package/agent/setup-reminders.mjs +16 -14
- package/agent/setup.mjs +3 -2
- package/agent/spawn-child.mjs +17 -4
- package/agent/suspension.mjs +42 -21
- package/agent/task-lifecycle.mjs +165 -52
- package/agent/timers.mjs +9 -1
- package/agent/turn-loop.mjs +160 -69
- package/agent/turn-projection.mjs +26 -15
- package/agent/turn-task-state.mjs +4 -4
- package/agent/write-gate-ledger.mjs +1 -1
- package/agent/write-gate.mjs +14 -11
- package/agent-tools/advisor-async.mjs +2 -0
- package/agent-tools/advisor-launch.mjs +27 -13
- package/agent-tools/advisor-settle.mjs +19 -18
- package/agent-tools/advisor.mjs +90 -13
- package/agent-tools/bash-async.mjs +3 -3
- package/agent-tools/batch-ledger-bind.mjs +8 -5
- package/agent-tools/batch-read.mjs +42 -0
- package/agent-tools/batch-record-write.mjs +20 -12
- package/agent-tools/batch-segment-vocab.mjs +6 -4
- package/agent-tools/batch-skeleton.mjs +43 -12
- package/agent-tools/consult.mjs +5 -1
- package/agent-tools/context.mjs +5 -4
- package/agent-tools/design-slots.mjs +7 -4
- package/agent-tools/design-token.mjs +3 -2
- package/agent-tools/doc-graph.mjs +257 -95
- package/agent-tools/escalate-async.mjs +4 -1
- package/agent-tools/goal.mjs +28 -95
- package/agent-tools/plan.mjs +1 -1
- package/agent-tools/review-facts.mjs +56 -7
- package/agent-tools/settings.mjs +35 -1
- package/agent-tools/ssh-transport.mjs +23 -22
- package/agent-tools/step.mjs +24 -4
- package/agent-tools/subagent-actions.mjs +6 -2
- package/agent-tools/subagent-async.mjs +4 -2
- package/agent-tools/subagent.mjs +1 -1
- package/agent-tools/task.mjs +73 -65
- package/agent-tools.mjs +3 -3
- package/agent.mjs +12 -3
- package/auto-think.mjs +16 -3
- package/browser/actions.mjs +5 -1
- package/browser/cdp.mjs +1 -1
- package/browser/pool.mjs +110 -17
- package/compaction-work-state.mjs +103 -13
- package/compress-form.mjs +29 -3
- package/config-defaults.mjs +27 -3
- package/config-io.mjs +3 -14
- package/config-normalize.mjs +24 -4
- package/config-presets.mjs +40 -26
- package/config-warn.mjs +30 -0
- package/config.mjs +139 -63
- package/context-degrade.mjs +4 -4
- package/context-push.mjs +20 -9
- package/context.mjs +65 -20
- package/doc-graph/anchors.mjs +39 -40
- package/doc-graph/clusters.mjs +49 -0
- package/doc-graph/code-parsers.mjs +494 -0
- package/doc-graph/context-pack.mjs +392 -0
- package/doc-graph/dir-signals.mjs +228 -0
- package/doc-graph/edges.mjs +231 -0
- package/doc-graph/format.mjs +70 -0
- package/doc-graph/gc-cmd.mjs +104 -0
- package/doc-graph/gc.mjs +112 -0
- package/doc-graph/glob-work-graph.mjs +307 -0
- package/doc-graph/golden-set.mjs +131 -0
- package/doc-graph/ls-work-graph.mjs +534 -0
- package/doc-graph/outline.mjs +377 -0
- package/doc-graph/output-annotations.mjs +85 -0
- package/doc-graph/process-docs.mjs +68 -0
- package/doc-graph/read-work-graph.mjs +91 -0
- package/doc-graph/rebuild-cmd.mjs +75 -0
- package/doc-graph/resolvers.mjs +322 -0
- package/doc-graph/roots.mjs +86 -0
- package/doc-graph/schema.mjs +110 -0
- package/doc-graph/search-augment.mjs +418 -0
- package/doc-graph/store.mjs +231 -0
- package/doc-graph/target-resolve.mjs +352 -0
- package/doc-graph/walk.mjs +87 -0
- package/doc-graph.mjs +583 -707
- package/explore-distill.mjs +52 -17
- package/generate-title.mjs +7 -4
- package/ledger-close.mjs +6 -6
- package/ledger-cmd.mjs +3 -3
- package/ledger-consistency.mjs +8 -6
- package/ledger-db.mjs +45 -10
- package/ledger-migrate.mjs +25 -10
- package/ledger-read.mjs +1 -1
- package/ledger-write-ops.mjs +6 -6
- package/ledger.mjs +2 -2
- package/model-context.mjs +54 -18
- package/model-specs.mjs +86 -67
- package/package.json +1 -1
- package/prompt-overlays.mjs +3 -3
- package/prompts/advisor-round1.md +6 -5
- package/prompts/common.md +16 -6
- package/prompts/consult-base.md +2 -1
- package/prompts/discipline-engineering.md +1 -1
- package/prompts/discipline-normal.md +12 -8
- package/prompts/knowledge/doc-lookup.md +2 -2
- package/prompts/knowledge/normal-batch-discipline.md +2 -2
- package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
- package/prompts/knowledge/tool-advisor.md +2 -2
- package/prompts/knowledge/tool-apply-patch.md +1 -1
- package/prompts/knowledge/tool-bash.md +2 -2
- package/prompts/knowledge/tool-batch.md +4 -4
- package/prompts/knowledge/tool-glob.md +9 -2
- package/prompts/knowledge/tool-goal.md +9 -6
- package/prompts/knowledge/tool-grep.md +7 -2
- package/prompts/knowledge/tool-ls.md +11 -5
- package/prompts/knowledge/tool-lsp.md +1 -1
- package/prompts/knowledge/tool-operations.md +3 -2
- package/prompts/knowledge/tool-plan.md +1 -1
- package/prompts/knowledge/tool-read.md +7 -6
- package/prompts/knowledge/tool-repo-graph-read.md +12 -0
- package/prompts/knowledge/tool-repo-graph.md +12 -0
- package/prompts/knowledge/tool-step.md +1 -1
- package/prompts/knowledge/tool-subagent.md +2 -2
- package/prompts/knowledge/tool-task.md +10 -9
- package/prompts/knowledge/tool-tree.md +7 -1
- package/prompts/persona-eng-coder.md +1 -1
- package/prompts/persona-eng-designer.md +1 -1
- package/prompts/persona-engineering.md +2 -1
- package/prompts/persona-explore.md +1 -1
- package/prompts/persona-normal.md +7 -6
- package/prompts/persona-plan.md +2 -2
- package/prompts/planning-next-moves.md +7 -8
- package/provider/anthropic.mjs +53 -51
- package/provider/core.mjs +85 -34
- package/provider/errors.mjs +33 -10
- package/provider/google.mjs +244 -37
- package/provider/list-models.mjs +28 -14
- package/provider/responses-request.mjs +15 -9
- package/provider/responses.mjs +10 -8
- package/provider/sse.mjs +3 -6
- package/proxy-transport.mjs +228 -119
- package/rules-file.mjs +79 -0
- package/rules.mjs +13 -51
- package/session-lifecycle.mjs +32 -20
- package/team-ledger.mjs +7 -7
- package/think-off.mjs +37 -18
- package/token-window.mjs +48 -31
- package/tool-args.mjs +8 -8
- package/tool-docs/bash.md +1 -1
- package/tool-docs/glob.md +3 -1
- package/tool-docs/goal.md +2 -2
- package/tool-docs/grep.md +3 -1
- package/tool-docs/ls.md +7 -1
- package/tool-docs/read.md +1 -1
- package/tool-docs/repo_graph-read.md +3 -0
- package/tool-docs/repo_graph.md +3 -0
- package/tool-docs/tree.md +1 -1
- package/tools/bash.mjs +53 -8
- package/tools/browser.mjs +4 -4
- package/tools/file.mjs +34 -7
- package/tools/glob-dialect.mjs +57 -7
- package/tools/index.mjs +3 -7
- package/tools/patch.mjs +8 -7
- package/tools/process-doc-mark.mjs +13 -0
- package/tools/search.mjs +152 -37
- package/tools/shared.mjs +6 -0
- package/tools/tree.mjs +211 -8
- package/window-policy.mjs +205 -126
- package/prompts/knowledge/tool-doc-graph-read.md +0 -20
- package/prompts/knowledge/tool-doc-graph.md +0 -49
- package/prompts/knowledge/tool-peek.md +0 -10
- package/prompts/knowledge/tool-repo-outline.md +0 -4
- package/tool-docs/doc_graph-read.md +0 -3
- package/tool-docs/doc_graph.md +0 -3
- package/tool-docs/peek.md +0 -3
- package/tool-docs/repo_outline.md +0 -3
- package/tools/peek.mjs +0 -447
package/provider/sse.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* provider/sse.mjs — SSE stream reader
|
|
3
3
|
* Extracted from core.mjs. Parses Server-Sent Events for LLM chat responses.
|
|
4
4
|
*/
|
|
5
|
-
import { abortError, timeoutError } from "../abort-provenance.mjs"
|
|
5
|
+
import { abortError, timeoutError, isUserInterrupt, markInterrupted } from "../abort-provenance.mjs"
|
|
6
6
|
import { terminateBody } from "../stream-destroy.mjs"
|
|
7
7
|
import { DEFAULT_BODY_IDLE_MS } from "../config-defaults.mjs"
|
|
8
8
|
// 推理回声的可空表示与累加(设计 = `docs/core/design/AGENT-LOOP.md` §5.4):`null` = 这一轮没给。
|
|
@@ -267,11 +267,8 @@ export async function readSSE(response, { onToken, onReasoning, rules, signal, f
|
|
|
267
267
|
processLines(buffer.split("\n"))
|
|
268
268
|
} catch (e) {
|
|
269
269
|
if (idleTimer) clearTimeout(idleTimer)
|
|
270
|
-
if (
|
|
271
|
-
result
|
|
272
|
-
result.interruptMessage = signal.reason.message
|
|
273
|
-
if (idleTimer) clearTimeout(idleTimer)
|
|
274
|
-
return result
|
|
270
|
+
if (isUserInterrupt(signal)) {
|
|
271
|
+
return markInterrupted(result, signal)
|
|
275
272
|
}
|
|
276
273
|
// #878:看门狗终结归类归一(abort 通道下底层错误形不定)——无内容 ⇒ idle 超时错误;
|
|
277
274
|
// 有部分内容 ⇒ partial + networkError(原径语义保持)。
|
package/proxy-transport.mjs
CHANGED
|
@@ -25,6 +25,212 @@ const HEADER_END = Buffer.from("\r\n\r\n")
|
|
|
25
25
|
/** content-encoding 解压器族(#1067——单 token 且已列 ⇒ 解压;identity ∥ 未知 ∥ 多 token 列表透传)。 */
|
|
26
26
|
const CE_DECODERS = { gzip: createGunzip, "x-gzip": createGunzip, deflate: createInflate, br: createBrotliDecompress }
|
|
27
27
|
|
|
28
|
+
/** 长度已知的体归一为可写给 socket 的形(string 原样交回——node 自带 UTF-8 编码;
|
|
29
|
+
* TypedArray ∥ DataView ∥ ArrayBuffer 归一为 Buffer 视图)。 */
|
|
30
|
+
function bodyForSocket(b) {
|
|
31
|
+
if (typeof b === "string" || Buffer.isBuffer(b)) return b
|
|
32
|
+
if (b instanceof ArrayBuffer) return Buffer.from(new Uint8Array(b))
|
|
33
|
+
return Buffer.from(b.buffer, b.byteOffset, b.byteLength)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 流形块的统一化:**一律产出 Buffer**——chunk 头按 `buf.length`(字节数)写,
|
|
37
|
+
* 与实际写出的字节必须严格同源;string 块原样过就会「头报字符数、体发字节数」。 */
|
|
38
|
+
function chunkBuffer(c) {
|
|
39
|
+
if (Buffer.isBuffer(c)) return c
|
|
40
|
+
if (typeof c === "string") return Buffer.from(c, "utf8")
|
|
41
|
+
return bodyForSocket(c)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 写请求段(`CODE-TIER.md` §3:`streamHttpResponse` ≥100 行 ⇒ 提取有独立语义的子函数)。
|
|
45
|
+
* 请求行 ∥ 头 ∥ 体分帧与写出;流形体的分帧与写侧背压同在此。
|
|
46
|
+
* **本函数的 `body` 是请求体**——响应体是 `streamHttpResponse` 内的 `PassThrough`(`const body`);
|
|
47
|
+
* 两者同名并存,勿混。
|
|
48
|
+
* `fail` 由调用方传入——它绑着响应侧状态(settle ∥ body 流),pump 的异步失败必须落到同一处。 */
|
|
49
|
+
function writeRequest({ sock, urlStr, target, method, headers, body, signal, absoluteForm, fail }) {
|
|
50
|
+
// 请求体分帧(2026-12-01):HTTP/1.1 下**带体请求必须自带分帧声明**,否则服务端按「没有体」处理——
|
|
51
|
+
// 实测 Google 回 411 Length Required、OpenAI 回 400 could-not-parse-JSON-body(体被丢弃)。
|
|
52
|
+
// 原实现只写头 + 体、零声明 ⇒ 代理隧道上一切带体 POST 都发不出体。
|
|
53
|
+
// 调用方已自带 `Content-Length` ∥ `Transfer-Encoding` ⇒ 不覆盖(可读性优先于猜测)。
|
|
54
|
+
const requestTarget = absoluteForm ? urlStr : `${target.pathname}${target.search}`
|
|
55
|
+
const callerKeys = new Set(Object.keys(headers).map((k) => k.toLowerCase()))
|
|
56
|
+
const framing = {}
|
|
57
|
+
// 「长度已知的体」= string ∥ Buffer ∥ TypedArray ∥ DataView ∥ ArrayBuffer(`Buffer.byteLength` 五者都支持);
|
|
58
|
+
// 其余(异步可迭代)按流处理——归一只认「长度能不能算出来」,不枚举具体类。
|
|
59
|
+
const bodyIsStream = body != null
|
|
60
|
+
&& !(typeof body === "string" || ArrayBuffer.isView(body) || body instanceof ArrayBuffer)
|
|
61
|
+
if (body != null && !callerKeys.has("content-length") && !callerKeys.has("transfer-encoding")) {
|
|
62
|
+
// UTF-8 字节数(不是 String.length——多字节字符按字符数发会截断体)
|
|
63
|
+
if (bodyIsStream) framing["Transfer-Encoding"] = "chunked"
|
|
64
|
+
else framing["Content-Length"] = String(Buffer.byteLength(body))
|
|
65
|
+
}
|
|
66
|
+
const lines = [`${method} ${requestTarget} HTTP/1.1`]
|
|
67
|
+
for (const [k, v] of Object.entries({ ...headers, ...framing, Host: target.hostname })) lines.push(`${k}: ${v}`)
|
|
68
|
+
lines.push("Connection: close", "", "")
|
|
69
|
+
sock.write(lines.join("\r\n"))
|
|
70
|
+
if (body == null) return
|
|
71
|
+
if (!bodyIsStream) {
|
|
72
|
+
sock.write(bodyForSocket(body))
|
|
73
|
+
return
|
|
74
|
+
}
|
|
75
|
+
// 流形体:逐块分帧(`<size>CRLF<data>CRLF`),结束写 `0` 块;abort 即停。
|
|
76
|
+
// 写侧背压:`write` 返 false ⇒ 等 `drain`(或对端先关)再写下一段,不把源流读空堆进内存。
|
|
77
|
+
// 两条监听必须互摘:否则 drain 先命中时 close 监听器残留,长流上累积到 MaxListeners 告警。
|
|
78
|
+
const drain = () => new Promise((resolve) => {
|
|
79
|
+
const done = () => {
|
|
80
|
+
sock.removeListener("drain", done)
|
|
81
|
+
sock.removeListener("close", done)
|
|
82
|
+
resolve()
|
|
83
|
+
}
|
|
84
|
+
sock.once("drain", done)
|
|
85
|
+
sock.once("close", done)
|
|
86
|
+
})
|
|
87
|
+
const pumpChunked = async () => {
|
|
88
|
+
try {
|
|
89
|
+
for await (const chunk of body) {
|
|
90
|
+
if (signal?.aborted) return
|
|
91
|
+
const buf = chunkBuffer(chunk)
|
|
92
|
+
if (buf.length === 0) continue
|
|
93
|
+
if (sock.write(`${buf.length.toString(16)}\r\n`) === false) await drain()
|
|
94
|
+
if (signal?.aborted) return
|
|
95
|
+
if (sock.write(buf) === false) await drain()
|
|
96
|
+
if (signal?.aborted) return
|
|
97
|
+
if (sock.write("\r\n") === false) await drain()
|
|
98
|
+
}
|
|
99
|
+
if (!signal?.aborted) sock.write("0\r\n\r\n")
|
|
100
|
+
} catch (e) {
|
|
101
|
+
// 头已带 `Transfer-Encoding: chunked` 发出——服务端会等体;不主动断则连接与 fd 悬挂
|
|
102
|
+
sock.destroy()
|
|
103
|
+
fail(e)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
pumpChunked()
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 响应头文本 → 状态码 + 头对象(键统一小写)。`CODE-TIER.md` §3 提取——纯函数,无外部状态。 */
|
|
110
|
+
function parseResponseHead(headerText) {
|
|
111
|
+
const statusMatch = headerText.match(/^HTTP\/\d\.\d (\d+)/)
|
|
112
|
+
const status = statusMatch ? Number(statusMatch[1]) : 502
|
|
113
|
+
const respHeaders = {}
|
|
114
|
+
for (const line of headerText.split("\r\n").slice(1)) {
|
|
115
|
+
const ci = line.indexOf(":")
|
|
116
|
+
if (ci > 0) respHeaders[line.slice(0, ci).trim().toLowerCase()] = line.slice(ci + 1).trim()
|
|
117
|
+
}
|
|
118
|
+
return { status, respHeaders }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 响应侧状态机(`CODE-TIER.md` §3:`streamHttpResponse` ≥100 行 ⇒ 提取有独立语义的子函数)。
|
|
122
|
+
* 五个可变态(`settled` ∥ `sink` ∥ `sawInput` ∥ `pausedUpstream` ∥ `idleTimer`)与它们的操作族
|
|
123
|
+
* (失败结算 / 空闲看门狗 / 背压暂停与恢复 / body 终止)共享同一份生命周期;另持监听器身份字段
|
|
124
|
+
* `onAbort`——abort 监听的**挂与摘都经它**(各存一份会让摘不到真监听器)。
|
|
125
|
+
* `fail` 是**错误唯一出口**(`writeRequest` ∥ socket 事件 ∥ 解压器共同引用):头阶段 reject、
|
|
126
|
+
* body 阶段终止流,判据 = `settled`。 */
|
|
127
|
+
function createResponseState({ sock, body, signal, timeout, bodyIdleMs, reject }) {
|
|
128
|
+
let timer = null
|
|
129
|
+
let onAbort = null
|
|
130
|
+
const st = {
|
|
131
|
+
settled: false,
|
|
132
|
+
idleTimer: null,
|
|
133
|
+
sink: null, // body 前解压器(单 token 已知 content-encoding 时建立——#1067;无则 null)
|
|
134
|
+
sawInput: false, // 解压器输入门(#1067):零输入(空体)+ CE 在场 ⇒ 不解压(零误报)
|
|
135
|
+
pausedUpstream: false, // 背压旗(#1087):sock.pause() 在场,幂等守卫
|
|
136
|
+
onAbort: null,
|
|
137
|
+
/** 头部阶段失败 reject;resolve 后失败则终止 body 流(for-await 抛出,不挂起) */
|
|
138
|
+
fail(err) {
|
|
139
|
+
st.cleanup()
|
|
140
|
+
if (!st.settled) { st.settled = true; reject(err) }
|
|
141
|
+
else destroyBody(body, err)
|
|
142
|
+
},
|
|
143
|
+
/** 清定时器与 abort 监听(幂等——多次进 fail / body 结束都安全)。abort 监听**只认 `st.onAbort`**:
|
|
144
|
+
* 监听器的挂/摘都经同一字段,否则改了一处会让另一处摘不到真监听器(静默泄漏)。 */
|
|
145
|
+
cleanup() {
|
|
146
|
+
clearTimeout(timer)
|
|
147
|
+
clearTimeout(st.idleTimer)
|
|
148
|
+
signal?.removeEventListener("abort", st.onAbort)
|
|
149
|
+
},
|
|
150
|
+
/** 摘 abort 监听(body 已结束——`close` 径收尾用;与 `cleanup` 分开是为了不误清 body 看门狗) */
|
|
151
|
+
detachAbort() { signal?.removeEventListener("abort", st.onAbort) },
|
|
152
|
+
/** 背压暂停上游源(#1087——幂等:排空前只暂停一次) */
|
|
153
|
+
pauseUpstream() { if (!st.pausedUpstream) { st.pausedUpstream = true; sock.pause() } },
|
|
154
|
+
/** 排空恢复上游源(#1087——暂停态对偶分支,幂等) */
|
|
155
|
+
resumeUpstream() { if (st.pausedUpstream) { st.pausedUpstream = false; sock.resume() } },
|
|
156
|
+
/** body 结束(幂等——`0` 块 ∥ 对端 close 两径都会到达;#1065):带 CE 且已收输入 ⇒ 先结解压器
|
|
157
|
+
* (flush 后经 pipe 结 body);零输入(空体 + CE 在场)⇒ 直结 body(sawInput 门——#1067,零误报)。 */
|
|
158
|
+
endBody() {
|
|
159
|
+
if (st.sink && st.sawInput) {
|
|
160
|
+
if (!st.sink.destroyed && !st.sink.writableEnded) st.sink.end()
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
if (!body.destroyed && !body.writableEnded) body.end()
|
|
164
|
+
},
|
|
165
|
+
/** 推入 body 前最后一级可写流(带 CE = 解压器 ∥ 无 CE = body——#1087 暂停触发级);
|
|
166
|
+
* `write()` 返 false ⇒ 暂停上游源(排空后 'drain' 恢复);终止后不再写(watchdog ∥ abort ∥
|
|
167
|
+
* `0` 块后余包,与非 chunked 径 pipe 自摘语义齐)。 */
|
|
168
|
+
pushDownstream(chunk) {
|
|
169
|
+
const target = st.sink ?? body
|
|
170
|
+
if (target.destroyed || target.writableEnded) return
|
|
171
|
+
if (st.sink) st.sawInput = true
|
|
172
|
+
if (target.write(chunk) === false) st.pauseUpstream()
|
|
173
|
+
},
|
|
174
|
+
/** body 阶段空闲看门狗:每次数据到达重置;无数据超时 → 断流(流式消费方抛错) */
|
|
175
|
+
armIdle() {
|
|
176
|
+
clearTimeout(st.idleTimer)
|
|
177
|
+
if (bodyIdleMs > 0) st.idleTimer = setTimeout(() => destroyBody(body, timeoutError("Response body timeout (idle)", "provider", "proxy-body-idle")), bodyIdleMs)
|
|
178
|
+
},
|
|
179
|
+
/** 头到齐:置 settle 位 → 清头阶段定时器与 abort 监听 → 装 body 看门狗(三步顺序有依赖,收在一处) */
|
|
180
|
+
settle() {
|
|
181
|
+
st.settled = true
|
|
182
|
+
st.cleanup()
|
|
183
|
+
st.armIdle()
|
|
184
|
+
},
|
|
185
|
+
/** body 结束收尾(`close` 径):清看门狗、摘 abort 监听;终止时上游仍在背压暂停态 ⇒ 先恢复再销毁源
|
|
186
|
+
* (#1087 评审 F3:被暂停的 sock 不因 body 消亡自行关闭——悬挂口)。 */
|
|
187
|
+
finishBody() {
|
|
188
|
+
clearTimeout(st.idleTimer)
|
|
189
|
+
st.detachAbort()
|
|
190
|
+
if (st.pausedUpstream) { st.resumeUpstream(); sock.destroy() }
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
timer = setTimeout(() => st.fail(timeoutError("Response timeout", "provider", "proxy-header")), timeout)
|
|
194
|
+
onAbort = () => { sock.destroy(); st.fail(abortError(signal, "provider", "proxy")) }
|
|
195
|
+
st.onAbort = onAbort
|
|
196
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
197
|
+
return st
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 响应体分径接线(`CODE-TIER.md` §3 提取):TE 剥帧 ∥ CE 解压 ∥ 原样直写三条径的接法与顺序
|
|
201
|
+
* (#1065 ∥ #1067 ∥ #1087),含剩余字节的首段交接。状态操作一律经 `st`(暂停 / 恢复 / 终止同源)。 */
|
|
202
|
+
function attachResponseBody({ sock, body, respHeaders, remaining, st }) {
|
|
203
|
+
// 判定按 Transfer-Encoding 末段 token(大小写不敏感);头缺席而帧在场(协议违规)不解码
|
|
204
|
+
const chunked = (respHeaders["transfer-encoding"] ?? "").split(",").pop().trim().toLowerCase() === "chunked"
|
|
205
|
+
// 内容编码解压阶段(#1067——TE 剥帧后接,chunked ∥ 非 chunked 两径同点):单 token 且已列编码
|
|
206
|
+
// 建解压器;identity ∥ 头缺席 ∥ 未知编码 ∥ 多 token 列表 ⇒ 透传零动。请求头零改(不发
|
|
207
|
+
// Accept-Encoding——上游自发压缩才走本阶段)。
|
|
208
|
+
const ceTokens = (respHeaders["content-encoding"] ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
|
|
209
|
+
const ceFactory = ceTokens.length === 1 ? CE_DECODERS[ceTokens[0]] : undefined
|
|
210
|
+
if (ceFactory) {
|
|
211
|
+
st.sink = ceFactory()
|
|
212
|
+
// 解压失败 ⇒ body 以明错误终止(部分解码已发生——无「原字节」可回退);解压器 ⇒ body 走 pipe
|
|
213
|
+
// (自带背压:body 慢 ⇒ 解压器停 ⇒ 其可写侧涨满 ⇒ 推送分支暂停源)。
|
|
214
|
+
st.sink.on("error", (e) => st.fail(new Error(`Response body decompression failed (content-encoding: ${ceTokens[0]}): ${e.message}`)))
|
|
215
|
+
st.sink.pipe(body)
|
|
216
|
+
}
|
|
217
|
+
if (chunked) {
|
|
218
|
+
// chunked 径:解码器剥帧 ⇒ 逐段推入 body 前最后一级(带 CE = 解压器;函数式改写——body 本体零替换);
|
|
219
|
+
// 不再 pipe——body 由解码器 onData/onEnd 驱动
|
|
220
|
+
const decoder = createChunkedDecoder({ onData: st.pushDownstream, onEnd: st.endBody })
|
|
221
|
+
sock.on("data", (c) => decoder.push(c)) // 推送分支 = 背压暂停点(#1087:write() 返 false ⇒ sock.pause())
|
|
222
|
+
decoder.push(remaining)
|
|
223
|
+
} else if (st.sink) {
|
|
224
|
+
// 非 chunked 径 · 带 CE:源 ⇒ 解压器(推送分支同形——背压暂停点同判)
|
|
225
|
+
if (remaining.length > 0) st.pushDownstream(remaining)
|
|
226
|
+
sock.on("data", (c) => st.pushDownstream(c))
|
|
227
|
+
} else {
|
|
228
|
+
// 非 chunked 径 · 无 CE:原样直写 + pipe(现状语义,零动)
|
|
229
|
+
if (remaining.length > 0) body.write(remaining)
|
|
230
|
+
sock.pipe(body)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
28
234
|
/**
|
|
29
235
|
* 在已建立的 socket 上发 HTTP 请求,响应头到齐即 resolve(流式)。
|
|
30
236
|
* 返回 Response-like: { ok, status, headers: Headers, body: PassThrough(异步迭代), text(): Promise<string> }
|
|
@@ -36,8 +242,8 @@ const CE_DECODERS = { gzip: createGunzip, "x-gzip": createGunzip, deflate: creat
|
|
|
36
242
|
* absoluteForm: 请求行发绝对 URI(http:// 目标的经典代理转发用),默认发 origin-form。
|
|
37
243
|
* 2026-08-31 会诊 #4:timeout 只覆盖"响应头阶段";settle 后 body 空闲 > bodyIdleMs 即
|
|
38
244
|
* 断流(原实现头部 timer 到齐即清,流式中途停摆会无限挂起直到用户 Ctrl+C)。
|
|
39
|
-
* bodyIdleMs 缺省 = DEFAULT_BODY_IDLE_MS(与 `agent.bodyIdleTimeoutMs`
|
|
40
|
-
*
|
|
245
|
+
* bodyIdleMs 缺省 = DEFAULT_BODY_IDLE_MS(与 `agent.bodyIdleTimeoutMs` 同源);≤ 0 ⇒ **不装看门狗**
|
|
246
|
+
* (生产路径经 `effectiveBodyIdleMs` 回退缺省值,走不到这条——它只在直调本函数的用例里出现)。
|
|
41
247
|
* 导出供测试(裸 socket,无需 TLS/CONNECT);生产路径走 tunnelHttps / proxyFetch。
|
|
42
248
|
*/
|
|
43
249
|
export function streamHttpResponse(sock, urlStr, opts = {}, timeout = FETCH_TIMEOUT, absoluteForm = false, bodyIdleMs = DEFAULT_BODY_IDLE_MS) {
|
|
@@ -50,130 +256,38 @@ export function streamHttpResponse(sock, urlStr, opts = {}, timeout = FETCH_TIME
|
|
|
50
256
|
if (signal?.aborted) { sock.destroy(); return reject(abortError(signal, "provider", "proxy")) }
|
|
51
257
|
|
|
52
258
|
const body = new PassThrough()
|
|
53
|
-
let settled = false
|
|
54
259
|
let headerBuf = Buffer.alloc(0) // 头阶段按字节累积(#1065 K5——替代 utf8 往返)
|
|
55
|
-
|
|
56
|
-
let sink = null // body 前解压器(单 token 已知 content-encoding 时建立——#1067;无则 null)
|
|
57
|
-
let sawInput = false // 解压器输入门(#1067):零输入(空体)+ CE 在场 ⇒ 不解压(零误报)
|
|
58
|
-
let pausedUpstream = false // 背压旗(#1087):sock.pause() 在场,幂等守卫
|
|
59
|
-
|
|
60
|
-
const timer = setTimeout(() => fail(timeoutError("Response timeout", "provider", "proxy-header")), timeout)
|
|
61
|
-
const onAbort = () => { sock.destroy(); fail(abortError(signal, "provider", "proxy")) }
|
|
62
|
-
signal?.addEventListener("abort", onAbort, { once: true })
|
|
63
|
-
|
|
64
|
-
function cleanup() {
|
|
65
|
-
clearTimeout(timer)
|
|
66
|
-
clearTimeout(idleTimer)
|
|
67
|
-
signal?.removeEventListener("abort", onAbort)
|
|
68
|
-
}
|
|
69
|
-
/** 头部阶段失败 reject;resolve 后失败则终止 body 流(for-await 抛出,不挂起) */
|
|
70
|
-
function fail(err) {
|
|
71
|
-
cleanup()
|
|
72
|
-
if (!settled) { settled = true; reject(err) }
|
|
73
|
-
else destroyBody(body, err)
|
|
74
|
-
}
|
|
75
|
-
/** 背压暂停上游源(#1087——幂等:排空前只暂停一次) */
|
|
76
|
-
function pauseUpstream() {
|
|
77
|
-
if (!pausedUpstream) { pausedUpstream = true; sock.pause() }
|
|
78
|
-
}
|
|
79
|
-
/** 排空恢复上游源(#1087——暂停态对偶分支,幂等) */
|
|
80
|
-
function resumeUpstream() {
|
|
81
|
-
if (pausedUpstream) { pausedUpstream = false; sock.resume() }
|
|
82
|
-
}
|
|
83
|
-
/** body 结束(幂等——`0` 块 ∥ 对端 close 两径都会到达;#1065):带 CE 且已收输入 ⇒ 先结解压器
|
|
84
|
-
* (flush 后经 pipe 结 body);零输入(空体 + CE 在场)⇒ 直结 body(sawInput 门——#1067,零误报)。 */
|
|
85
|
-
function endBody() {
|
|
86
|
-
if (sink && sawInput) {
|
|
87
|
-
if (!sink.destroyed && !sink.writableEnded) sink.end()
|
|
88
|
-
return
|
|
89
|
-
}
|
|
90
|
-
if (!body.destroyed && !body.writableEnded) body.end()
|
|
91
|
-
}
|
|
92
|
-
/** 推入 body 前最后一级可写流(带 CE = 解压器 ∥ 无 CE = body——#1087 暂停触发级);
|
|
93
|
-
* `write()` 返 false ⇒ 暂停上游源(排空后 'drain' 恢复);终止后不再写(watchdog ∥ abort ∥
|
|
94
|
-
* `0` 块后余包,与非 chunked 径 pipe 自摘语义齐)。 */
|
|
95
|
-
function pushDownstream(chunk) {
|
|
96
|
-
const target = sink ?? body
|
|
97
|
-
if (target.destroyed || target.writableEnded) return
|
|
98
|
-
if (sink) sawInput = true
|
|
99
|
-
if (target.write(chunk) === false) pauseUpstream()
|
|
100
|
-
}
|
|
101
|
-
/** body 阶段空闲看门狗:每次数据到达重置;无数据超时 → 断流(流式消费方抛错) */
|
|
102
|
-
function armIdle() {
|
|
103
|
-
clearTimeout(idleTimer)
|
|
104
|
-
if (bodyIdleMs > 0) idleTimer = setTimeout(() => destroyBody(body, timeoutError("Response body timeout (idle)", "provider", "proxy-body-idle")), bodyIdleMs)
|
|
105
|
-
}
|
|
260
|
+
const st = createResponseState({ sock, body, signal, timeout, bodyIdleMs, reject })
|
|
106
261
|
|
|
107
262
|
sock.on("data", (d) => {
|
|
108
|
-
if (settled) return // 理论上不会发生(settle 后摘掉本监听器),防御
|
|
263
|
+
if (st.settled) return // 理论上不会发生(settle 后摘掉本监听器),防御
|
|
109
264
|
headerBuf = headerBuf.length > 0 ? Buffer.concat([headerBuf, d]) : d
|
|
110
265
|
const idx = headerBuf.indexOf(HEADER_END)
|
|
111
266
|
if (idx < 0) return
|
|
112
267
|
|
|
113
|
-
const
|
|
114
|
-
const statusMatch = headerText.match(/^HTTP\/\d\.\d (\d+)/)
|
|
115
|
-
const status = statusMatch ? Number(statusMatch[1]) : 502
|
|
116
|
-
const respHeaders = {}
|
|
117
|
-
for (const line of headerText.split("\r\n").slice(1)) {
|
|
118
|
-
const ci = line.indexOf(":")
|
|
119
|
-
if (ci > 0) respHeaders[line.slice(0, ci).trim().toLowerCase()] = line.slice(ci + 1).trim()
|
|
120
|
-
}
|
|
268
|
+
const { status, respHeaders } = parseResponseHead(headerBuf.subarray(0, idx).toString("utf8"))
|
|
121
269
|
|
|
122
270
|
// 头到齐:摘掉头阶段监听;剩余字节(字节副本)按 TE 分径交接
|
|
123
271
|
sock.removeAllListeners("data")
|
|
124
|
-
|
|
125
|
-
cleanup()
|
|
126
|
-
armIdle()
|
|
272
|
+
st.settle()
|
|
127
273
|
const remaining = Buffer.from(headerBuf.subarray(idx + 4))
|
|
128
|
-
|
|
129
|
-
const chunked = (respHeaders["transfer-encoding"] ?? "").split(",").pop().trim().toLowerCase() === "chunked"
|
|
130
|
-
// 内容编码解压阶段(#1067——TE 剥帧后接,chunked ∥ 非 chunked 两径同点):单 token 且已列编码
|
|
131
|
-
// 建解压器;identity ∥ 头缺席 ∥ 未知编码 ∥ 多 token 列表 ⇒ 透传零动。请求头零改(不发
|
|
132
|
-
// Accept-Encoding——上游自发压缩才走本阶段)。
|
|
133
|
-
const ceTokens = (respHeaders["content-encoding"] ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
|
|
134
|
-
const ceFactory = ceTokens.length === 1 ? CE_DECODERS[ceTokens[0]] : undefined
|
|
135
|
-
if (ceFactory) {
|
|
136
|
-
sink = ceFactory()
|
|
137
|
-
// 解压失败 ⇒ body 以明错误终止(部分解码已发生——无「原字节」可回退);解压器 ⇒ body 走 pipe
|
|
138
|
-
// (自带背压:body 慢 ⇒ 解压器停 ⇒ 其可写侧涨满 ⇒ 推送分支暂停源)。
|
|
139
|
-
sink.on("error", (e) => fail(new Error(`Response body decompression failed (content-encoding: ${ceTokens[0]}): ${e.message}`)))
|
|
140
|
-
sink.pipe(body)
|
|
141
|
-
}
|
|
142
|
-
if (chunked) {
|
|
143
|
-
// chunked 径:解码器剥帧 ⇒ 逐段推入 body 前最后一级(带 CE = 解压器;函数式改写——body 本体零替换);
|
|
144
|
-
// 不再 pipe——body 由解码器 onData/onEnd 驱动
|
|
145
|
-
const decoder = createChunkedDecoder({ onData: pushDownstream, onEnd: endBody })
|
|
146
|
-
sock.on("data", (c) => decoder.push(c)) // 推送分支 = 背压暂停点(#1087:write() 返 false ⇒ sock.pause())
|
|
147
|
-
decoder.push(remaining)
|
|
148
|
-
} else if (sink) {
|
|
149
|
-
// 非 chunked 径 · 带 CE:源 ⇒ 解压器(推送分支同形——背压暂停点同判)
|
|
150
|
-
if (remaining.length > 0) pushDownstream(remaining)
|
|
151
|
-
sock.on("data", pushDownstream)
|
|
152
|
-
} else {
|
|
153
|
-
// 非 chunked 径 · 无 CE:原样直写 + pipe(现状语义,零动)
|
|
154
|
-
if (remaining.length > 0) body.write(remaining)
|
|
155
|
-
sock.pipe(body)
|
|
156
|
-
}
|
|
274
|
+
attachResponseBody({ sock, body, respHeaders, remaining, st })
|
|
157
275
|
// 空闲看门狗随数据到达重置。注意必须用 'readable' 而非 'data':
|
|
158
276
|
// 'data' 监听把流切成 flowing 模式,会抢走 readSSE/for-await 未来得及认领的
|
|
159
277
|
// 已写缓冲(2026-08-31 实测:分包响应头的 remaining 首段被吞,readSSE 等不到 ack)。
|
|
160
278
|
// 'readable' 不改变流模式,数据仍由消费方按需拉取。
|
|
161
|
-
body.on("readable", armIdle)
|
|
279
|
+
body.on("readable", st.armIdle)
|
|
162
280
|
// 背压排空 = 消费进度信号(#1087——防「暂停期无数据到达」把慢而健康的消费者误杀)。
|
|
163
|
-
body.on("drain", armIdle)
|
|
281
|
+
body.on("drain", st.armIdle)
|
|
164
282
|
// 背压对偶分支:排空 ⇒ 恢复上游源。带 CE 时恢复信号在解压器(body 经 pipe 先恢复解压器——链传导);
|
|
165
283
|
// 无 CE 时 body 即最后一级 ⇒ 其 drain 即恢复点。
|
|
166
|
-
if (sink) sink.on("drain", resumeUpstream)
|
|
167
|
-
else body.on("drain", resumeUpstream)
|
|
168
|
-
// body 结束后才移除 abort 监听(流式中途 abort
|
|
169
|
-
body.on("close", () =>
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
// 被暂停的 sock 不因 body 消亡自行关闭(悬挂口)。
|
|
174
|
-
if (pausedUpstream) { pausedUpstream = false; sock.resume(); sock.destroy() }
|
|
175
|
-
})
|
|
176
|
-
signal?.addEventListener("abort", onAbort, { once: true })
|
|
284
|
+
if (st.sink) st.sink.on("drain", st.resumeUpstream)
|
|
285
|
+
else body.on("drain", st.resumeUpstream)
|
|
286
|
+
// body 结束后才移除 abort 监听(流式中途 abort 要能终止流);空闲看门狗与背压暂停态同在一处收尾
|
|
287
|
+
body.on("close", () => st.finishBody())
|
|
288
|
+
// 头阶段那条 abort 监听已被 `st.settle()` → `cleanup()` 摘除,这里是为 **body 阶段重新挂上**——
|
|
289
|
+
// 不是重复注册;删掉这一行,流式中途 abort 就不再终止流(静默退化)。
|
|
290
|
+
signal?.addEventListener("abort", st.onAbort, { once: true })
|
|
177
291
|
|
|
178
292
|
resolve({
|
|
179
293
|
ok: status >= 200 && status < 400,
|
|
@@ -188,23 +302,18 @@ export function streamHttpResponse(sock, urlStr, opts = {}, timeout = FETCH_TIME
|
|
|
188
302
|
})
|
|
189
303
|
})
|
|
190
304
|
sock.on("close", () => {
|
|
191
|
-
if (!settled) fail(new Error("Connection closed before response"))
|
|
192
|
-
else endBody()
|
|
305
|
+
if (!st.settled) st.fail(new Error("Connection closed before response"))
|
|
306
|
+
else st.endBody()
|
|
193
307
|
})
|
|
194
308
|
// 头部阶段的传输错误统一包装为稳定契约(对端 RST 会抛原生 ECONNRESET,调用方难判别);
|
|
195
309
|
// resolve 后的 body 阶段保留原始错误终止流
|
|
196
310
|
sock.on("error", (e) => {
|
|
197
|
-
if (!settled) fail(new Error(`Connection closed before response (${e.code ?? e.message})`))
|
|
198
|
-
else fail(e)
|
|
311
|
+
if (!st.settled) st.fail(new Error(`Connection closed before response (${e.code ?? e.message})`))
|
|
312
|
+
else st.fail(e)
|
|
199
313
|
})
|
|
200
314
|
|
|
201
|
-
//
|
|
202
|
-
|
|
203
|
-
const lines = [`${method} ${requestTarget} HTTP/1.1`]
|
|
204
|
-
for (const [k, v] of Object.entries({ ...headers, Host: target.hostname })) lines.push(`${k}: ${v}`)
|
|
205
|
-
lines.push("Connection: close", "", "")
|
|
206
|
-
sock.write(lines.join("\r\n"))
|
|
207
|
-
if (opts.body) sock.write(opts.body)
|
|
315
|
+
// 写请求(提取到 `writeRequest`——`CODE-TIER.md` §3 函数档位;`absoluteForm` = 代理转发时请求行用绝对 URI)
|
|
316
|
+
writeRequest({ sock, urlStr, target, method, headers, body: opts.body, signal, absoluteForm, fail: st.fail })
|
|
208
317
|
})
|
|
209
318
|
}
|
|
210
319
|
|
package/rules-file.mjs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rules-file.mjs — stream 规则(`.thincoder/rules/*.md`)的**发现与合并**单源(A 面)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成档(2026-12-01):`config.mjs` 的装载期归一要用 `mergeFileRules`(批 #109 把
|
|
5
|
+
* stream 规则合并从装配期挪到装载期,三端同源)。而 `rules.mjs` 同时承载 B 面(`.cursor/rules`),
|
|
6
|
+
* 它 import `agent/helpers.mjs` 的 `FILE_MUTATORS`,而 `agent/helpers.mjs` 再出口
|
|
7
|
+
* `agent/offload.mjs`,后者 `import { configDir } from "../config.mjs"` ——
|
|
8
|
+
* `config → rules → helpers → offload → config` 成一个环:`rules.mjs` 顶层
|
|
9
|
+
* `const PATH_TOOLS = new Set([...FILE_MUTATORS, …])` 在 `helpers` 尚未初始化时读 `FILE_MUTATORS`,
|
|
10
|
+
* 抛 `ReferenceError: Cannot access 'FILE_MUTATORS' before initialization`(单独
|
|
11
|
+
* `import agent/helpers.mjs` 即复现,5 个集成用例连带红)。
|
|
12
|
+
*
|
|
13
|
+
* 本档只依赖 `node:fs` ∥ `node:path` ∥ `./markdown.mjs`(后者零 import,同属叶层),
|
|
14
|
+
* 所以 `config.mjs` 直连本档不成环。`rules.mjs` 再出口两件,`agent/assemble.mjs` 的导入面零改。
|
|
15
|
+
*
|
|
16
|
+
* 面定义(权威)= `docs/core/design/WORKSPACE.md` §2.3「规则发现面(一线程一语义)」:
|
|
17
|
+
* `.thincoder/rules/*` 恒 = stream 规则。
|
|
18
|
+
*
|
|
19
|
+
* Stream rule file format (markdown + YAML frontmatter):
|
|
20
|
+
* ---
|
|
21
|
+
* pattern: "console\\.log"
|
|
22
|
+
* action: abort # "abort"|"warn" (default: "warn")
|
|
23
|
+
* repeat: once # "once"|"always" (default: "always")
|
|
24
|
+
* ---
|
|
25
|
+
* Use the project logger instead of console.log.
|
|
26
|
+
*
|
|
27
|
+
* The body becomes the rule message; if empty, falls back to `message` frontmatter.
|
|
28
|
+
*/
|
|
29
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs"
|
|
30
|
+
import { join } from "node:path"
|
|
31
|
+
import { parseFrontmatter } from "./markdown.mjs"
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Scan `.thincoder/rules/` in the project root for `.md` rule files.
|
|
35
|
+
* Returns an array of rule objects compatible with config.streamRules format.
|
|
36
|
+
*/
|
|
37
|
+
export function discoverRules(projectRoot) {
|
|
38
|
+
const rulesDir = join(projectRoot, ".thincoder", "rules")
|
|
39
|
+
if (!existsSync(rulesDir)) return []
|
|
40
|
+
|
|
41
|
+
const rules = []
|
|
42
|
+
let entries
|
|
43
|
+
try { entries = readdirSync(rulesDir) } catch { return rules }
|
|
44
|
+
|
|
45
|
+
for (const f of entries) {
|
|
46
|
+
if (!f.endsWith(".md")) continue
|
|
47
|
+
try {
|
|
48
|
+
const text = readFileSync(join(rulesDir, f), "utf8")
|
|
49
|
+
const fm = text.match(/^---\r?\n([\s\S]*?)\r?\n---/)
|
|
50
|
+
if (!fm) continue
|
|
51
|
+
const meta = parseFrontmatter(fm[1])
|
|
52
|
+
const body = text.slice(fm[0].length).trim()
|
|
53
|
+
if (!meta.pattern) continue
|
|
54
|
+
// Strip surrounding quotes from frontmatter values (parseFrontmatter returns raw)
|
|
55
|
+
const pattern = meta.pattern.replace(/^"(.*)"$/s, "$1").replace(/^'(.*)'$/s, "$1")
|
|
56
|
+
const message = (meta.message || "").replace(/^"(.*)"$/s, "$1").replace(/^'(.*)'$/s, "$1")
|
|
57
|
+
|
|
58
|
+
rules.push({
|
|
59
|
+
pattern,
|
|
60
|
+
message: body || message || "",
|
|
61
|
+
action: meta.action || "warn",
|
|
62
|
+
repeat: meta.repeat || "always",
|
|
63
|
+
name: f.replace(/\.md$/, ""),
|
|
64
|
+
})
|
|
65
|
+
} catch { /* skip malformed rule files silently */ }
|
|
66
|
+
}
|
|
67
|
+
return rules
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 装配合并:`.thincoder/rules/` 文件规则**置前**,config 规则按 `pattern` 去重(文件侧优先;
|
|
71
|
+
* 逐字镜像原 CLI `make-agent.mjs` 语义)。文件规则为空 ⇒ 归一数组原样返回(零拷贝零改)。
|
|
72
|
+
* `discover` 可注入(核装配 `DEFAULT_DEPS.discoverRules` 缝——U79 装配序可机验;VSC 端壳同取本件)。 */
|
|
73
|
+
export function mergeFileRules(configRules, cwd, discover = discoverRules) {
|
|
74
|
+
const rules = Array.isArray(configRules) ? configRules : []
|
|
75
|
+
const fileRules = discover(cwd)
|
|
76
|
+
if (fileRules.length === 0) return rules
|
|
77
|
+
const filePatterns = new Set(fileRules.map((r) => r.pattern))
|
|
78
|
+
return [...fileRules, ...rules.filter((r) => !filePatterns.has(r.pattern))]
|
|
79
|
+
}
|
package/rules.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* rules.mjs — 规则面**单源**(两面):
|
|
3
|
-
* ① stream 规则(`.thincoder/rules/*.md`——两端;`discoverRules` ∕ `mergeFileRules
|
|
3
|
+
* ① stream 规则(`.thincoder/rules/*.md`——两端;`discoverRules` ∕ `mergeFileRules`,
|
|
4
|
+
* 2026-12-01 起实证住叶档 `./rules-file.mjs`,本档再出口)
|
|
4
5
|
* ② 作用域规则(`.cursor/rules/*`——三端同面;`loadRules` 读取 ∕ 三分类 ∕ 尾块 ∕ JIT 注入全档单源)
|
|
5
6
|
*
|
|
6
7
|
* 面定义(权威)= `docs/core/design/WORKSPACE.md` §2.3「规则发现面(一线程一语义)」:
|
|
@@ -25,60 +26,21 @@
|
|
|
25
26
|
*/
|
|
26
27
|
import { existsSync, readFileSync, readdirSync } from "node:fs"
|
|
27
28
|
import { join } from "node:path"
|
|
28
|
-
import { parseFrontmatter } from "./markdown.mjs"
|
|
29
29
|
import { pushInject } from "./context-push.mjs"
|
|
30
30
|
// #327 触达路径单源谓词 + 写集(JIT 面 `PATH_TOOLS` 构造——B7 3a:与门禁 ∕ 记账同址单源)
|
|
31
31
|
import { FILE_MUTATORS, toolTouchPaths } from "./agent/helpers.mjs"
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
for (const f of entries) {
|
|
46
|
-
if (!f.endsWith(".md")) continue
|
|
47
|
-
try {
|
|
48
|
-
const text = readFileSync(join(rulesDir, f), "utf8")
|
|
49
|
-
const fm = text.match(/^---\r?\n([\s\S]*?)\r?\n---/)
|
|
50
|
-
if (!fm) continue
|
|
51
|
-
const meta = parseFrontmatter(fm[1])
|
|
52
|
-
const body = text.slice(fm[0].length).trim()
|
|
53
|
-
if (!meta.pattern) continue
|
|
54
|
-
// Strip surrounding quotes from frontmatter values (parseFrontmatter returns raw)
|
|
55
|
-
const pattern = meta.pattern.replace(/^"(.*)"$/s, "$1").replace(/^'(.*)'$/s, "$1")
|
|
56
|
-
const message = (meta.message || "").replace(/^"(.*)"$/s, "$1").replace(/^'(.*)'$/s, "$1")
|
|
57
|
-
|
|
58
|
-
rules.push({
|
|
59
|
-
pattern,
|
|
60
|
-
message: body || message || "",
|
|
61
|
-
action: meta.action || "warn",
|
|
62
|
-
repeat: meta.repeat || "always",
|
|
63
|
-
name: f.replace(/\.md$/, ""),
|
|
64
|
-
})
|
|
65
|
-
} catch { /* skip malformed rule files silently */ }
|
|
66
|
-
}
|
|
67
|
-
return rules
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// ─── A 面:stream 规则装配合并(`.thincoder/rules`——B7 3a 自核装配内联块抽取单源)────────
|
|
71
|
-
|
|
72
|
-
/** 装配合并:`.thincoder/rules/` 文件规则**置前**,config 规则按 `pattern` 去重(文件侧优先;
|
|
73
|
-
* 逐字镜像原 CLI `make-agent.mjs` 语义)。文件规则为空 ⇒ 归一数组原样返回(零拷贝零改)。
|
|
74
|
-
* `discover` 可注入(核装配 `DEFAULT_DEPS.discoverRules` 缝——U79 装配序可机验;VSC 端壳同取本件)。 */
|
|
75
|
-
export function mergeFileRules(configRules, cwd, discover = discoverRules) {
|
|
76
|
-
const rules = Array.isArray(configRules) ? configRules : []
|
|
77
|
-
const fileRules = discover(cwd)
|
|
78
|
-
if (fileRules.length === 0) return rules
|
|
79
|
-
const filePatterns = new Set(fileRules.map((r) => r.pattern))
|
|
80
|
-
return [...fileRules, ...rules.filter((r) => !filePatterns.has(r.pattern))]
|
|
81
|
-
}
|
|
33
|
+
// ─── A 面:stream 规则发现与合并(已抽出为叶档 `./rules-file.mjs`)──────────────────────
|
|
34
|
+
//
|
|
35
|
+
// 为何搬出(2026-12-01):`config.mjs` 的装载期归一要用 `mergeFileRules`(批 #109 把 stream 规则
|
|
36
|
+
// 合并从装配期挪到装载期——三端同源)。而本档 import `agent/helpers.mjs` 的 `FILE_MUTATORS`,
|
|
37
|
+
// `helpers` 又再出口 `agent/offload.mjs`,后者 `import { configDir } from "../config.mjs"` ⇒
|
|
38
|
+
// `config → rules → helpers → offload → config` 成环:本档顶层 `PATH_TOOLS` 在 `helpers` 尚未
|
|
39
|
+
// 初始化时读 `FILE_MUTATORS`,抛 `ReferenceError: Cannot access 'FILE_MUTATORS' before initialization`
|
|
40
|
+
// (单独 import `agent/helpers.mjs` 即复现;5 个集成用例连带红)。叶档只依赖
|
|
41
|
+
// `node:fs` ∥ `node:path` ∥ `./markdown.mjs`,`config.mjs` 直连它不成环。
|
|
42
|
+
// 本档再出口两件——`agent/assemble.mjs` 的导入面零改。
|
|
43
|
+
export { discoverRules, mergeFileRules } from "./rules-file.mjs"
|
|
82
44
|
|
|
83
45
|
// ─── B 面:作用域规则读取面(`.cursor/rules`——R10 上提;纯搬自 VSC 端壳)──
|
|
84
46
|
|