@thincoder/core 0.10.3 → 0.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +62 -0
- package/README.md +1 -1
- package/advisor/citations.mjs +29 -3
- package/advisor/compaction.mjs +31 -7
- package/advisor/history.mjs +8 -6
- package/advisor/loop.mjs +29 -27
- package/advisor/messages.mjs +2 -1
- package/advisor/run.mjs +9 -5
- package/advisor/timeline.mjs +26 -0
- package/advisor.mjs +4 -2
- package/agent/assemble.mjs +1 -1
- package/agent/chat-call.mjs +1 -1
- package/agent/child-marks.mjs +2 -2
- package/agent/completion.mjs +3 -1
- package/agent/digest-account.mjs +189 -0
- package/agent/dispatch-gates.mjs +8 -0
- package/agent/dispatch.mjs +39 -18
- package/agent/family-tools.mjs +27 -16
- package/agent/helpers.mjs +12 -3
- package/agent/light-round.mjs +66 -0
- package/agent/post-turn.mjs +8 -4
- package/agent/record-results.mjs +4 -0
- package/agent/run-stages.mjs +32 -7
- package/agent/run-start.mjs +50 -3
- package/agent/setup-reminders.mjs +1 -1
- package/agent/setup.mjs +18 -3
- package/agent/subagent-event.mjs +1 -1
- package/agent/suspension.mjs +37 -12
- package/agent/timers.mjs +56 -5
- package/agent/turn-loop.mjs +30 -5
- package/agent/write-gate.mjs +20 -32
- package/agent-tools/advisor-async.mjs +15 -7
- package/agent-tools/advisor-settle.mjs +2 -2
- package/agent-tools/advisor.mjs +34 -33
- package/agent-tools/async-discard.mjs +34 -0
- package/agent-tools/async-settle.mjs +32 -7
- package/agent-tools/audit-block.mjs +1 -1
- package/agent-tools/bash-async.mjs +1 -1
- package/agent-tools/batch-lifecycle.mjs +59 -17
- package/agent-tools/batch-paths.mjs +24 -4
- package/agent-tools/batch-skeleton.mjs +59 -43
- package/agent-tools/batch.mjs +39 -18
- package/agent-tools/browser-async.mjs +198 -0
- package/agent-tools/checkpoint.mjs +1 -1
- package/agent-tools/design-slots.mjs +232 -0
- package/agent-tools/design-token.mjs +20 -0
- package/agent-tools/digest-budget.mjs +1 -1
- package/agent-tools/escalate-async.mjs +4 -2
- package/agent-tools/manifest.mjs +193 -0
- package/agent-tools/parent-channel.mjs +7 -4
- package/agent-tools/review-facts.mjs +143 -16
- package/agent-tools/settings.mjs +1 -1
- package/agent-tools/skill.mjs +1 -1
- package/agent-tools/subagent-actions-query.mjs +13 -6
- package/agent-tools/subagent-async.mjs +31 -15
- package/agent-tools/subagent-panel.mjs +2 -1
- package/agent-tools/subagent-scheduler.mjs +8 -5
- package/agent-tools/subagent-spawn.mjs +30 -56
- package/agent-tools/subagent.mjs +21 -8
- package/agent-tools/timer.mjs +186 -12
- package/agent-tools/zero-write-watch.mjs +77 -0
- package/agent-tools.mjs +2 -1
- package/agent.mjs +2 -2
- package/attachments.mjs +1 -1
- package/config-io.mjs +18 -13
- package/config-migrate.mjs +13 -29
- package/config-presets.mjs +33 -29
- package/config.mjs +68 -25
- package/context-degrade.mjs +1 -1
- package/context-echo.mjs +1 -1
- package/context-push.mjs +2 -2
- package/context.mjs +1 -1
- package/conventions.mjs +28 -8
- package/declaration.mjs +18 -2
- package/escape.mjs +1 -1
- package/file-links.mjs +1 -1
- package/file-refs.mjs +1 -1
- package/history-window.mjs +1 -1
- package/i18n.mjs +7 -0
- package/ledger-cmd.mjs +62 -16
- package/ledger-db.mjs +6 -0
- package/ledger-surface.mjs +49 -5
- package/ledger-tools.mjs +158 -87
- package/ledger-variant-notice.mjs +47 -0
- package/ledger.mjs +11 -18
- package/log.mjs +1 -1
- package/manifest-discovery.mjs +1 -1
- package/manifest-schema.mjs +7 -5
- package/manifest.mjs +5 -3
- package/mcp/transport-stdio.mjs +1 -1
- package/mcp.mjs +1 -1
- package/memory/code-index.mjs +1 -1
- package/memory/code-search.mjs +1 -1
- package/memory/code-sync.mjs +1 -1
- package/memory/docs.mjs +6 -2
- package/memory/file-list.mjs +1 -1
- package/memory/file-walk.mjs +17 -5
- package/memory/maintain.mjs +410 -0
- package/memory/memory-tool.mjs +21 -6
- package/memory/schema.mjs +19 -7
- package/memory/sweep.mjs +8 -5
- package/memory/sync-tail.mjs +16 -10
- package/model-ref.mjs +16 -13
- package/model-specs.mjs +21 -9
- package/package.json +1 -1
- package/peer-instances.mjs +1 -1
- package/permission.mjs +33 -0
- package/process-probe.mjs +2 -2
- package/prompts/advisor-design.md +4 -2
- package/prompts/advisor-round1.md +1 -1
- package/prompts/advisor-round2.md +1 -1
- package/prompts/advisor-round3.md +1 -1
- package/prompts/common.md +38 -4
- package/prompts/consult-base.md +1 -1
- package/prompts/discipline-engineering.md +32 -15
- package/prompts/discipline-normal.md +46 -2
- package/prompts/persona-eng-designer.md +6 -6
- package/prompts/persona-engineering.md +18 -9
- package/prompts/persona-normal.md +2 -0
- package/prompts/subagent-base.md +3 -0
- package/provider/anthropic.mjs +14 -2
- package/provider/core.mjs +6 -0
- package/provider/errors.mjs +28 -3
- package/provider/google.mjs +22 -10
- package/provider/list-models.mjs +3 -2
- package/provider/responses-request.mjs +3 -1
- package/provider/responses.mjs +38 -4
- package/provider/sse.mjs +3 -0
- package/provider-flows.mjs +14 -15
- package/proxy-chunked.mjs +102 -0
- package/proxy-target.mjs +54 -0
- package/proxy-transport.mjs +298 -0
- package/proxy.mjs +17 -248
- package/session-gc.mjs +2 -2
- package/session-lifecycle.mjs +18 -14
- package/session-slot-claims.mjs +2 -2
- package/session-slots-manifest.mjs +1 -1
- package/session-slots.mjs +3 -3
- package/shell-identity.mjs +107 -0
- package/team-ledger.mjs +282 -0
- package/team.mjs +223 -0
- package/tool-docs/advisor.md +1 -1
- package/tool-docs/bash.md +2 -1
- package/tool-docs/batch.md +1 -1
- package/tool-docs/browser.md +48 -0
- package/tool-docs/delete.md +7 -5
- package/tool-docs/ledger.md +6 -0
- package/tool-docs/manifest.md +16 -0
- package/tool-docs/memory.md +1 -0
- package/tool-docs/notify_parent.md +5 -0
- package/tool-docs/process.md +4 -4
- package/tool-docs/question.md +1 -0
- package/tool-docs/subagent.md +14 -3
- package/tool-docs/team_ledger.md +9 -0
- package/tool-docs/timer.md +6 -0
- package/tool-docs/wait_for.md +1 -0
- package/tools/bash.mjs +9 -4
- package/tools/browser.mjs +161 -0
- package/tools/git.mjs +1 -1
- package/tools/index.mjs +4 -4
- package/tools/ops.mjs +26 -10
- package/tools/patch.mjs +8 -2
- package/tools/repomap.mjs +1 -1
- package/tools/write-path.mjs +8 -6
- package/traces/trace-cleanup.mjs +1 -1
- package/traces/trace-store.mjs +1 -1
- package/vision-reader.mjs +10 -16
- package/tool-docs/ledger_add.md +0 -1
- package/tool-docs/ledger_close.md +0 -1
- package/tool-docs/ledger_count.md +0 -1
- package/tool-docs/ledger_query.md +0 -1
- package/tool-docs/ledger_update.md +0 -1
package/provider-flows.mjs
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* M9 语义定死:**准入永不阻断写** —— 探针只出读数 ∕ 失败消息(消息本体逐字长句),绝不抛出 ∕
|
|
22
22
|
* 绝不回滚已完成的保存;失败不缓存(下次配置动作重探)。
|
|
23
23
|
*
|
|
24
|
-
* 消费面:桌面 `thincoder-desktop/src/main/providers.mjs
|
|
24
|
+
* 消费面:桌面 `thincoder-desktop/src/main/providers.mjs`(四通道壳——判据:`FORMATS` ∕
|
|
25
25
|
* `customFieldsError` ∕ `probeAdmission`;端侧 reason 词法不动);三流程本体 = 桌面 ∕ VSC(已随本批迁移改指)消费,CLI 待迁。
|
|
26
26
|
*/
|
|
27
27
|
import { PROVIDER_PRESETS } from "./config-presets.mjs"
|
|
@@ -54,17 +54,16 @@ export function providerNameError(name, existing = new Set()) {
|
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
/**
|
|
57
|
-
* 自定形必填字段校验(VSC `addProviderFlow` 自定径输入步步序 = baseURL →
|
|
58
|
-
* name 步单列见 `providerNameError
|
|
59
|
-
*
|
|
57
|
+
* 自定形必填字段校验(VSC `addProviderFlow` 自定径输入步步序 = baseURL → format;
|
|
58
|
+
* name 步单列见 `providerNameError`。2026-10-09 清除批:model 步退场——渠道不携模型)。
|
|
59
|
+
* 两拒因串 = 核持久化面**同条件串**逐字(`config-io.mjs`
|
|
60
|
+
* `addProviderEntry`)——VSC 该两步为静默中止位(无消息可搬)⇒ 取同条件核串,保「同条件同词」。
|
|
60
61
|
* `format` 缺省 = `"openai"`(沿端侧形判同式)。
|
|
61
62
|
* @returns {string|null} 首个失败字段的拒因串;全过 ⇒ `null`
|
|
62
63
|
*/
|
|
63
64
|
export function customFieldsError(fields) {
|
|
64
65
|
const baseURL = String(fields?.baseURL ?? "").trim()
|
|
65
66
|
if (!baseURL) return "Base URL is required"
|
|
66
|
-
const model = String(fields?.model ?? "").trim()
|
|
67
|
-
if (!model) return "Model is required"
|
|
68
67
|
const format = fields?.format ?? "openai"
|
|
69
68
|
if (!FORMATS.includes(format)) return `Unknown API format: ${format} (expected ${FORMATS.join("/")})`
|
|
70
69
|
return null
|
|
@@ -73,19 +72,21 @@ export function customFieldsError(fields) {
|
|
|
73
72
|
/**
|
|
74
73
|
* M9 探针目标构造(上提源 = VSC `provider-flows.mjs:38` 的实参面 `presets.mjs` `probeTargetFromEntry`——
|
|
75
74
|
* 逐条随迁):渠道条目 ⇒ `listModels` 可消费的探针目标。代理链与 chat 请求同规则(per-provider `proxy: true`
|
|
76
|
-
* ∧
|
|
77
|
-
* 渠道标「不可用」——准入判据 M8
|
|
75
|
+
* ∧ `proxy.uri` 在案 ⇒ 探针也走该代理;无全局闸——2026-10-08 批落);apiKey 归一(trim;缺 ⇒ 空串——探针会
|
|
76
|
+
* 如实失败 ⇒ 渠道标「不可用」——准入判据 M8)。`headers` 字段面(#1048①):仅 plain-object 才携;缺 ∥ 非法 ⇒
|
|
77
|
+
* 零键(同 apiKey 归一律)——来源面 = 盘上条目 ∥ 表单;消费点 = `list-models` 各 format 分支请求头展开。
|
|
78
78
|
*/
|
|
79
79
|
export function probeTargetOf(entry) {
|
|
80
80
|
const raw = loadRaw()
|
|
81
81
|
const proxyCfg = normalizeProxy(raw.proxy)
|
|
82
|
-
const proxyUri = entry?.proxy === true && proxyCfg?.uri
|
|
82
|
+
const proxyUri = entry?.proxy === true && proxyCfg?.uri ? proxyCfg.uri : undefined
|
|
83
83
|
return {
|
|
84
84
|
name: entry?.name,
|
|
85
85
|
baseURL: entry?.baseURL,
|
|
86
86
|
apiKey: typeof entry?.apiKey === "string" ? entry.apiKey.trim() : "",
|
|
87
87
|
format: entry?.format,
|
|
88
88
|
proxyUri,
|
|
89
|
+
...(entry?.headers && typeof entry.headers === "object" && !Array.isArray(entry.headers) ? { headers: entry.headers } : {}),
|
|
89
90
|
}
|
|
90
91
|
}
|
|
91
92
|
|
|
@@ -146,8 +147,8 @@ export async function addProviderFlow(ui, refresh, deps = {}) {
|
|
|
146
147
|
|
|
147
148
|
const items = Object.entries(PROVIDER_PRESETS)
|
|
148
149
|
.filter(([name]) => !existing.has(name))
|
|
149
|
-
.map(([name, p]) => ({ label: name, description: p.desc, detail: p.
|
|
150
|
-
items.push({ label: "Custom (manual config)", description: "enter baseURL/
|
|
150
|
+
.map(([name, p]) => ({ label: name, description: p.desc, detail: p.baseURL ?? "", kind: "preset", name }))
|
|
151
|
+
items.push({ label: "Custom (manual config)", description: "enter baseURL/format", kind: "custom" })
|
|
151
152
|
|
|
152
153
|
const sel = await host.pick(items, {
|
|
153
154
|
placeHolder: "Add provider — select a preset",
|
|
@@ -166,14 +167,12 @@ export async function addProviderFlow(ui, refresh, deps = {}) {
|
|
|
166
167
|
placeHolder: "https://api.example.com/v1",
|
|
167
168
|
}))?.trim()
|
|
168
169
|
if (!baseURL) return
|
|
169
|
-
const model = (await host.input({ prompt: `Model name for ${name}` }))?.trim()
|
|
170
|
-
if (!model) return
|
|
171
170
|
const format = await host.pick(
|
|
172
171
|
FORMATS.map((f) => ({ label: f, description: f === "openai" ? "(default)" : f === "anthropic" ? "Messages API" : "streamGenerateContent" })),
|
|
173
172
|
{ placeHolder: "API format" },
|
|
174
173
|
)
|
|
175
174
|
if (!format) return
|
|
176
|
-
const err = addProviderEntry({ custom: { name, baseURL,
|
|
175
|
+
const err = addProviderEntry({ custom: { name, baseURL, format: format.label } })
|
|
177
176
|
if (err) { host.error(err); return }
|
|
178
177
|
const key = await host.input({ prompt: `API key for ${name} (leave empty to skip)`, password: true })
|
|
179
178
|
if (key?.trim()) {
|
|
@@ -213,7 +212,7 @@ export async function removeProviderFlow(ui, refresh) {
|
|
|
213
212
|
return
|
|
214
213
|
}
|
|
215
214
|
const sel = await host.pick(
|
|
216
|
-
candidates.map((p) => ({ label: p.name, description: p.
|
|
215
|
+
candidates.map((p) => ({ label: p.name, description: p.baseURL ?? "" })),
|
|
217
216
|
{ placeHolder: "Remove provider" },
|
|
218
217
|
)
|
|
219
218
|
if (!sel) return
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* proxy-chunked.mjs — HTTP/1.1 分块传输(`Transfer-Encoding: chunked`)流式剥帧器(#1065)。
|
|
3
|
+
*
|
|
4
|
+
* 单出 `createChunkedDecoder`(设计 = `docs/core/design/PROXY.md` §2 ∥ §7 D-PX11):
|
|
5
|
+
* - **流式保形**:边收边吐、只保有帧头(块长行上限 1KiB);块数据到达即吐 `min(可用, 待吐)`;
|
|
6
|
+
* - 块长 = 十六进制(行长 ≤1KiB、数值须安全整数——越界判畸形)+ 可选 `;扩展`(扩展忽略);块尾须恰为 CRLF;`0` 块 ⇒ `onEnd`
|
|
7
|
+
* (其后 trailer ∥ 余字节读取即弃——`Connection: close` 语义下无复用面);
|
|
8
|
+
* - **畸形帧回退 = 透传**:已持有字节原样吐出 + 其后全部字节直通——不报错(不把协议违规
|
|
9
|
+
* 升级成连接失败)、不截断(零静默丢数据);
|
|
10
|
+
* - 纯状态机、无自有 `'error'` 面(#16 契约零变——body 终止守卫族照旧对 body 单点直作)。
|
|
11
|
+
* 零依赖:Node built-ins only。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** 块长行上限(超限判畸形——防无界持有帧头)。 */
|
|
15
|
+
const MAX_SIZE_LINE = 1024
|
|
16
|
+
const CRLF = Buffer.from("\r\n")
|
|
17
|
+
const EMPTY = Buffer.alloc(0)
|
|
18
|
+
|
|
19
|
+
/** 十六进制字节判定(0-9 ∥ a-f ∥ A-F——大小写不敏感)。 */
|
|
20
|
+
const isHexByte = (b) => (b >= 0x30 && b <= 0x39) || (b >= 0x61 && b <= 0x66) || (b >= 0x41 && b <= 0x46)
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 建流式分块解码器(消费单点 = `proxy-transport.mjs` `streamHttpResponse` chunked 径)。
|
|
24
|
+
* @param {{ onData?: (chunk: Buffer) => void, onEnd?: () => void }} [handlers]
|
|
25
|
+
* `onData` 逐段收解码后的块数据(任意分包边界);`onEnd` 于 `0` 块到达时触发一次。
|
|
26
|
+
* @returns {{ push: (buf: Buffer) => void, mode: "chunked" | "raw" | "done" }}
|
|
27
|
+
* `push` 喂入原始字节;`mode` = `chunked`(解码中)∥ `raw`(畸形回退透传)∥
|
|
28
|
+
* `done`(`0` 块已终,其后字节读取即弃)——供测试与诊断。
|
|
29
|
+
*/
|
|
30
|
+
export function createChunkedDecoder({ onData, onEnd } = {}) {
|
|
31
|
+
let state = "size" // size → data → crlf → size …
|
|
32
|
+
let mode = "chunked"
|
|
33
|
+
let buf = EMPTY // 未消费字节(只保有帧头——块数据即到即吐)
|
|
34
|
+
let need = 0 // data 阶段待吐字节数
|
|
35
|
+
|
|
36
|
+
const emit = (chunk) => { if (chunk.length > 0) onData?.(chunk) }
|
|
37
|
+
/** 畸形回退:已持有字节原样吐出,此后全量直通(不再解析)。 */
|
|
38
|
+
const fallback = () => {
|
|
39
|
+
mode = "raw"
|
|
40
|
+
const held = buf
|
|
41
|
+
buf = EMPTY
|
|
42
|
+
emit(held)
|
|
43
|
+
}
|
|
44
|
+
/** `0` 块终:body 随 0 块结束。 */
|
|
45
|
+
const finish = () => { mode = "done"; buf = EMPTY; onEnd?.() }
|
|
46
|
+
|
|
47
|
+
/** 帧推进:逐状态消费 buf;块数据即吐(只保有帧头)。 */
|
|
48
|
+
function step() {
|
|
49
|
+
for (;;) {
|
|
50
|
+
if (state === "size") {
|
|
51
|
+
const idx = buf.indexOf(CRLF)
|
|
52
|
+
if (idx < 0) {
|
|
53
|
+
// 未成行:首字节非十六进制 ∥ 超限 ⇒ 畸形;否则等下一包
|
|
54
|
+
if (buf.length > 0 && !isHexByte(buf[0])) return fallback()
|
|
55
|
+
if (buf.length > MAX_SIZE_LINE) return fallback()
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
const line = buf.subarray(0, idx)
|
|
59
|
+
const semi = line.indexOf(0x3b) // ";"——块扩展起点(忽略)
|
|
60
|
+
const hex = semi < 0 ? line : line.subarray(0, semi)
|
|
61
|
+
// 畸形行(超限 ∥ 空 ∥ 非十六进制)⇒ 整段原样吐出(行 ∥ CRLF 零丢弃——不截断);行有效才消费
|
|
62
|
+
if (idx > MAX_SIZE_LINE || hex.length === 0) return fallback()
|
|
63
|
+
for (const b of hex) if (!isHexByte(b)) return fallback()
|
|
64
|
+
const size = Number.parseInt(hex.toString("latin1"), 16)
|
|
65
|
+
if (!Number.isSafeInteger(size)) return fallback() // 数值越界(>2^53——double 溢出可为 Infinity)⇒ 归畸形
|
|
66
|
+
buf = buf.subarray(idx + 2)
|
|
67
|
+
if (size === 0) return finish()
|
|
68
|
+
need = size
|
|
69
|
+
state = "data"
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
if (state === "data") {
|
|
73
|
+
if (buf.length === 0) return
|
|
74
|
+
const take = Math.min(buf.length, need)
|
|
75
|
+
emit(buf.subarray(0, take))
|
|
76
|
+
buf = buf.subarray(take)
|
|
77
|
+
need -= take
|
|
78
|
+
if (need > 0) return
|
|
79
|
+
state = "crlf"
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
// state === "crlf":块尾须恰为 CRLF
|
|
83
|
+
if (buf.length < 2) {
|
|
84
|
+
if (buf.length === 1 && buf[0] !== 0x0d) return fallback()
|
|
85
|
+
return
|
|
86
|
+
}
|
|
87
|
+
if (buf[0] !== 0x0d || buf[1] !== 0x0a) return fallback()
|
|
88
|
+
buf = buf.subarray(2)
|
|
89
|
+
state = "size"
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
push(d) {
|
|
95
|
+
if (mode === "done") return // 0 块后余字节(trailer 等)读取即弃
|
|
96
|
+
if (mode === "raw") { emit(d); return }
|
|
97
|
+
buf = buf.length > 0 ? Buffer.concat([buf, d]) : d
|
|
98
|
+
step()
|
|
99
|
+
},
|
|
100
|
+
get mode() { return mode },
|
|
101
|
+
}
|
|
102
|
+
}
|
package/proxy-target.mjs
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* proxy-target.mjs — 代理目标 ∥ 配置解析面(2026-10-08 拆档——原 `proxy.mjs` 迁出;#1037)。
|
|
3
|
+
* 逐渠判定 = 渠道旗 `providers[].proxy` ∧ `proxy.uri` 在案(无全局闸——D-PX1,2026-10-08 批落)。
|
|
4
|
+
* 零依赖:Node built-ins only(net, url)。
|
|
5
|
+
*/
|
|
6
|
+
import { isIP } from "node:net"
|
|
7
|
+
import { URL } from "node:url"
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Resolve proxy URI.
|
|
11
|
+
* New format: { proxy: { uri: "http://host:port", web: true } }
|
|
12
|
+
* Old format: { proxy: "http://host:port" } — backwards compatible, web=true
|
|
13
|
+
* Env vars: HTTPS_PROXY, HTTP_PROXY, ALL_PROXY
|
|
14
|
+
*
|
|
15
|
+
* @returns {{ uri: string|null, web: boolean }}
|
|
16
|
+
*/
|
|
17
|
+
export function resolveProxyConfig(ctx) {
|
|
18
|
+
const cfgProxy = ctx?.agent?.config?.proxy
|
|
19
|
+
if (!cfgProxy) {
|
|
20
|
+
const uri = process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.ALL_PROXY || null
|
|
21
|
+
return { uri, web: !!uri }
|
|
22
|
+
}
|
|
23
|
+
if (typeof cfgProxy === "string") {
|
|
24
|
+
// Backward compat: bare string → web only
|
|
25
|
+
return { uri: cfgProxy, web: true }
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
uri: cfgProxy.uri || cfgProxy.url || null,
|
|
29
|
+
web: cfgProxy.web !== false,
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Convenience: resolve proxy URI for web tools (websearch/fetch) */
|
|
34
|
+
export function resolveWebProxy(ctx) {
|
|
35
|
+
const cfg = resolveProxyConfig(ctx)
|
|
36
|
+
return (cfg.uri && cfg.web) ? cfg.uri : null
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Loopback 目标判定(NO_PROXY 语义——#1026,2026-10-07 用户案):
|
|
41
|
+
* `localhost` ∥ `*.localhost`(RFC 6761)∥ `127.0.0.0/8` ∥ `::1` —— 此类目标永不经代理。
|
|
42
|
+
* 解析失败 ⇒ false(未知串不宣称 loopback);尾点(`localhost.`)先归一。
|
|
43
|
+
*/
|
|
44
|
+
export function isLoopbackTarget(urlStr) {
|
|
45
|
+
let host
|
|
46
|
+
try { host = new URL(urlStr).hostname } catch { return false }
|
|
47
|
+
if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1) // IPv6 带括号(URL.hostname 规范形)
|
|
48
|
+
if (host.endsWith(".")) host = host.slice(0, -1)
|
|
49
|
+
if (host === "localhost" || host.endsWith(".localhost")) return true
|
|
50
|
+
const v = isIP(host)
|
|
51
|
+
if (v === 4) return host.split(".")[0] === "127"
|
|
52
|
+
if (v === 6) return host === "::1"
|
|
53
|
+
return false
|
|
54
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* proxy-transport.mjs — 传输面(2026-10-08 拆档——原 `proxy.mjs` 迁出;#1037):
|
|
3
|
+
* CONNECT 隧道 ∥ 经典转发 ∥ 流式响应。`FETCH_TIMEOUT` = CONNECT/TLS 与经典转发建连超时(15s;
|
|
4
|
+
* 响应头阶段另有 `opts._headerTimeoutMs`)。
|
|
5
|
+
* 响应体 `Transfer-Encoding: chunked` ⇒ 解码器剥帧(`proxy-chunked.mjs`;#1065);单 token 已知
|
|
6
|
+
* `content-encoding`(gzip ∥ x-gzip ∥ deflate ∥ br)⇒ 剥帧后接解压器(#1067)。chunked 径背压:
|
|
7
|
+
* body 前最后一级可写流拒收 ⇒ 暂停上游源,排空 ⇒ 恢复(#1087)。
|
|
8
|
+
* 零依赖:Node built-ins only(net, tls, stream, url, zlib)。
|
|
9
|
+
*/
|
|
10
|
+
import { connect } from "node:net"
|
|
11
|
+
import { connect as tlsConnect } from "node:tls"
|
|
12
|
+
import { PassThrough } from "node:stream"
|
|
13
|
+
import { URL } from "node:url"
|
|
14
|
+
import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib"
|
|
15
|
+
import { abortError, timeoutError } from "./abort-provenance.mjs"
|
|
16
|
+
import { createChunkedDecoder } from "./proxy-chunked.mjs"
|
|
17
|
+
import { destroyBody } from "./stream-destroy.mjs"
|
|
18
|
+
|
|
19
|
+
export const FETCH_TIMEOUT = 15_000
|
|
20
|
+
|
|
21
|
+
/** 响应头终止序列(头阶段按字节累积——#1065 K5:chunked 首段须以字节交接)。 */
|
|
22
|
+
const HEADER_END = Buffer.from("\r\n\r\n")
|
|
23
|
+
|
|
24
|
+
/** content-encoding 解压器族(#1067——单 token 且已列 ⇒ 解压;identity ∥ 未知 ∥ 多 token 列表透传)。 */
|
|
25
|
+
const CE_DECODERS = { gzip: createGunzip, "x-gzip": createGunzip, deflate: createInflate, br: createBrotliDecompress }
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 在已建立的 socket 上发 HTTP 请求,响应头到齐即 resolve(流式)。
|
|
29
|
+
* 返回 Response-like: { ok, status, headers: Headers, body: PassThrough(异步迭代), text(): Promise<string> }
|
|
30
|
+
* body 边收边吐(SSE 流式消费方可逐 chunk 读取);text() 消费流到底(非流式调用方用)。
|
|
31
|
+
* 响应头 `Transfer-Encoding: chunked` ⇒ 体经 `proxy-chunked.mjs` 解码器剥帧后入 body(#1065;
|
|
32
|
+
* 流式保形、畸形帧回退透传、`0` 块 ⇒ body 结束);单 token 已知 `content-encoding` ⇒ 剥帧后接
|
|
33
|
+
* 解压器(#1067);chunked 径背压 ⇒ 暂停上游源 / 排空恢复(#1087);非 chunked 无 CE 径零动。
|
|
34
|
+
* opts.signal 全程有效:abort 即 destroy socket 并 reject/终止流。
|
|
35
|
+
* absoluteForm: 请求行发绝对 URI(http:// 目标的经典代理转发用),默认发 origin-form。
|
|
36
|
+
* 2026-08-31 会诊 #4:timeout 只覆盖"响应头阶段";settle 后 body 空闲 > bodyIdleMs 即
|
|
37
|
+
* 断流(原实现头部 timer 到齐即清,流式中途停摆会无限挂起直到用户 Ctrl+C)。
|
|
38
|
+
* bodyIdleMs 默认 120s(provider 长生成用 0 即禁用,由调用方决定)。
|
|
39
|
+
* 导出供测试(裸 socket,无需 TLS/CONNECT);生产路径走 tunnelHttps / proxyFetch。
|
|
40
|
+
*/
|
|
41
|
+
export function streamHttpResponse(sock, urlStr, opts = {}, timeout = FETCH_TIMEOUT, absoluteForm = false, bodyIdleMs = 120_000) {
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
const target = new URL(urlStr)
|
|
44
|
+
const method = opts.method ?? "GET"
|
|
45
|
+
const headers = opts.headers ?? {}
|
|
46
|
+
const signal = opts.signal
|
|
47
|
+
|
|
48
|
+
if (signal?.aborted) { sock.destroy(); return reject(abortError(signal, "provider", "proxy")) }
|
|
49
|
+
|
|
50
|
+
const body = new PassThrough()
|
|
51
|
+
let settled = false
|
|
52
|
+
let headerBuf = Buffer.alloc(0) // 头阶段按字节累积(#1065 K5——替代 utf8 往返)
|
|
53
|
+
let idleTimer = null
|
|
54
|
+
let sink = null // body 前解压器(单 token 已知 content-encoding 时建立——#1067;无则 null)
|
|
55
|
+
let sawInput = false // 解压器输入门(#1067):零输入(空体)+ CE 在场 ⇒ 不解压(零误报)
|
|
56
|
+
let pausedUpstream = false // 背压旗(#1087):sock.pause() 在场,幂等守卫
|
|
57
|
+
|
|
58
|
+
const timer = setTimeout(() => fail(timeoutError("Response timeout", "provider", "proxy-header")), timeout)
|
|
59
|
+
const onAbort = () => { sock.destroy(); fail(abortError(signal, "provider", "proxy")) }
|
|
60
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
61
|
+
|
|
62
|
+
function cleanup() {
|
|
63
|
+
clearTimeout(timer)
|
|
64
|
+
clearTimeout(idleTimer)
|
|
65
|
+
signal?.removeEventListener("abort", onAbort)
|
|
66
|
+
}
|
|
67
|
+
/** 头部阶段失败 reject;resolve 后失败则终止 body 流(for-await 抛出,不挂起) */
|
|
68
|
+
function fail(err) {
|
|
69
|
+
cleanup()
|
|
70
|
+
if (!settled) { settled = true; reject(err) }
|
|
71
|
+
else destroyBody(body, err)
|
|
72
|
+
}
|
|
73
|
+
/** 背压暂停上游源(#1087——幂等:排空前只暂停一次) */
|
|
74
|
+
function pauseUpstream() {
|
|
75
|
+
if (!pausedUpstream) { pausedUpstream = true; sock.pause() }
|
|
76
|
+
}
|
|
77
|
+
/** 排空恢复上游源(#1087——暂停态对偶分支,幂等) */
|
|
78
|
+
function resumeUpstream() {
|
|
79
|
+
if (pausedUpstream) { pausedUpstream = false; sock.resume() }
|
|
80
|
+
}
|
|
81
|
+
/** body 结束(幂等——`0` 块 ∥ 对端 close 两径都会到达;#1065):带 CE 且已收输入 ⇒ 先结解压器
|
|
82
|
+
* (flush 后经 pipe 结 body);零输入(空体 + CE 在场)⇒ 直结 body(sawInput 门——#1067,零误报)。 */
|
|
83
|
+
function endBody() {
|
|
84
|
+
if (sink && sawInput) {
|
|
85
|
+
if (!sink.destroyed && !sink.writableEnded) sink.end()
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
if (!body.destroyed && !body.writableEnded) body.end()
|
|
89
|
+
}
|
|
90
|
+
/** 推入 body 前最后一级可写流(带 CE = 解压器 ∥ 无 CE = body——#1087 暂停触发级);
|
|
91
|
+
* `write()` 返 false ⇒ 暂停上游源(排空后 'drain' 恢复);终止后不再写(watchdog ∥ abort ∥
|
|
92
|
+
* `0` 块后余包,与非 chunked 径 pipe 自摘语义齐)。 */
|
|
93
|
+
function pushDownstream(chunk) {
|
|
94
|
+
const target = sink ?? body
|
|
95
|
+
if (target.destroyed || target.writableEnded) return
|
|
96
|
+
if (sink) sawInput = true
|
|
97
|
+
if (target.write(chunk) === false) pauseUpstream()
|
|
98
|
+
}
|
|
99
|
+
/** body 阶段空闲看门狗:每次数据到达重置;无数据超时 → 断流(流式消费方抛错) */
|
|
100
|
+
function armIdle() {
|
|
101
|
+
clearTimeout(idleTimer)
|
|
102
|
+
if (bodyIdleMs > 0) idleTimer = setTimeout(() => destroyBody(body, timeoutError("Response body timeout (idle)", "provider", "proxy-body-idle")), bodyIdleMs)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
sock.on("data", (d) => {
|
|
106
|
+
if (settled) return // 理论上不会发生(settle 后摘掉本监听器),防御
|
|
107
|
+
headerBuf = headerBuf.length > 0 ? Buffer.concat([headerBuf, d]) : d
|
|
108
|
+
const idx = headerBuf.indexOf(HEADER_END)
|
|
109
|
+
if (idx < 0) return
|
|
110
|
+
|
|
111
|
+
const headerText = headerBuf.subarray(0, idx).toString("utf8")
|
|
112
|
+
const statusMatch = headerText.match(/^HTTP\/\d\.\d (\d+)/)
|
|
113
|
+
const status = statusMatch ? Number(statusMatch[1]) : 502
|
|
114
|
+
const respHeaders = {}
|
|
115
|
+
for (const line of headerText.split("\r\n").slice(1)) {
|
|
116
|
+
const ci = line.indexOf(":")
|
|
117
|
+
if (ci > 0) respHeaders[line.slice(0, ci).trim().toLowerCase()] = line.slice(ci + 1).trim()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// 头到齐:摘掉头阶段监听;剩余字节(字节副本)按 TE 分径交接
|
|
121
|
+
sock.removeAllListeners("data")
|
|
122
|
+
settled = true
|
|
123
|
+
cleanup()
|
|
124
|
+
armIdle()
|
|
125
|
+
const remaining = Buffer.from(headerBuf.subarray(idx + 4))
|
|
126
|
+
// 判定按 Transfer-Encoding 末段 token(大小写不敏感);头缺席而帧在场(协议违规)不解码
|
|
127
|
+
const chunked = (respHeaders["transfer-encoding"] ?? "").split(",").pop().trim().toLowerCase() === "chunked"
|
|
128
|
+
// 内容编码解压阶段(#1067——TE 剥帧后接,chunked ∥ 非 chunked 两径同点):单 token 且已列编码
|
|
129
|
+
// 建解压器;identity ∥ 头缺席 ∥ 未知编码 ∥ 多 token 列表 ⇒ 透传零动。请求头零改(不发
|
|
130
|
+
// Accept-Encoding——上游自发压缩才走本阶段)。
|
|
131
|
+
const ceTokens = (respHeaders["content-encoding"] ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
|
|
132
|
+
const ceFactory = ceTokens.length === 1 ? CE_DECODERS[ceTokens[0]] : undefined
|
|
133
|
+
if (ceFactory) {
|
|
134
|
+
sink = ceFactory()
|
|
135
|
+
// 解压失败 ⇒ body 以明错误终止(部分解码已发生——无「原字节」可回退);解压器 ⇒ body 走 pipe
|
|
136
|
+
// (自带背压:body 慢 ⇒ 解压器停 ⇒ 其可写侧涨满 ⇒ 推送分支暂停源)。
|
|
137
|
+
sink.on("error", (e) => fail(new Error(`Response body decompression failed (content-encoding: ${ceTokens[0]}): ${e.message}`)))
|
|
138
|
+
sink.pipe(body)
|
|
139
|
+
}
|
|
140
|
+
if (chunked) {
|
|
141
|
+
// chunked 径:解码器剥帧 ⇒ 逐段推入 body 前最后一级(带 CE = 解压器;函数式改写——body 本体零替换);
|
|
142
|
+
// 不再 pipe——body 由解码器 onData/onEnd 驱动
|
|
143
|
+
const decoder = createChunkedDecoder({ onData: pushDownstream, onEnd: endBody })
|
|
144
|
+
sock.on("data", (c) => decoder.push(c)) // 推送分支 = 背压暂停点(#1087:write() 返 false ⇒ sock.pause())
|
|
145
|
+
decoder.push(remaining)
|
|
146
|
+
} else if (sink) {
|
|
147
|
+
// 非 chunked 径 · 带 CE:源 ⇒ 解压器(推送分支同形——背压暂停点同判)
|
|
148
|
+
if (remaining.length > 0) pushDownstream(remaining)
|
|
149
|
+
sock.on("data", pushDownstream)
|
|
150
|
+
} else {
|
|
151
|
+
// 非 chunked 径 · 无 CE:原样直写 + pipe(现状语义,零动)
|
|
152
|
+
if (remaining.length > 0) body.write(remaining)
|
|
153
|
+
sock.pipe(body)
|
|
154
|
+
}
|
|
155
|
+
// 空闲看门狗随数据到达重置。注意必须用 'readable' 而非 'data':
|
|
156
|
+
// 'data' 监听把流切成 flowing 模式,会抢走 readSSE/for-await 未来得及认领的
|
|
157
|
+
// 已写缓冲(2026-08-31 实测:分包响应头的 remaining 首段被吞,readSSE 等不到 ack)。
|
|
158
|
+
// 'readable' 不改变流模式,数据仍由消费方按需拉取。
|
|
159
|
+
body.on("readable", armIdle)
|
|
160
|
+
// 背压排空 = 消费进度信号(#1087——防「暂停期无数据到达」把慢而健康的消费者误杀)。
|
|
161
|
+
body.on("drain", armIdle)
|
|
162
|
+
// 背压对偶分支:排空 ⇒ 恢复上游源。带 CE 时恢复信号在解压器(body 经 pipe 先恢复解压器——链传导);
|
|
163
|
+
// 无 CE 时 body 即最后一级 ⇒ 其 drain 即恢复点。
|
|
164
|
+
if (sink) sink.on("drain", resumeUpstream)
|
|
165
|
+
else body.on("drain", resumeUpstream)
|
|
166
|
+
// body 结束后才移除 abort 监听(流式中途 abort 要能终止流);空闲看门狗一并清
|
|
167
|
+
body.on("close", () => {
|
|
168
|
+
clearTimeout(idleTimer)
|
|
169
|
+
signal?.removeEventListener("abort", onAbort)
|
|
170
|
+
// 停止门(#1087 评审 F3):body 终止时上游仍在背压暂停态 ⇒ 先恢复再销毁源——
|
|
171
|
+
// 被暂停的 sock 不因 body 消亡自行关闭(悬挂口)。
|
|
172
|
+
if (pausedUpstream) { pausedUpstream = false; sock.resume(); sock.destroy() }
|
|
173
|
+
})
|
|
174
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
175
|
+
|
|
176
|
+
resolve({
|
|
177
|
+
ok: status >= 200 && status < 400,
|
|
178
|
+
status,
|
|
179
|
+
headers: new Headers(respHeaders),
|
|
180
|
+
body,
|
|
181
|
+
text: async () => {
|
|
182
|
+
const chunks = []
|
|
183
|
+
for await (const c of body) chunks.push(c)
|
|
184
|
+
return Buffer.concat(chunks).toString("utf8")
|
|
185
|
+
},
|
|
186
|
+
})
|
|
187
|
+
})
|
|
188
|
+
sock.on("close", () => {
|
|
189
|
+
if (!settled) fail(new Error("Connection closed before response"))
|
|
190
|
+
else endBody()
|
|
191
|
+
})
|
|
192
|
+
// 头部阶段的传输错误统一包装为稳定契约(对端 RST 会抛原生 ECONNRESET,调用方难判别);
|
|
193
|
+
// resolve 后的 body 阶段保留原始错误终止流
|
|
194
|
+
sock.on("error", (e) => {
|
|
195
|
+
if (!settled) fail(new Error(`Connection closed before response (${e.code ?? e.message})`))
|
|
196
|
+
else fail(e)
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
// 写请求(absoluteForm:代理转发时请求行为绝对 URI)
|
|
200
|
+
const requestTarget = absoluteForm ? urlStr : `${target.pathname}${target.search}`
|
|
201
|
+
const lines = [`${method} ${requestTarget} HTTP/1.1`]
|
|
202
|
+
for (const [k, v] of Object.entries({ ...headers, Host: target.hostname })) lines.push(`${k}: ${v}`)
|
|
203
|
+
lines.push("Connection: close", "", "")
|
|
204
|
+
sock.write(lines.join("\r\n"))
|
|
205
|
+
if (opts.body) sock.write(opts.body)
|
|
206
|
+
})
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* HTTPS request through HTTP CONNECT proxy tunnel.
|
|
211
|
+
* CONNECT + TLS 建立后交给 streamHttpResponse — 响应头到齐即 resolve,body 为流式。
|
|
212
|
+
* 2026-08-31 会诊 #1/#4:
|
|
213
|
+
* - TLS 默认全量证书校验(rejectUnauthorized: true)——走代理的流量(含 API key)
|
|
214
|
+
* 不得在未验证链路上传输;确需自签/内网代理时 opts.insecureTls=true 显式放行。
|
|
215
|
+
* - CONNECT/TLS 阶段用 timeout(默认 15s,建隧道快);**响应头超时**用
|
|
216
|
+
* opts._headerTimeoutMs(默认 60s)——原实现共用 15s,DeepSeek 排队 TTFB>15s
|
|
217
|
+
* 即误报 "Response timeout",与直连 600s 语义割裂。
|
|
218
|
+
*/
|
|
219
|
+
export function tunnelHttps(urlStr, opts, proxyUri, timeout = FETCH_TIMEOUT) {
|
|
220
|
+
return new Promise((resolve, reject) => {
|
|
221
|
+
let target, proxy
|
|
222
|
+
try {
|
|
223
|
+
target = new URL(urlStr)
|
|
224
|
+
proxy = new URL(proxyUri)
|
|
225
|
+
} catch {
|
|
226
|
+
// 融合(§2.5 #74——取双侧并集):VSC 侧的**坏代理串友好报错**并入核内——
|
|
227
|
+
// 原生 `Invalid URL` 不解释期望形态,调用方拿到的可观测文案退化。
|
|
228
|
+
return reject(new Error(`Invalid proxy URI: "${proxyUri}" — expected http://host:port`))
|
|
229
|
+
}
|
|
230
|
+
const signal = opts?.signal
|
|
231
|
+
const headerTimeoutMs = Number.isFinite(opts?._headerTimeoutMs) ? opts._headerTimeoutMs : 60_000
|
|
232
|
+
const bodyIdleMs = opts?._bodyIdleMs ?? 120_000
|
|
233
|
+
|
|
234
|
+
if (signal?.aborted) return reject(abortError(signal, "provider", "proxy"))
|
|
235
|
+
|
|
236
|
+
const sock = connect({ host: proxy.hostname, port: Number(proxy.port) || 3128 })
|
|
237
|
+
const timer = setTimeout(() => { sock.destroy(); reject(new Error("Proxy CONNECT timeout")) }, timeout)
|
|
238
|
+
const onAbort = () => { sock.destroy(); reject(abortError(signal, "provider", "proxy")) }
|
|
239
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
240
|
+
sock.on("connect", () => sock.write(`CONNECT ${target.hostname}:${target.port || 443} HTTP/1.1\r\nHost: ${target.hostname}\r\n\r\n`))
|
|
241
|
+
|
|
242
|
+
let buf = ""
|
|
243
|
+
sock.on("data", d => {
|
|
244
|
+
buf += d.toString()
|
|
245
|
+
const end = buf.indexOf("\r\n\r\n")
|
|
246
|
+
if (end < 0) return
|
|
247
|
+
const statusLine = buf.slice(0, end).split("\r\n")[0]
|
|
248
|
+
buf = buf.slice(end + 4)
|
|
249
|
+
if (!statusLine.includes("200")) { sock.destroy(); clearTimeout(timer); return reject(new Error(`Proxy CONNECT: ${statusLine}`)) }
|
|
250
|
+
sock.removeAllListeners("data"); clearTimeout(timer)
|
|
251
|
+
|
|
252
|
+
// 安全默认:TLS 全量校验。企业中间人代理场景显式 opts.insecureTls=true 才放行。
|
|
253
|
+
const tlsSock = tlsConnect({ socket: sock, servername: target.hostname, rejectUnauthorized: opts?.insecureTls !== true })
|
|
254
|
+
if (buf) tlsSock.unshift(Buffer.from(buf))
|
|
255
|
+
tlsSock.on("secureConnect", () => {
|
|
256
|
+
// TLS 之后的请求/响应阶段:abort 交由 streamHttpResponse 接管
|
|
257
|
+
signal?.removeEventListener("abort", onAbort)
|
|
258
|
+
streamHttpResponse(tlsSock, urlStr, opts, headerTimeoutMs, false, bodyIdleMs).then(resolve, reject)
|
|
259
|
+
})
|
|
260
|
+
tlsSock.on("error", e => { sock.destroy(); reject(e) })
|
|
261
|
+
})
|
|
262
|
+
sock.on("error", e => { clearTimeout(timer); reject(new Error(`Proxy CONNECT failed (${e.code ?? e.message})`)) })
|
|
263
|
+
// 代理干净 FIN 关闭(无 error)时也要 reject,不能卡满超时
|
|
264
|
+
sock.on("close", () => { clearTimeout(timer); reject(new Error("Proxy connection closed before tunnel established")) })
|
|
265
|
+
})
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** TCP 直连代理(http:// 目标的经典转发用):超时/abort/对端关闭都有稳定 reject */
|
|
269
|
+
export function tcpConnectProxy(proxyUri, signal, timeout) {
|
|
270
|
+
return new Promise((resolve, reject) => {
|
|
271
|
+
let proxy
|
|
272
|
+
try {
|
|
273
|
+
proxy = new URL(proxyUri)
|
|
274
|
+
} catch {
|
|
275
|
+
// 融合(§2.5 #74):同 tunnelHttps——坏代理串友好报错。
|
|
276
|
+
return reject(new Error(`Invalid proxy URI: "${proxyUri}" — expected http://host:port`))
|
|
277
|
+
}
|
|
278
|
+
const sock = connect({ host: proxy.hostname, port: Number(proxy.port) || 3128 })
|
|
279
|
+
if (signal?.aborted) { sock.destroy(); return reject(abortError(signal, "provider", "proxy")) }
|
|
280
|
+
const onAbort = () => sock.destroy()
|
|
281
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
282
|
+
const timer = setTimeout(() => { sock.destroy(); reject(new Error("Proxy CONNECT timeout")) }, timeout)
|
|
283
|
+
const onError = (e) => { clearTimeout(timer); reject(new Error(`Proxy CONNECT failed (${e.code ?? e.message})`)) }
|
|
284
|
+
const onClose = () => {
|
|
285
|
+
clearTimeout(timer)
|
|
286
|
+
reject(signal?.aborted ? abortError(signal, "provider", "proxy") : new Error("Proxy connection closed before tunnel established"))
|
|
287
|
+
}
|
|
288
|
+
sock.once("connect", () => {
|
|
289
|
+
clearTimeout(timer)
|
|
290
|
+
signal?.removeEventListener("abort", onAbort)
|
|
291
|
+
sock.removeListener("error", onError)
|
|
292
|
+
sock.removeListener("close", onClose)
|
|
293
|
+
resolve(sock)
|
|
294
|
+
})
|
|
295
|
+
sock.once("error", onError)
|
|
296
|
+
sock.once("close", onClose)
|
|
297
|
+
})
|
|
298
|
+
}
|