feat(net): route every outbound request through the configured proxy

Node's built-in fetch ignores HTTP_PROXY, so every harness request connected
directly regardless of what the user exported. Resolve one policy from the
launch environment and install it as undici's global dispatcher, then wire the
four surfaces a global dispatcher cannot reach: web_fetch's pinned transport,
the OTLP exporter's node:http agent, the E2B SDK's own proxy option, and the
environment a child process or worker thread is given.

Each outbound call site carries an egress test that drives its real code path
through a fake proxy; that measurement is what found the OTLP and E2B gaps.
This commit is contained in:
Yichen Jiang committed 2026-08-29 13:17:11 +08:00
1 parent 1dd5476232
commit 545e2ad914
83 files changed
+3050 -133

No files matched your search

@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.md
2026-08-27-outbound-proxy-policy.md: 9d0a1545e68652f2f2453e89fbf6321385b6c804
2026-08-27-outbound-proxy-policy.zh.md: fe4f596c6839b7b1c275abf042b90d08b42643c1
@@ -0,0 +1,83 @@
# Agent Note: One outbound proxy policy, installed before anything can request
Status: implemented
English | [中文](2026-08-27-outbound-proxy-policy.zh.md)
## Problem
Node's built-in `fetch` ignores `HTTP_PROXY` and `HTTPS_PROXY`. Every other tool a developer runs — curl, git, npm, pip — honours them, so a user behind a proxy exports the variables once and expects everything to follow. The harness did not: `setGlobalDispatcher`, `ProxyAgent`, and `EnvHttpProxyAgent` appeared zero times across `packages/` and `apps/`, so the model request, every web search, `web_fetch`, MCP over HTTP, the OTLP exporter, and the E2B SDK all connected directly, silently, with no diagnostic anywhere.
The repository had briefly had an answer and lost it without noticing. PR #971 set `NODE_USE_ENV_PROXY=1` in `bin/dsh`; eleven days later `bbb1b1cc38 cleanup: remove managed source installer` deleted that launcher wholesale, taking the flag with it. What survived was one sentence in `apps/cli/reference/README.md` telling the reader to set a variable that nothing consumed any more.
That sentence could not have worked anyway, for three measured reasons. `NODE_USE_ENV_PROXY` samples the environment at process start, while `loadLayeredEnv()` merges the `.env` layers afterwards, so a proxy declared in a project or `$DSH_HOME` `.env` is invisible to it. It reaches Node 24.0+ and, on the 22 line, only 22.21+ — while `engines` admits `^22.19.0`, where the variable does not exist and setting it warns about nothing. And it does not reach `web-fetch-http` at all: that provider passes its own `dispatcher` to `fetch`, and an explicit dispatcher overrides the global one whatever the flag says.
## Decision
**One policy, resolved once from the launch environment, installed as the global dispatcher.** `packages/net/http-proxy` resolves a `ProxyPolicy` and installs it in `runProfile` immediately after the environment snapshot is provided and before any entry mounts. Node's `fetch` resolves undici's global dispatcher, so every plain `fetch()` and every SDK that reaches `globalThis.fetch` is covered without touching its code — nine call sites at the time of writing, and every future one for free. `loadLayeredEnv` has exactly one caller and `apps/web` ships no bin, so this single site covers every profile including `sdk-minimal`, which does not layer over `base`.
Resolution reads the launcher's snapshot rather than `process.env`, which is what makes a proxy in a `.env` layer work — the capability the environment-variable approach cannot have.
**A new `packages/net/` group.** The package must depend on `undici` (Node exposes no `node:undici`), so it cannot join the zero-dependency `util/` group; and `boot`, `web`, `subprocess`, and `workflow` all consume it, so joining any one of them would invert three dependencies. It is deliberately not a capability seam: transport policy has one implementation and one answer per process, so there is nothing to swap.
**The installed agent reads back what was resolved, not the raw environment.** `installGlobalProxy` publishes the policy into the proxy environment variables and then constructs `EnvHttpProxyAgent` with no options. Passing the fields explicitly instead would let undici fall back to reading the environment for any field left `undefined` — including a SOCKS or malformed value this package had already rejected, which `new ProxyAgent` would then throw on during boot. Publishing also normalizes what children inherit: the `ALL_PROXY` fallback lands as a concrete `HTTP_PROXY`, and the bypass list arrives with loopback merged.
This keeps `proxyForUrl()` and the dispatcher answering from one set of values. They must agree: if they disagreed about a URL, `web-fetch-http` would pin a connection the dispatcher meant to tunnel.
**Resolution supplies what neither Node nor undici does.** `ALL_PROXY` backs both schemes; a blank value counts as unset, because undici's `??` chain lets an empty lowercase name shadow a populated uppercase one; loopback is always bypassed, since the Web UI, the Connection transport, and every local test server would otherwise route through the proxy and loop. The bypass list carries `::1` *and* `[::1]`: undici's own matcher reads a bare `::1` as host `:` port `1` and never exempts it.
**Rejection is loud or quiet by where the value came from.** A SOCKS URL, an unparseable string, or an unsupported scheme *from the environment* is reported on stderr and skipped — that variable may have been exported for other tools, and a typo in it must not stop the agent from starting. The same value through the plugin's `Config` throws at load, because that is the harness's own configuration surface, where `AGENTS.md` requires misconfiguration to fail loud.
**Through a proxy, `web_fetch` stops resolving and pinning.** The provider validates a public address set and pins the connection to it. Through a proxy there is nothing to pin — the proxy performs the origin's DNS — and a pinned direct connection would bypass the proxy entirely. So a proxied hop skips resolution, and configuring a proxy is a statement that the proxy is trusted with destination selection. A hop the policy bypasses, which includes every loopback and every `NO_PROXY` entry, takes the resolved-and-pinned path unchanged. Kimi Code and Claude Code reached this same conclusion independently.
The URL-level policy is untouched: `http(s)` only, no embedded credentials, the length cap, and the cross-origin redirect refusal all still apply on every hop.
**A separate Node execution context gets the policy through its environment.** `childProxyEnv()` returns the resolved names plus `NODE_USE_ENV_PROXY=1`, merged into `scrubbedParentEnv()` — one function every spawner already shares — and into `workerSpawnEnv()`. A worker thread has its own `globalThis` and does not inherit the global dispatcher, and its environment is built explicitly rather than inherited, so it needs the names as well as the flag. Measured: the flag does take effect for a `Worker` given an explicit `env`.
This accepts a documented seam. Such a context matches bypass entries by Node's rules, which differ from this package's in separators and IPv4-range support, and the flag exists only on Node 22.21+ and 24+.
**Two SDKs do not reach `globalThis.fetch`, and reading their code said otherwise.** The audit first classified the OTLP exporter and the E2B SDK as covered, on a grep that found `globalThis.fetch` in `@opentelemetry/otlp-exporter-base`. That match is the *browser* transport; on Node the delegate selects `http-exporter-transport`, which posts through `node:http` — where a global dispatcher does not reach. E2B is a second shape again: it builds its own undici `Agent`/`ProxyAgent` and takes a `proxy` URL that it never reads from the environment. Both were measured direct and both are now wired — the exporter through `createNodeHttpAgent` as its `httpAgentOptions` factory, E2B through `proxyUrlFor` into `Sandbox.create`.
**Every call site carries an egress test, because reading the code was not enough.** `egress.spec.ts` in each owning package drives that site's real code path at an unresolvable `.invalid` host through a fake proxy and asserts the proxy saw the request. Nine of them cover the search backends, pi-ai discovery, MCP over HTTP, telemetry, E2B, a spawned child Node, and a worker thread. The gate below cannot see inside a dependency; these can, and they are what turns "an SDK changed its transport" from a silent regression into a failing test.
**A gate keeps the defect from returning.** `verify-no-bare-dispatcher` rejects `new Agent(...)` and an explicit `dispatcher:` outside the owning package. `createDispatcher(url, options)` is the sanctioned replacement, and a line that must genuinely ignore the proxy says so with a `proxy-exempt:` comment. The rule exists because `web-fetch-http`'s original `new Agent` was entirely reasonable when it was written — proxying simply did not exist yet, and nothing would have caught it.
## Alternatives considered
**Document `NODE_USE_ENV_PROXY=1` and stop.** Rejected on three measurements, above: invisible to `.env` layers, absent on the lowest supported Node, and bypassed by `web-fetch-http` regardless. It is also what the repository already claimed to do.
**Thread a policy value to every call site.** DeepSeek-Reasonix does this across 98 sites, buying a per-provider opt-out. Rejected: that opt-out exists for a need this harness does not have, and nine sites changed by hand means the tenth is forgotten — Pi's changelog records OAuth and Bedrock as two separate after-the-fact fixes of exactly that kind. The isolation argument for it is real, and is answered instead by handling worker threads explicitly and by proving disposal restores the previous dispatcher.
**`http.setGlobalProxyFromEnv()`.** Node's own programmatic switch covers `fetch` and `node:http` together and returns a restore function — the shape `ctx.effect()` wants. Unusable: `added: v24.14.0`, with nothing on the 22 line. Worth revisiting if `engines` ever rises past it.
**Patch `globalThis.fetch` via `undici.install()`.** Pi does, to keep fetch and the dispatcher on one undici when a newer Node's bundled fetch mishandles compressed responses through a userland dispatcher. Rejected as speculative here: this repository's `engines` ceiling has not reached that runtime.
**Make this a capability seam.** Rejected. Service Definition / Provider / Consumer is for swappable backends; this has one implementation and one answer per process. If operating-system proxy or PAC support ever lands, `resolveProxyPolicy` is the extension point.
**Read the operating system's proxy settings.** Rejected for this change. Only Codex and Reasonix among six surveyed products do it, and Codex keeps it behind a default-off flag. Measured on the author's machine, it would have found nothing: the proxy application had written the setting to the Wi-Fi service while the primary interface was a USB ethernet adapter with no proxy, so `scutil --proxy` reported none while the exported variables worked. It also needs its own bypass matcher, because an operating system list carries CIDR entries that neither undici nor Node matches.
**Give the `code-runtime` worker the proxy too.** Rejected. Model-authored programs run there with no ambient environment at all — a stronger containment than the scrubbed environment spawned commands get — and a proxy URL may carry credentials. Handing model code a credentialed URL to reach the network is the wrong trade; the exclusion is recorded in that package's limitations.
## Consequences
A user who exports `HTTPS_PROXY`, or writes it into a `.env` layer, is proxied everywhere the harness makes a request, with no flag and no configuration. Compositions that want the policy in `cordis.yml` mount the plugin; it is in no shipped bundle, so the default path installs exactly once.
Because the operating system's settings are not read, the user-facing documentation is now load-bearing rather than supplementary: a user who only toggled "system proxy" in a proxy application gets nothing and no diagnostic. `docs/user/guide/network-proxy.md` therefore states which variables to export and why a browser is proxied when a terminal is not — the three-mechanism confusion is the single most common report, and it is not specific to this harness.
`web_fetch`'s safety story now has two shapes, and its README says so: direct hops keep address validation and pinning, proxied hops delegate destination selection to a proxy the operator configured. This is the one outward-facing security promise the change alters.
Reaching Node's built-in `fetch` from a userland undici depends on both writing the legacy `Symbol.for('undici.globalDispatcher.1')` slot. That is an implicit cross-version coupling rather than a contract — corepack#834 records it breaking — so `tests/install.spec.ts` drives a real request through a loopback proxy. A version bump that breaks the coupling fails there instead of in the field.
The suite is hermetic against the developer's own environment: `plugin.spec.ts` saves and clears all eight proxy names in both casings. It has to. An exported lowercase `all_proxy` decided a test's outcome during development, because resolution reads lowercase first.
## Testing
`packages/net/http-proxy` holds 64 tests at 100% per-file coverage. Resolution covers precedence, the `ALL_PROXY` fallback, blank-shadowing, the SOCKS and malformed diagnostics, and `mode: 'off'`; bypass matching covers suffixes, ports, both IPv6 spellings, and the CIDR entry that deliberately does not match. Installation drives a real loopback proxy and asserts the absolute-form request arrives, that a bypassed target does not, and that disposal restores the dispatcher, the policy, and the environment.
`packages/web/web-fetch-http/tests/proxy.spec.ts` asserts the decision that matters most: under a proxy the public-address resolver is never called, while a bypassed hop still calls it exactly once, and the cross-origin redirect refusal survives on the proxied path.
`verify-no-bare-dispatcher.spec.ts` proves the gate rejects the exact shape this package was introduced to fix, accepts `createDispatcher`, accepts an annotated exemption, and passes on the current tree.
The egress suite also carries the negative case for telemetry: without the agent this change supplies, the exporter reaches no proxy at all. That assertion is what keeps the fix from being quietly reverted by an SDK upgrade that restores the default agent.
No recorded-session snapshot changes: nothing here alters a model-visible input or product-user-visible transcript output.
@@ -0,0 +1,83 @@
# Agent Note: 一份出站代理策略,在任何请求发生之前装好
Status: implemented
[English](2026-08-27-outbound-proxy-policy.md) | 中文
## Problem
Node 内置的 `fetch` 会忽略 `HTTP_PROXY` 与 `HTTPS_PROXY`。开发者运行的其他工具——curl、git、npm、pip——都遵循它们,所以代理后面的用户导出一次变量就期待一切随之生效。Harness 并没有:`setGlobalDispatcher`、`ProxyAgent` 与 `EnvHttpProxyAgent` 在 `packages/` 与 `apps/` 中出现次数为零,因此模型请求、每次 web 搜索、`web_fetch`、走 HTTP 的 MCP、OTLP 导出器与 E2B SDK 全部直连,且是静默的,任何地方都没有诊断。
仓库曾短暂拥有过答案,又在无人察觉时弄丢了。PR #971 在 `bin/dsh` 里设置了 `NODE_USE_ENV_PROXY=1`;十一天后 `bbb1b1cc38 cleanup: remove managed source installer` 整体删除了那个启动器,把该标志一并带走。留下的只有 `apps/cli/reference/README.md` 里的一句话,让读者去设置一个已经无人消费的变量。
即便照做,那句话也不可能生效,原因有三条且都经过实测。`NODE_USE_ENV_PROXY` 在进程启动时对环境取快照,而 `loadLayeredEnv()` 是在之后才合并 `.env` 层,因此写在项目或 `$DSH_HOME` `.env` 中的代理对它不可见。它只覆盖 Node 24.0+,在 22 线上只覆盖 22.21+——而 `engines` 允许 `^22.19.0`,那里根本没有这个变量,设置了也不会有任何警告。它也完全触及不到 `web-fetch-http`:该提供方向 `fetch` 传入自己的 `dispatcher`,而显式 dispatcher 无论标志如何都会覆盖全局的那个。
## Decision
**一份策略,从启动环境解析一次,装为全局 dispatcher。** `packages/net/http-proxy` 解析出 `ProxyPolicy`,并在 `runProfile` 中于环境快照提供之后、任何 entry 挂载之前完成安装。Node 的 `fetch` 解析的正是 undici 的全局 dispatcher,因此每一处普通 `fetch()` 以及每一个最终落到 `globalThis.fetch` 的 SDK 都无需改动即被覆盖——撰写时是九个调用点,未来新增的也自动覆盖。`loadLayeredEnv` 只有一个调用方,且 `apps/web` 不提供 bin,因此这一处即覆盖全部 profile,包括不叠加 `base` 的 `sdk-minimal`。
解析读取的是启动器的快照而非 `process.env`,这正是让 `.env` 层中的代理生效的原因——也是环境变量方案不可能具备的能力。
**新增 `packages/net/` 分组。** 本包必须依赖 `undici`(Node 不暴露 `node:undici`),因此无法加入零依赖的 `util/` 组;而 `boot`、`web`、`subprocess` 与 `workflow` 都消费它,放进其中任何一组都会让另外三条依赖反向。它刻意不是能力接缝:传输策略每个进程只有一种实现、一个答案,没有可替换的对象。
**已安装的 agent 读回的是解析结果,而非原始环境。** `installGlobalProxy` 把策略发布到代理环境变量中,再以无选项方式构造 `EnvHttpProxyAgent`。若改为显式传字段,undici 会对任何留空的字段回退去读环境——包括本包已经拒绝的 SOCKS 或畸形值,而 `new ProxyAgent` 会因此在启动期抛出。发布同时也规范化了子进程继承到的内容:`ALL_PROXY` 兜底落为具体的 `HTTP_PROXY`,绕过列表也已并入 loopback。
这样 `proxyForUrl()` 与 dispatcher 就从同一组值给出答案。两者必须一致:一旦对某个 URL 产生分歧,`web-fetch-http` 就会把 dispatcher 本打算隧道转发的连接固定到某个地址上。
**解析补上 Node 与 undici 都不提供的部分。** `ALL_PROXY` 为两种协议兜底;空值视为未设置,因为 undici 的 `??` 链会让空的小写名遮住有值的大写名;loopback 始终绕过,否则 Web UI、Connection 传输以及每一个本地测试服务器都会经由代理并形成回环。绕过列表同时携带 `::1` **与** `[::1]`:undici 自带的匹配器会把裸写的 `::1` 读成主机 `:` 端口 `1`,从而永不豁免它。
**拒绝是响还是静,取决于值从哪来。** 来自**环境**的 SOCKS URL、无法解析的字符串或不受支持的协议,会在 stderr 上报告并跳过——该变量可能是为其他工具导出的,它的笔误不应阻止 agent 启动。同样的值若经由插件的 `Config` 传入,则在加载期抛出,因为那是 Harness 自己的配置面,`AGENTS.md` 要求配置错误必须响。
**经由代理时,`web_fetch` 不再解析与固定地址。** 该提供方会校验一组公网地址并把连接固定到其上。经由代理时没有可固定的对象——origin 的 DNS 由代理执行——而固定后的直连会彻底绕开代理。因此代理转发的一跳跳过解析,配置代理即表示信任该代理进行目的地选择。被策略绕过的一跳,包括每一个 loopback 与每一条 `NO_PROXY` 条目,仍走原有的解析并固定路径。Kimi Code 与 Claude Code 各自独立得出了同一结论。
URL 层策略未受影响:仅 `http(s)`、禁止内嵌凭据、长度上限与跨域重定向拒绝在每一跳上依然生效。
**独立的 Node 执行上下文通过环境获得策略。** `childProxyEnv()` 返回解析出的变量名加上 `NODE_USE_ENV_PROXY=1`,并入 `scrubbedParentEnv()`(每个 spawner 本就共享的一个函数)与 `workerSpawnEnv()`。worker 线程拥有独立的 `globalThis`,不继承全局 dispatcher,而且它的环境是显式构造而非继承的,因此除标志外还需要那些变量名。已实测:对给定显式 `env` 的 `Worker`,该标志确实生效。
这接受了一处已记录的接缝。此类上下文按 Node 自己的规则匹配绕过条目,其分隔符与 IPv4 区间支持与本包不同,且该标志仅存在于 Node 22.21+ 与 24+。
**有两个 SDK 并不落到 `globalThis.fetch`,而读代码给出的答案是相反的。** 审计最初把 OTLP 导出器与 E2B SDK 判为已覆盖,依据是在 `@opentelemetry/otlp-exporter-base` 里 grep 到了 `globalThis.fetch`。那处命中属于**浏览器**传输;在 Node 上 delegate 选择的是 `http-exporter-transport`,它通过 `node:http` 投递——那里全局 dispatcher 触及不到。E2B 又是另一种形态:它自建 undici `Agent`/`ProxyAgent`,并接受一个自己从不从环境读取的 `proxy` URL。两者都实测为直连,现均已接通——导出器通过把 `createNodeHttpAgent` 作为其 `httpAgentOptions` 工厂,E2B 通过把 `proxyUrlFor` 传入 `Sandbox.create`。
**每个出网点都配一份出网测试,因为读代码不够。** 各所属包中的 `egress.spec.ts` 驱动该点的真实代码路径,目标是无法解析的 `.invalid` 主机,穿过一个假代理,并断言代理确实收到了请求。九份测试覆盖搜索后端、pi-ai 发现、走 HTTP 的 MCP、遥测、E2B、派生的子 Node 与 worker 线程。下面那条门禁看不进依赖内部;这些能,它们把「某个 SDK 换了传输」从静默回归变成失败的测试。
**用门禁防止该缺陷复现。** `verify-no-bare-dispatcher` 在所属包之外拒绝 `new Agent(...)` 与显式 `dispatcher:`。`createDispatcher(url, options)` 是受支持的替代;确实必须忽略代理的行用 `proxy-exempt:` 注释说明。这条规则之所以存在,是因为 `web-fetch-http` 里原本那行 `new Agent` 在写下时完全合理——那时根本还没有代理这回事,也没有任何机制会拦下它。
## Alternatives considered
**只写文档,让用户设 `NODE_USE_ENV_PROXY=1`。** 基于上文三条实测被否决:对 `.env` 层不可见、在最低支持的 Node 上不存在、且无论如何被 `web-fetch-http` 绕过。而这恰恰是仓库此前声称的做法。
**把策略值传递到每一个调用点。** DeepSeek-Reasonix 在 98 处这样做,换来每提供方的 opt-out。被否决:该能力服务于本 Harness 并不具备的需求,而手工改九处意味着第十处会被遗忘——Pi 的变更日志正记录了 OAuth 与 Bedrock 两次事后补漏。它关于隔离性的论点确实成立,本方案改为显式处理 worker 线程、并以「dispose 后还原前一个 dispatcher」的断言来回应。
**`http.setGlobalProxyFromEnv()`。** Node 自带的程序化开关同时覆盖 `fetch` 与 `node:http`,并返回还原函数——正是 `ctx.effect()` 想要的形态。不可用:`added: v24.14.0`,22 线上完全没有。若 `engines` 日后升过该版本,值得回头替换。
**用 `undici.install()` patch `globalThis.fetch`。** Pi 这样做,是为了让 fetch 与 dispatcher 处于同一个 undici——较新 Node 的内置 fetch 经 userland dispatcher 处理压缩响应时会出错。此处被否决为投机性复杂度:本仓库 `engines` 的上限尚未触及该运行时。
**做成能力接缝。** 被否决。Service Definition/Provider/Consumer 用于可替换后端;这里每个进程只有一种实现、一个答案。若日后要支持操作系统代理或 PAC,`resolveProxyPolicy` 就是扩展点。
**读取操作系统的代理设置。** 本次变更中被否决。所调研的六个产品中只有 Codex 与 Reasonix 这样做,且 Codex 把它放在默认关闭的开关之后。在作者机器上实测,它什么也读不到:代理软件把设置写在了 Wi-Fi 服务上,而主接口是一块没有代理的 USB 以太网卡,因此 `scutil --proxy` 报告无代理,而导出的环境变量却工作正常。它还需要自带的绕过匹配器,因为操作系统的列表含有 undici 与 Node 都不匹配的 CIDR 条目。
**也把代理给 `code-runtime` worker。** 被否决。模型编写的程序在那里运行时完全没有环境变量——这比派生命令得到的 scrubbed 环境更严——而代理 URL 可能携带凭据。把带凭据的 URL 交给模型代码去访问网络是错误的取舍;该排除已记入那个包的限制清单。
## Consequences
导出了 `HTTPS_PROXY`、或把它写进 `.env` 层的用户,在 Harness 发起请求的每一处都会走代理,无需任何标志与配置。希望把策略写进 `cordis.yml` 的组合可挂载该插件;它不在任何随附组合包中,因此默认路径只安装一次。
由于不读取操作系统设置,面向用户的文档从补充材料变成了承重件:仅在代理软件里拨了「系统代理」开关的用户什么也得不到,且没有诊断。因此 `docs/user/guide/network-proxy.md` 说明了要导出哪些变量,以及为什么浏览器走代理而终端不走——这个「三套机制」的困惑是最常见的报障,且并非本 Harness 特有。
`web_fetch` 的安全叙述现在有两种形态,其 README 已如实说明:直连的一跳保留地址校验与固定,代理转发的一跳把目的地选择交给运维方配置的代理。这是本次变更唯一改动的对外安全承诺。
userland undici 能触及 Node 内置的 `fetch`,依赖于两者都会写入 legacy 的 `Symbol.for('undici.globalDispatcher.1')` 槽位。那是跨版本的隐式耦合而非约定——corepack#834 记录了它失效的实例——因此 `tests/install.spec.ts` 会驱动一次真实请求穿过 loopback 代理。破坏该耦合的版本升级会在那里失败,而不是流到线上。
测试套件对开发者自身的环境免疫:`plugin.spec.ts` 会保存并清除全部八个代理变量名的两种大小写形式。这是必需的。开发过程中,一个已导出的小写 `all_proxy` 曾决定了某个测试的结果,因为解析优先读取小写。
## Testing
`packages/net/http-proxy` 有 64 个测试,per-file 覆盖率 100%。解析覆盖优先级、`ALL_PROXY` 兜底、空值遮蔽、SOCKS 与畸形值诊断,以及 `mode: 'off'`;绕过匹配覆盖后缀、端口、两种 IPv6 写法,以及刻意不匹配的 CIDR 条目。安装驱动一个真实的 loopback 代理,断言绝对形式的请求确实抵达、被绕过的目标不抵达,且 dispose 会还原 dispatcher、策略与环境。
`packages/web/web-fetch-http/tests/proxy.spec.ts` 断言了最关键的那个决定:经由代理时公网地址解析器完全不被调用,而被绕过的一跳仍恰好调用一次,且跨域重定向拒绝在代理路径上依然成立。
`verify-no-bare-dispatcher.spec.ts` 证明该门禁能拒掉本包所要修复的那种写法、接受 `createDispatcher`、接受带注释的豁免,并在当前代码树上通过。
出网测试还为遥测保留了负向用例:不带本次提供的 agent 时,导出器完全触及不到代理。该断言可以防止某次 SDK 升级恢复默认 agent 后把修复悄悄回退掉。
无录制会话快照变更:本次改动不影响任何模型可见输入或产品用户可见的 transcript 输出。
+1
View File
@@ -25,6 +25,7 @@ packages/ @deepseek-ai/dsh-<pkg> workspaces at packages/<group>/<pkg>/
lsp/ language-server capability
skill/ skill provider registry + local impl + catalog/loader tool
web/ web capability: Service Definition + search/fetch providers + tool Consumer
net/ outbound transport policy: the HTTP proxy every request inherits
compaction/ compaction capability + basic provider
context/ request-context plugins
subagent/ subagent capability: Service Definition + providers + delegation Consumers
+22 -17
View File
@@ -19,68 +19,75 @@
],
"dsh": {
"configTrees": [
{ "mount": "config/agent-presets", "path": "../../packages/preset/agent-presets/presets", "scanRoster": true }
{
"mount": "config/agent-presets",
"path": "../../packages/preset/agent-presets/presets",
"scanRoster": true
}
]
},
"license": "MIT",
"dependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/cordis-plugin-hmr": "workspace:^",
"@deepseek-ai/cordis-plugin-include": "workspace:^",
"@deepseek-ai/cordis-plugin-loader": "workspace:^",
"@deepseek-ai/cordis-plugin-timer": "workspace:^",
"@deepseek-ai/dsh-acp-app": "workspace:^",
"@deepseek-ai/dsh-agent-instructions": "workspace:^",
"@deepseek-ai/dsh-agent-tool-presentation": "workspace:^",
"@deepseek-ai/dsh-app-boot": "workspace:^",
"@deepseek-ai/dsh-base": "workspace:^",
"@deepseek-ai/dsh-cordis-client-runner": "workspace:^",
"@deepseek-ai/dsh-client-ui-agent-preset": "workspace:^",
"@deepseek-ai/dsh-client-ui-cordis": "workspace:^",
"@deepseek-ai/dsh-cmdline": "workspace:^",
"@deepseek-ai/dsh-command-compact": "workspace:^",
"@deepseek-ai/dsh-command-goal": "workspace:^",
"@deepseek-ai/dsh-compaction-basic": "workspace:^",
"@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:^",
"@deepseek-ai/dsh-cordis-client-runner": "workspace:^",
"@deepseek-ai/dsh-fs-local": "workspace:^",
"@deepseek-ai/dsh-goal": "workspace:^",
"@deepseek-ai/dsh-goal-round-driver": "workspace:^",
"@deepseek-ai/dsh-cmdline": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-fs-local": "workspace:^",
"@deepseek-ai/dsh-headless": "workspace:^",
"@deepseek-ai/dsh-mcp-client": "workspace:^",
"@deepseek-ai/dsh-home-paths": "workspace:^",
"@deepseek-ai/dsh-hooks-claude-code": "workspace:^",
"@deepseek-ai/dsh-hooks-codex": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-jobs-local": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-mcp-client": "workspace:^",
"@deepseek-ai/dsh-persona": "workspace:^",
"@deepseek-ai/dsh-plan-mode": "workspace:^",
"@deepseek-ai/dsh-terminal": "workspace:^",
"@deepseek-ai/dsh-terminal-bash": "workspace:^",
"@deepseek-ai/dsh-pwsh-local": "workspace:^",
"@deepseek-ai/dsh-pwsh-sandbox": "workspace:^",
"@deepseek-ai/dsh-session-projection": "workspace:^",
"@deepseek-ai/dsh-session-reference": "workspace:^",
"@deepseek-ai/dsh-schedule": "workspace:^",
"@deepseek-ai/dsh-sdk-app": "workspace:^",
"@deepseek-ai/dsh-sdk-minimal": "workspace:^",
"@deepseek-ai/dsh-time-context": "workspace:^",
"@deepseek-ai/dsh-session-projection": "workspace:^",
"@deepseek-ai/dsh-session-reference": "workspace:^",
"@deepseek-ai/dsh-skill": "workspace:^",
"@deepseek-ai/dsh-skill-filesystem": "workspace:^",
"@deepseek-ai/dsh-jobs-local": "workspace:^",
"@deepseek-ai/dsh-terminal": "workspace:^",
"@deepseek-ai/dsh-terminal-bash": "workspace:^",
"@deepseek-ai/dsh-time-context": "workspace:^",
"@deepseek-ai/dsh-tmux-context": "workspace:^",
"@deepseek-ai/dsh-token-meter": "workspace:^",
"@deepseek-ai/dsh-tool-ask-user": "workspace:^",
"@deepseek-ai/dsh-tool-bash": "workspace:^",
"@deepseek-ai/dsh-tool-bash-persistent": "workspace:^",
"@deepseek-ai/dsh-tool-pwsh-persistent": "workspace:^",
"@deepseek-ai/dsh-tool-cordis": "workspace:^",
"@deepseek-ai/dsh-tool-fs": "workspace:^",
"@deepseek-ai/dsh-tool-fs-search": "workspace:^",
"@deepseek-ai/dsh-tool-goal": "workspace:^",
"@deepseek-ai/dsh-tool-jobs": "workspace:^",
"@deepseek-ai/dsh-tool-pwsh": "workspace:^",
"@deepseek-ai/dsh-tool-pwsh-persistent": "workspace:^",
"@deepseek-ai/dsh-tool-ralph": "workspace:^",
"@deepseek-ai/dsh-schedule": "workspace:^",
"@deepseek-ai/dsh-tool-skill": "workspace:^",
"@deepseek-ai/dsh-tool-str-replace-editor": "workspace:^",
"@deepseek-ai/dsh-tool-subagent": "workspace:^",
"@deepseek-ai/dsh-tool-subagent-control": "workspace:^",
"@deepseek-ai/dsh-tool-jobs": "workspace:^",
"@deepseek-ai/dsh-tool-todo": "workspace:^",
"@deepseek-ai/dsh-tool-web": "workspace:^",
"@deepseek-ai/dsh-tool-workflow": "workspace:^",
@@ -88,10 +95,8 @@
"@deepseek-ai/dsh-webhook": "workspace:^",
"@deepseek-ai/dsh-webhook-github": "workspace:^",
"@deepseek-ai/dsh-workflow-worker-thread": "workspace:^",
"@deepseek-ai/dsh-agent-instructions": "workspace:^",
"@deepseek-ai/schemastery": "workspace:^",
"commander": "^15.0.0",
"@deepseek-ai/cordis": "workspace:^",
"js-yaml": "^4.2.0",
"node-addon-require-builtin": "^0.1.4"
},
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/cli/reference/README.md
README.md: f5cbe1659e5181cdaa6eaefcdb9bd8c8fe289e6d
README.zh.md: cf040f085241f0af58eb3db485bcedd4316726be
README.md: 9e88d527ebaed9a20b64ea77016fa7af4ca4c216
README.zh.md: 2d4f330aa46c94e8ebc2798dd678242ee2acb528
+1 -1
View File
@@ -98,4 +98,4 @@ Install external plugin bundles through `dsh plugin --profile <name> add <packag
<a id="source-execution"></a>
## Source execution
From the repository root, run `pnpm run build` separately after a fresh checkout and whenever artifacts need updating, then use `pnpm dsh <args...>`. The `package.json` script launches `apps/cli/src/bin.ts` with `node --import tsx/esm` without building and forwards every argument. Missing Typert host artifacts fail profile boot through module-resolution errors without a build instruction. Once those host artifacts exist, missing frontend or client-plugin bundles fail at startup with an instruction to run `pnpm run build`. The launcher does not check freshness, so existing stale bundles can run older browser code until rebuilt. The process inherits the launch environment; set `NODE_USE_ENV_PROXY=1` when a supporting Node version must honor `HTTP_PROXY` and `HTTPS_PROXY`. The installed form launches the built `apps/cli/lib/bin.js` without rebuilding the repository.
From the repository root, run `pnpm run build` separately after a fresh checkout and whenever artifacts need updating, then use `pnpm dsh <args...>`. The `package.json` script launches `apps/cli/src/bin.ts` with `node --import tsx/esm` without building and forwards every argument. Missing Typert host artifacts fail profile boot through module-resolution errors without a build instruction. Once those host artifacts exist, missing frontend or client-plugin bundles fail at startup with an instruction to run `pnpm run build`. The launcher does not check freshness, so existing stale bundles can run older browser code until rebuilt. The process inherits the launch environment, and `runProfile` resolves the outbound proxy from that snapshot before any entry mounts, so `HTTP_PROXY`/`HTTPS_PROXY` (and a proxy declared in a `.env` layer) apply without any further flag. The installed form launches the built `apps/cli/lib/bin.js` without rebuilding the repository.
+1 -1
View File
@@ -98,4 +98,4 @@ dsh web --help
<a id="source-execution"></a>
## 源码执行
请在仓库根目录中,于全新 checkout 之后及产物需要更新时单独运行 `pnpm run build`,然后使用 `pnpm dsh <args...>`。`package.json` 中的脚本不会构建,而是通过 `node --import tsx/esm` 启动 `apps/cli/src/bin.ts`,并转发所有参数。Typert Host 产物缺失时,profile 启动会因不含构建指引的模块解析错误而失败。这些 Host 产物存在后,如果前端或 Client plugin 组合包缺失,启动会失败并提示运行 `pnpm run build`。启动器不会检查产物是否为最新,因此已有的陈旧组合包可能继续运行旧版浏览器代码,直至重新构建。该进程会继承启动环境;当支持环境代理的 Node 版本必须遵循 `HTTP_PROXY` 和 `HTTPS_PROXY` 时,请设置 `NODE_USE_ENV_PROXY=1`。安装形式会直接启动构建后的 `apps/cli/lib/bin.js`,不会重新构建仓库。
请在仓库根目录中,于全新 checkout 之后及产物需要更新时单独运行 `pnpm run build`,然后使用 `pnpm dsh <args...>`。`package.json` 中的脚本不会构建,而是通过 `node --import tsx/esm` 启动 `apps/cli/src/bin.ts`,并转发所有参数。Typert Host 产物缺失时,profile 启动会因不含构建指引的模块解析错误而失败。这些 Host 产物存在后,如果前端或 Client plugin 组合包缺失,启动会失败并提示运行 `pnpm run build`。启动器不会检查产物是否为最新,因此已有的陈旧组合包可能继续运行旧版浏览器代码,直至重新构建。该进程会继承启动环境,且 `runProfile` 会在任何 entry 挂载之前从该快照解析出站代理,因此 `HTTP_PROXY`/`HTTPS_PROXY`(以及写在 `.env` 层中的代理)无需任何额外开关即可生效。安装形式会直接启动构建后的 `apps/cli/lib/bin.js`,不会重新构建仓库。
+15 -1
View File
@@ -30,6 +30,7 @@ import {
type Profile,
} from '@deepseek-ai/dsh-app-boot'
import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
import { installGlobalProxy, resolveProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
import { DSH_LAUNCH_ENVIRONMENT_KEY, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { provideCmdline, type AppReady } from '@deepseek-ai/dsh-cmdline'
import { createProcessShutdown, type ProcessShutdown } from './process-shutdown.ts'
@@ -207,10 +208,23 @@ function suppressShutdownError(ctx: Context, signal: AbortSignal, error: unknown
* @returns the settled root context and the shutdown controller.
*/
export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Context; shutdown: ProcessShutdown }> {
// Before the first plugin mounts and before anything can issue a request: Node's fetch ignores the
// proxy environment on its own, so every profile would otherwise connect directly. Resolving from
// the launcher's snapshot — not `process.env` — is what lets a proxy declared in a `.env` layer
// work, which the NODE_USE_ENV_PROXY flag cannot do because Node samples the environment at start.
const { policy: proxyPolicy, diagnostics } = resolveProxyPolicy(options.environment)
// A proxy variable may have been exported for other tools, so a value this harness cannot use is
// reported and skipped rather than being allowed to stop the agent from starting.
for (const diagnostic of diagnostics) process.stderr.write(`${NAME}: ${diagnostic.message}\n`)
const disposeProxy = await installGlobalProxy(proxyPolicy)
const composed = await composeProfile(options.profile, options.patchFiles)
const app: { current?: Context } = {}
const appReady = createAppReady()
const shutdown = createProcessShutdown(async () => { await app.current?.fiber.dispose() })
const shutdown = createProcessShutdown(async () => {
await app.current?.fiber.dispose()
await disposeProxy()
})
const signalShutdown = new AbortController()
const interrupt = (code: number): void => {
signalShutdown.abort()
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/config-catalog.md
config-catalog.md: 9e2b671ee054af797e9a919920fdd799e8c50e61
config-catalog.zh.md: df386630eeddefaccd9d1630da95a7116492173c
config-catalog.md: 6911366cd70f7fcf0bf0c0ed62d79e0bcd55e680
config-catalog.zh.md: 69a069624732ca5111c14a3939fa9c43e26d961c
+35 -2
View File
@@ -604,7 +604,7 @@ export interface Config {
}
```
Source: [`packages/e2b/e2b/src/index.ts:43`](../packages/e2b/e2b/src/index.ts)
Source: [`packages/e2b/e2b/src/index.ts:44`](../packages/e2b/e2b/src/index.ts)
<a id="deepseek-aidsh-experimental-agent-team"></a>
@@ -924,6 +924,39 @@ export interface Config {
Source: [`packages/host/webserver/src/index.ts:59`](../packages/host/webserver/src/index.ts)
<a id="deepseek-aidsh-http-proxy"></a>
## `@deepseek-ai/dsh-http-proxy`
```ts config-catalog
/** Composition-declared proxy settings; every field is optional and the environment outranks them. */
export interface Config extends ProxyConfig {}
/**
* Proxy settings a composition may declare in `cordis.yml`. Real environment variables win over every
* field here except `mode`, which governs whether the environment is consulted at all.
*/
export interface ProxyConfig {
/**
* `env` (default) resolves from the environment and lets the fields below fill the gaps; `custom`
* does the same but is the honest label for a composition that supplies its own proxy; `off`
* ignores every source and keeps the harness's own requests direct.
*
* `off` governs requests this process issues. It does not strip proxy variables from the
* environment child tools inherit, because those belong to the user, not to the harness.
*/
mode?: 'env' | 'custom' | 'off'
/** Proxy for `http:` origins when the environment supplies none. */
httpProxy?: string
/** Proxy for `https:` origins when the environment supplies none. */
httpsProxy?: string
/** Bypass list when the environment supplies none. {@link LOOPBACK_NO_PROXY} is merged in regardless. */
noProxy?: string
}
```
Source: [`packages/net/http-proxy/src/index.ts:49`](../packages/net/http-proxy/src/index.ts)
<a id="deepseek-aidsh-invariants"></a>
## `@deepseek-ai/dsh-invariants`
@@ -2047,7 +2080,7 @@ export enum SessionTelemetryMode {
Depends on: `BatchLogRecordProcessorOptions` (`@opentelemetry/sdk-logs`) · `OTLPExporterNodeConfigBase` (`@opentelemetry/otlp-exporter-base`)
Source: [`packages/session/session-telemetry-otel/src/index.ts:91`](../packages/session/session-telemetry-otel/src/index.ts)
Source: [`packages/session/session-telemetry-otel/src/index.ts:92`](../packages/session/session-telemetry-otel/src/index.ts)
<a id="deepseek-aidsh-session-title"></a>
+34 -1
View File
@@ -606,7 +606,7 @@ export interface Config {
}
```
来源:[`packages/e2b/e2b/src/index.ts:43`](../packages/e2b/e2b/src/index.ts)
来源:[`packages/e2b/e2b/src/index.ts:44`](../packages/e2b/e2b/src/index.ts)
<a id="deepseek-aidsh-experimental-agent-team"></a>
@@ -926,6 +926,39 @@ export interface Config {
来源:[`packages/host/webserver/src/index.ts:59`](../packages/host/webserver/src/index.ts)
<a id="deepseek-aidsh-http-proxy"></a>
## `@deepseek-ai/dsh-http-proxy`
```ts config-catalog
/** Composition-declared proxy settings; every field is optional and the environment outranks them. */
export interface Config extends ProxyConfig {}
/**
* Proxy settings a composition may declare in `cordis.yml`. Real environment variables win over every
* field here except `mode`, which governs whether the environment is consulted at all.
*/
export interface ProxyConfig {
/**
* `env` (default) resolves from the environment and lets the fields below fill the gaps; `custom`
* does the same but is the honest label for a composition that supplies its own proxy; `off`
* ignores every source and keeps the harness's own requests direct.
*
* `off` governs requests this process issues. It does not strip proxy variables from the
* environment child tools inherit, because those belong to the user, not to the harness.
*/
mode?: 'env' | 'custom' | 'off'
/** Proxy for `http:` origins when the environment supplies none. */
httpProxy?: string
/** Proxy for `https:` origins when the environment supplies none. */
httpsProxy?: string
/** Bypass list when the environment supplies none. {@link LOOPBACK_NO_PROXY} is merged in regardless. */
noProxy?: string
}
```
来源:[`packages/net/http-proxy/src/index.ts:47`](../packages/net/http-proxy/src/index.ts)
<a id="deepseek-aidsh-invariants"></a>
## `@deepseek-ai/dsh-invariants`
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/module-graph.md
module-graph.md: 7c4ccbf6841070d37116641c1404a70cbb598769
module-graph.zh.md: 4581a5bdda1e75a9678a731ab109d3b3c71b7434
module-graph.md: 4aa7db428e91719bdd6aaee385c41af903922726
module-graph.zh.md: 7d390651a8887946b9354b80964e185b5c2c8223
+25 -15
View File
@@ -262,6 +262,9 @@ flowchart TD
subgraph group_mcp["packages/mcp"]
pkg_mcp_client["mcp-client"]
end
subgraph group_net["packages/net"]
pkg_http_proxy["http-proxy"]
end
subgraph group_preset["packages/preset"]
pkg_agent_presets["agent-presets"]
pkg_persona["persona"]
@@ -382,7 +385,6 @@ flowchart TD
pkg_client_web --> pkg_invariants
pkg_code_runtime --> pkg_invariants
pkg_code_runtime_python --> pkg_invariants
pkg_e2b --> pkg_invariants
pkg_experimental_agent_team_profile --> pkg_invariants
pkg_experimental_agent_team_web_profile --> pkg_invariants
pkg_experimental_webworker_packer --> pkg_invariants
@@ -392,7 +394,6 @@ flowchart TD
pkg_host_webserver --> pkg_invariants
pkg_sandbox_windows_acl --> pkg_invariants
pkg_storage --> pkg_invariants
pkg_subprocess --> pkg_invariants
pkg_win32_process --> pkg_invariants
pkg_llm_mock_server --> pkg_invariants
pkg_typert_generator --> pkg_invariants
@@ -404,25 +405,20 @@ flowchart TD
pkg_client_modules --> pkg_invariants
pkg_credentials --> pkg_brand
pkg_credentials --> pkg_invariants
pkg_subprocess_e2b --> pkg_e2b
pkg_subprocess_e2b --> pkg_invariants
pkg_subprocess_e2b --> pkg_subprocess
pkg_subprocess_e2b --> pkg_timeout
pkg_host_plugin_inventory --> pkg_brand
pkg_host_plugin_inventory --> pkg_invariants
pkg_host_plugin_inventory --> pkg_typert_protocol
pkg_anonymous_user_id --> pkg_brand
pkg_anonymous_user_id --> pkg_home_paths
pkg_anonymous_user_id --> pkg_invariants
pkg_http_proxy --> pkg_invariants
pkg_http_proxy --> pkg_launch_environment
pkg_storage_domain --> pkg_invariants
pkg_storage_domain --> pkg_storage
pkg_storage_json --> pkg_invariants
pkg_storage_json --> pkg_storage
pkg_storage_sqlite --> pkg_invariants
pkg_storage_sqlite --> pkg_storage
pkg_subprocess_local --> pkg_invariants
pkg_subprocess_local --> pkg_subprocess
pkg_subprocess_local --> pkg_timeout
pkg_typert_loader --> pkg_invariants
pkg_typert_loader --> pkg_typert_registry
pkg_llm --> pkg_attachment
@@ -441,9 +437,13 @@ flowchart TD
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_invariants
pkg_credentials_local --> pkg_launch_environment
pkg_e2b --> pkg_http_proxy
pkg_e2b --> pkg_invariants
pkg_experimental_inspector --> pkg_client_modules
pkg_experimental_inspector --> pkg_host_webserver
pkg_experimental_inspector --> pkg_invariants
pkg_subprocess --> pkg_http_proxy
pkg_subprocess --> pkg_invariants
pkg_session --> pkg_brand
pkg_session --> pkg_invariants
pkg_session --> pkg_llm
@@ -460,11 +460,19 @@ flowchart TD
pkg_authorization --> pkg_credentials
pkg_authorization --> pkg_invariants
pkg_authorization --> pkg_llm
pkg_subprocess_e2b --> pkg_e2b
pkg_subprocess_e2b --> pkg_invariants
pkg_subprocess_e2b --> pkg_subprocess
pkg_subprocess_e2b --> pkg_timeout
pkg_lsp --> pkg_brand
pkg_lsp --> pkg_invariants
pkg_lsp --> pkg_llm
pkg_subprocess_local --> pkg_invariants
pkg_subprocess_local --> pkg_subprocess
pkg_subprocess_local --> pkg_timeout
pkg_skill_badge --> pkg_invariants
pkg_skill_badge --> pkg_skill
pkg_web_fetch_http --> pkg_http_proxy
pkg_web_fetch_http --> pkg_invariants
pkg_web_fetch_http --> pkg_timeout
pkg_web_fetch_http --> pkg_web
@@ -944,6 +952,7 @@ flowchart TD
pkg_session_checkpoint_policy --> pkg_tools
pkg_session_telemetry_otel --> pkg_anonymous_user_id
pkg_session_telemetry_otel --> pkg_command_feedback
pkg_session_telemetry_otel --> pkg_http_proxy
pkg_session_telemetry_otel --> pkg_invariants
pkg_session_telemetry_otel --> pkg_llm
pkg_session_telemetry_otel --> pkg_session
@@ -1763,7 +1772,6 @@ flowchart TD
| [`client-web`](../packages/client/web) | `client` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`code-runtime`](../packages/code-runtime/code-runtime) | `code-runtime` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`code-runtime-python`](../packages/code-runtime/code-runtime-python) | `code-runtime` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`e2b`](../packages/e2b/e2b) | `e2b` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`experimental-agent-team-profile`](../packages/experimental/agent-team-profile) | `experimental` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`experimental-agent-team-web-profile`](../packages/experimental/agent-team-web-profile) | `experimental` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`experimental-webworker-packer`](../packages/experimental/webworker-packer) | `experimental` | [`invariants`](../packages/runtime-diagnostics/invariants) |
@@ -1773,7 +1781,6 @@ flowchart TD
| [`host-webserver`](../packages/host/webserver) | `host` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`storage`](../packages/storage/storage) | `storage` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`typert-generator`](../packages/typert/generator) | `typert` | [`invariants`](../packages/runtime-diagnostics/invariants) |
@@ -1782,27 +1789,30 @@ flowchart TD
| [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`client-modules`](../packages/client/modules) | `client` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`credentials`](../packages/credentials/credentials) | `credentials` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`subprocess-e2b`](../packages/e2b/subprocess-e2b) | `e2b` | [`e2b`](../packages/e2b/e2b), [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`typert-protocol`](../packages/typert/protocol) |
| [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`http-proxy`](../packages/net/http-proxy) | `net` | [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment) |
| [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`invariants`](../packages/runtime-diagnostics/invariants), [`storage`](../packages/storage/storage) |
| [`storage-json`](../packages/storage/storage-json) | `storage` | [`invariants`](../packages/runtime-diagnostics/invariants), [`storage`](../packages/storage/storage) |
| [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`invariants`](../packages/runtime-diagnostics/invariants), [`storage`](../packages/storage/storage) |
| [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`typert-loader`](../packages/typert/loader) | `typert` | [`invariants`](../packages/runtime-diagnostics/invariants), [`typert-registry`](../packages/typert/registry) |
| [`llm`](../packages/llm/llm) | `llm` | [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`timeout`](../packages/util/timeout), [`typert-protocol`](../packages/typert/protocol) |
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`client-hmr`](../packages/client/hmr) | `client` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment) |
| [`e2b`](../packages/e2b/e2b) | `e2b` | [`http-proxy`](../packages/net/http-proxy), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/net/http-proxy), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`session`](../packages/core/session) | `core` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`typert-protocol`](../packages/typert/protocol) |
| [`system-prompt`](../packages/core/system-prompt) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`web`](../packages/web/web) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) |
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) |
| [`subprocess-e2b`](../packages/e2b/subprocess-e2b) | `e2b` | [`e2b`](../packages/e2b/e2b), [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) |
| [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`skill-badge`](../packages/skill/skill-badge) | `skill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`skill`](../packages/skill/skill) |
| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) |
| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`http-proxy`](../packages/net/http-proxy), [`invariants`](../packages/runtime-diagnostics/invariants), [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) |
| [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) |
| [`web-search-perplexity`](../packages/web/web-search-perplexity) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) |
| [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
@@ -1893,7 +1903,7 @@ flowchart TD
| [`agent-presets`](../packages/preset/agent-presets) | `preset` | [`agent`](../packages/core/agent), [`atomic-write`](../packages/util/atomic-write), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) |
| [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy) | `session` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) |
| [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) |
| [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`http-proxy`](../packages/net/http-proxy), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) |
| [`session-title-all-prompts-llm`](../packages/session/session-title-all-prompts-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) |
| [`session-title-first-prompt-llm`](../packages/session/session-title-first-prompt-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) |
| [`shell-env`](../packages/shell/shell-env) | `shell` | [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`session-persistence`](../packages/session/session-persistence), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) |
+25 -15
View File
@@ -264,6 +264,9 @@ flowchart TD
subgraph group_mcp["packages/mcp"]
pkg_mcp_client["mcp-client"]
end
subgraph group_net["packages/net"]
pkg_http_proxy["http-proxy"]
end
subgraph group_preset["packages/preset"]
pkg_agent_presets["agent-presets"]
pkg_persona["persona"]
@@ -384,7 +387,6 @@ flowchart TD
pkg_client_web --> pkg_invariants
pkg_code_runtime --> pkg_invariants
pkg_code_runtime_python --> pkg_invariants
pkg_e2b --> pkg_invariants
pkg_experimental_agent_team_profile --> pkg_invariants
pkg_experimental_agent_team_web_profile --> pkg_invariants
pkg_experimental_webworker_packer --> pkg_invariants
@@ -394,7 +396,6 @@ flowchart TD
pkg_host_webserver --> pkg_invariants
pkg_sandbox_windows_acl --> pkg_invariants
pkg_storage --> pkg_invariants
pkg_subprocess --> pkg_invariants
pkg_win32_process --> pkg_invariants
pkg_llm_mock_server --> pkg_invariants
pkg_typert_generator --> pkg_invariants
@@ -406,25 +407,20 @@ flowchart TD
pkg_client_modules --> pkg_invariants
pkg_credentials --> pkg_brand
pkg_credentials --> pkg_invariants
pkg_subprocess_e2b --> pkg_e2b
pkg_subprocess_e2b --> pkg_invariants
pkg_subprocess_e2b --> pkg_subprocess
pkg_subprocess_e2b --> pkg_timeout
pkg_host_plugin_inventory --> pkg_brand
pkg_host_plugin_inventory --> pkg_invariants
pkg_host_plugin_inventory --> pkg_typert_protocol
pkg_anonymous_user_id --> pkg_brand
pkg_anonymous_user_id --> pkg_home_paths
pkg_anonymous_user_id --> pkg_invariants
pkg_http_proxy --> pkg_invariants
pkg_http_proxy --> pkg_launch_environment
pkg_storage_domain --> pkg_invariants
pkg_storage_domain --> pkg_storage
pkg_storage_json --> pkg_invariants
pkg_storage_json --> pkg_storage
pkg_storage_sqlite --> pkg_invariants
pkg_storage_sqlite --> pkg_storage
pkg_subprocess_local --> pkg_invariants
pkg_subprocess_local --> pkg_subprocess
pkg_subprocess_local --> pkg_timeout
pkg_typert_loader --> pkg_invariants
pkg_typert_loader --> pkg_typert_registry
pkg_llm --> pkg_attachment
@@ -443,9 +439,13 @@ flowchart TD
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_invariants
pkg_credentials_local --> pkg_launch_environment
pkg_e2b --> pkg_http_proxy
pkg_e2b --> pkg_invariants
pkg_experimental_inspector --> pkg_client_modules
pkg_experimental_inspector --> pkg_host_webserver
pkg_experimental_inspector --> pkg_invariants
pkg_subprocess --> pkg_http_proxy
pkg_subprocess --> pkg_invariants
pkg_session --> pkg_brand
pkg_session --> pkg_invariants
pkg_session --> pkg_llm
@@ -462,11 +462,19 @@ flowchart TD
pkg_authorization --> pkg_credentials
pkg_authorization --> pkg_invariants
pkg_authorization --> pkg_llm
pkg_subprocess_e2b --> pkg_e2b
pkg_subprocess_e2b --> pkg_invariants
pkg_subprocess_e2b --> pkg_subprocess
pkg_subprocess_e2b --> pkg_timeout
pkg_lsp --> pkg_brand
pkg_lsp --> pkg_invariants
pkg_lsp --> pkg_llm
pkg_subprocess_local --> pkg_invariants
pkg_subprocess_local --> pkg_subprocess
pkg_subprocess_local --> pkg_timeout
pkg_skill_badge --> pkg_invariants
pkg_skill_badge --> pkg_skill
pkg_web_fetch_http --> pkg_http_proxy
pkg_web_fetch_http --> pkg_invariants
pkg_web_fetch_http --> pkg_timeout
pkg_web_fetch_http --> pkg_web
@@ -946,6 +954,7 @@ flowchart TD
pkg_session_checkpoint_policy --> pkg_tools
pkg_session_telemetry_otel --> pkg_anonymous_user_id
pkg_session_telemetry_otel --> pkg_command_feedback
pkg_session_telemetry_otel --> pkg_http_proxy
pkg_session_telemetry_otel --> pkg_invariants
pkg_session_telemetry_otel --> pkg_llm
pkg_session_telemetry_otel --> pkg_session
@@ -1765,7 +1774,6 @@ flowchart TD
| [`client-web`](../packages/client/web) | `client` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`code-runtime`](../packages/code-runtime/code-runtime) | `code-runtime` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`code-runtime-python`](../packages/code-runtime/code-runtime-python) | `code-runtime` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`e2b`](../packages/e2b/e2b) | `e2b` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`experimental-agent-team-profile`](../packages/experimental/agent-team-profile) | `experimental` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`experimental-agent-team-web-profile`](../packages/experimental/agent-team-web-profile) | `experimental` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`experimental-webworker-packer`](../packages/experimental/webworker-packer) | `experimental` | [`invariants`](../packages/runtime-diagnostics/invariants) |
@@ -1775,7 +1783,6 @@ flowchart TD
| [`host-webserver`](../packages/host/webserver) | `host` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`storage`](../packages/storage/storage) | `storage` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`typert-generator`](../packages/typert/generator) | `typert` | [`invariants`](../packages/runtime-diagnostics/invariants) |
@@ -1784,27 +1791,30 @@ flowchart TD
| [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`client-modules`](../packages/client/modules) | `client` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`credentials`](../packages/credentials/credentials) | `credentials` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`subprocess-e2b`](../packages/e2b/subprocess-e2b) | `e2b` | [`e2b`](../packages/e2b/e2b), [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`typert-protocol`](../packages/typert/protocol) |
| [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`http-proxy`](../packages/net/http-proxy) | `net` | [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment) |
| [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`invariants`](../packages/runtime-diagnostics/invariants), [`storage`](../packages/storage/storage) |
| [`storage-json`](../packages/storage/storage-json) | `storage` | [`invariants`](../packages/runtime-diagnostics/invariants), [`storage`](../packages/storage/storage) |
| [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`invariants`](../packages/runtime-diagnostics/invariants), [`storage`](../packages/storage/storage) |
| [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`typert-loader`](../packages/typert/loader) | `typert` | [`invariants`](../packages/runtime-diagnostics/invariants), [`typert-registry`](../packages/typert/registry) |
| [`llm`](../packages/llm/llm) | `llm` | [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`timeout`](../packages/util/timeout), [`typert-protocol`](../packages/typert/protocol) |
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`client-hmr`](../packages/client/hmr) | `client` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment) |
| [`e2b`](../packages/e2b/e2b) | `e2b` | [`http-proxy`](../packages/net/http-proxy), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/net/http-proxy), [`invariants`](../packages/runtime-diagnostics/invariants) |
| [`session`](../packages/core/session) | `core` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`typert-protocol`](../packages/typert/protocol) |
| [`system-prompt`](../packages/core/system-prompt) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`web`](../packages/web/web) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) |
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) |
| [`subprocess-e2b`](../packages/e2b/subprocess-e2b) | `e2b` | [`e2b`](../packages/e2b/e2b), [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) |
| [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`skill-badge`](../packages/skill/skill-badge) | `skill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`skill`](../packages/skill/skill) |
| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) |
| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`http-proxy`](../packages/net/http-proxy), [`invariants`](../packages/runtime-diagnostics/invariants), [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) |
| [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) |
| [`web-search-perplexity`](../packages/web/web-search-perplexity) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) |
| [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
@@ -1895,7 +1905,7 @@ flowchart TD
| [`agent-presets`](../packages/preset/agent-presets) | `preset` | [`agent`](../packages/core/agent), [`atomic-write`](../packages/util/atomic-write), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) |
| [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy) | `session` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) |
| [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) |
| [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`http-proxy`](../packages/net/http-proxy), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) |
| [`session-title-all-prompts-llm`](../packages/session/session-title-all-prompts-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) |
| [`session-title-first-prompt-llm`](../packages/session/session-title-first-prompt-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) |
| [`shell-env`](../packages/shell/shell-env) | `shell` | [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`session-persistence`](../packages/session/session-persistence), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) |
+6
View File
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/user/guide/network-proxy.md
network-proxy.md: 33f84766967ccac501629e930eaaef1b1c24d8b9
network-proxy.zh.md: 82aa63bb042d873c1fb16090a2a289dac033c4aa
+74
View File
@@ -0,0 +1,74 @@
# Run DSH behind a network proxy
English | [中文](network-proxy.zh.md)
DSH routes every outbound request — model calls, web search, page fetches, MCP servers over HTTP, and telemetry — through the proxy named by the standard proxy environment variables. It reads them at launch; nothing else needs configuring.
## Export the variables
```sh
export HTTPS_PROXY=http://127.0.0.1:7890
export HTTP_PROXY=http://127.0.0.1:7890
```
Put both lines in your shell profile so every `dsh` invocation inherits them. DSH also reads a `.env` file in the launch directory and in `$DSH_HOME`, so a proxy that should apply to one project can live there instead; a real environment variable always wins over a file.
A proxy that needs credentials takes them in the URL: `http://user:[email protected]:8080`. DSH never prints the password back — a proxy it reports in a diagnostic shows the username and masks the rest.
## Why your browser is proxied but your terminal is not
This is the most common surprise, and it is not specific to DSH. There is no single "system proxy" that all software obeys — there are three unrelated mechanisms:
| Mechanism | Who follows it |
|---|---|
| The operating system's proxy settings | Safari, most native macOS apps, Chrome and Edge |
| The `HTTP_PROXY` / `HTTPS_PROXY` environment variables | `curl`, `git`, `npm`, `pip`, and DSH |
| TUN mode (a virtual network interface) | Everything, transparently |
The "system proxy" switch in a proxy application such as Clash writes only the first one. Browsers pick it up; command-line tools never see it. That is why exporting the variables is a separate step, and why turning on TUN mode makes both work without any variables at all.
DSH does not read the operating system's proxy settings. Export the variables, or use TUN mode.
## Choose what stays direct
`NO_PROXY` lists hosts to reach directly:
```sh
export NO_PROXY=internal.example.com,.corp.example.com,registry.local
```
An entry matches an exact host, a `.suffix` or `*.suffix` domain, an optional `:port`, or `*` for everything.
**CIDR ranges do not work.** An operating system bypass list often contains entries like `10.0.0.0/8` or `192.168.0.0/16`; copying those into `NO_PROXY` has no effect. Use host names or domain suffixes instead.
You do not need to list `localhost` or `127.0.0.1`. DSH always bypasses loopback, because its own Web UI and local servers would otherwise route through the proxy and loop.
## Limits worth knowing
**SOCKS proxies are not supported.** A `socks5://` value is reported at startup and skipped, and DSH connects directly. Point the variables at your proxy application's HTTP port instead — most expose both, and the HTTP one is usually a neighbouring port number.
**`ALL_PROXY` alone is enough.** DSH falls back to it for both schemes, even though Node and curl differ on this. Setting `HTTPS_PROXY` explicitly is still clearer.
**A TLS-intercepting corporate proxy needs its certificate.** If requests fail with a certificate error once the proxy is reachable, point Node at your organisation's CA bundle before launching:
```sh
export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem
```
Node reads that variable only at process start, so export it before running `dsh`.
**Tools DSH runs for you follow the same proxy.** Commands in the bash tool, `git`, `gh`, and MCP servers started as child processes all inherit these variables. A child that is itself a Node program honors them only on Node 22.21 or later; an older Node connects directly.
## Check that it worked
Ask the agent to fetch a page and watch your proxy application's connection log:
```sh
dsh --profile headless "fetch https://example.com and tell me the page title"
```
If the request does not appear there, confirm the variables survive into DSH's own environment:
```sh
env | grep -i proxy
```
+74
View File
@@ -0,0 +1,74 @@
# 在网络代理后面运行 DSH
[English](network-proxy.md) | 中文
DSH 会把每一个出站请求——模型调用、web 搜索、页面抓取、走 HTTP 的 MCP 服务器与遥测——都经由标准代理环境变量所指定的代理发出。它在启动时读取这些变量,不需要其他配置。
## 导出环境变量
```sh
export HTTPS_PROXY=http://127.0.0.1:7890
export HTTP_PROXY=http://127.0.0.1:7890
```
把这两行写进 shell 配置,这样每次调用 `dsh` 都会继承它们。DSH 还会读取启动目录与 `$DSH_HOME` 下的 `.env` 文件,因此只对某个项目生效的代理可以写在那里;真实环境变量始终优先于文件。
需要凭据的代理把凭据写在 URL 里:`http://user:[email protected]:8080`。DSH 绝不会回显密码——诊断信息中出现的代理会显示用户名并掩去其余部分。
## 为什么浏览器走代理、终端却不走
这是最常见的意外,而且并非 DSH 特有。**根本不存在一个所有软件都遵循的"系统代理"**——实际上有三套互不相干的机制:
| 机制 | 谁会遵循 |
|---|---|
| 操作系统的代理设置 | Safari、绝大多数 macOS 原生应用、Chrome 与 Edge |
| `HTTP_PROXY` / `HTTPS_PROXY` 环境变量 | `curl`、`git`、`npm`、`pip` 以及 DSH |
| TUN 模式(虚拟网卡) | 所有程序,且对应用透明 |
Clash 这类代理软件里的"系统代理"开关只写第一套。浏览器会读到它,命令行工具则永远看不到。这就是为什么导出环境变量是一个独立步骤,也是为什么打开 TUN 模式后两者都能工作、且完全不需要变量。
DSH 不读取操作系统的代理设置。请导出环境变量,或使用 TUN 模式。
## 指定哪些目标保持直连
`NO_PROXY` 列出需要直连的主机:
```sh
export NO_PROXY=internal.example.com,.corp.example.com,registry.local
```
一个条目可匹配精确主机、`.suffix` 或 `*.suffix` 域名、可选的 `:port`,或用 `*` 匹配全部。
**CIDR 网段不生效。** 操作系统的绕过列表常含 `10.0.0.0/8` 或 `192.168.0.0/16` 这类条目;把它们复制进 `NO_PROXY` 不会有任何效果。请改用主机名或域名后缀。
不需要列出 `localhost` 或 `127.0.0.1`。DSH 始终绕过 loopback,否则它自己的 Web UI 与本地服务器都会经由代理并形成回环。
## 值得知道的限制
**不支持 SOCKS 代理。** `socks5://` 形式的值会在启动时被报告并跳过,DSH 转为直连。请把变量指向代理软件的 HTTP 端口——多数软件两者都提供,且 HTTP 端口通常就在相邻的端口号上。
**只设 `ALL_PROXY` 也够用。** DSH 会用它为两种协议兜底,尽管 Node 与 curl 在这一点上并不一致。显式设置 `HTTPS_PROXY` 仍然更清楚。
**做 TLS 拦截的企业代理需要它的证书。** 如果代理已经可达但请求仍报证书错误,请在启动前把 Node 指向你所在组织的 CA 包:
```sh
export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem
```
Node 只在进程启动时读取该变量,所以要在运行 `dsh` 之前导出。
**DSH 替你运行的工具遵循同一个代理。** bash 工具里的命令、`git`、`gh`,以及作为子进程启动的 MCP 服务器都会继承这些变量。子进程若本身是 Node 程序,则需 Node 22.21 或更高版本才会遵循;更旧的 Node 会直连。
## 验证是否生效
让 agent 抓取一个页面,同时观察代理软件的连接日志:
```sh
dsh --profile headless "fetch https://example.com and tell me the page title"
```
如果请求没有出现在那里,确认变量确实进入了 DSH 自己的环境:
```sh
env | grep -i proxy
```
+1
View File
@@ -106,6 +106,7 @@
"verify-application-entrypoints": "tsx scripts/verify-application-entrypoints.ts",
"verify-client-packages": "tsx scripts/verify-client-packages.ts",
"verify-client-ui-i18n": "tsx scripts/verify-client-ui-i18n.ts",
"verify-no-bare-dispatcher": "tsx scripts/verify-no-bare-dispatcher.ts",
"verify-vendored-links": "tsx scripts/verify-vendored-links.ts",
"verify-cordis-config": "tsx scripts/verify-cordis-config.ts",
"rescope-vendor": "tsx scripts/rescope-vendor.ts",
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/README.md
README.md: e1a729a6c80d8f8125e0d4c4b038dc631edd7a26
README.zh.md: 754ad0fc44677afb243c3a32a0281f58ec3b3af2
README.md: 032c18f301846b6e80c89b5f208e344d954b336b
README.zh.md: 86c3ce9b19812bcb21c6bb7440ee96f5075922f4
+1
View File
@@ -53,6 +53,7 @@ Every package lives in exactly one group; new packages join existing groups, and
| [`workflow/`](workflow/README.md) | Workflow seam, worker-thread engine, and model-facing `workflow`/`ralph` tools |
| [`webhook/`](webhook/README.md) | Verified external events, trusted rules, and fire-and-forget Workspace Sessions |
| [`web/`](web/README.md) | Web capability family: seam, search/fetch providers, model-facing web tools |
| [`net/`](net/README.md) | Process-wide outbound transport policy: the HTTP proxy every request inherits |
| [`attachment/`](attachment/README.md) | Durable attachment identity, validation, local content-addressed storage |
| [`spill/`](spill/README.md) | Spill capability family: storage seam, local impl, tool-result spill policy |
| [`todo/`](todo/README.md) | The model-facing `todo_write` tool |
+1
View File
@@ -53,6 +53,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会
| [`workflow/`](workflow/README.zh.md) | 工作流 seam、worker 线程引擎、面向模型的 `workflow`/`ralph` 工具 |
| [`webhook/`](webhook/README.zh.md) | 已验证外部事件、受信规则与即发即弃 Workspace Session |
| [`web/`](web/README.zh.md) | Web 能力系列:seam、搜索/获取提供方、面向模型的 Web 工具 |
| [`net/`](net/README.zh.md) | 进程级出站传输策略:每个请求都会继承的 HTTP 代理 |
| [`attachment/`](attachment/README.zh.md) | 持久附件标识、校验、本地内容寻址存储 |
| [`spill/`](spill/README.zh.md) | spill 能力系列:存储 seam、本地实现、工具结果 spill 策略 |
| [`todo/`](todo/README.zh.md) | 面向模型的 `todo_write` 工具 |
+6 -4
View File
@@ -32,18 +32,21 @@
],
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^"
},
"dependencies": {
"e2b": "2.29.1",
"@deepseek-ai/schemastery": "workspace:^"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-app-boot": "workspace:^",
"@deepseek-ai/dsh-bash-local": "workspace:^",
"@deepseek-ai/dsh-fs-e2b": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-loader-smoke": "workspace:^",
"@deepseek-ai/dsh-lsp": "workspace:^",
@@ -53,7 +56,6 @@
"@deepseek-ai/dsh-session-projection": "workspace:^",
"@deepseek-ai/dsh-subprocess-e2b": "workspace:^",
"@deepseek-ai/dsh-terminal": "workspace:^",
"@deepseek-ai/dsh-terminal-bash": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/dsh-terminal-bash": "workspace:^"
}
}
+9
View File
@@ -9,6 +9,7 @@ import { posix } from 'node:path'
import { Context, Service } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { FileType, Sandbox, SandboxNotFoundError } from 'e2b'
import { proxyUrlFor } from '@deepseek-ai/dsh-http-proxy'
export {
CommandExitError,
@@ -66,6 +67,9 @@ declare module '@deepseek-ai/cordis' {
}
}
/** The SDK's own default control-plane domain; `E2B_DOMAIN` overrides it there and here alike. */
const E2B_DEFAULT_DOMAIN = 'e2b.app'
/**
* Creates one lazily consumable E2B SDK handle and deletes the sandbox at
* timeout or disposal. Creation begins at plugin construction; adapters await
@@ -149,11 +153,16 @@ export class E2BRuntime extends Service {
}
private async open(): Promise<Sandbox> {
// The SDK builds its own undici dispatcher, so the global one never reaches it; it takes a proxy
// URL instead and reads no environment of its own. Its control-plane origin follows `E2B_DOMAIN`
// exactly as the SDK derives it, so a bypass entry naming that host is honored.
const proxy = proxyUrlFor(new URL(`https://api.${process.env.E2B_DOMAIN ?? E2B_DEFAULT_DOMAIN}`))
const sandbox = await Sandbox.create({
apiKey: this.config.apiKey,
timeoutMs: this.config.timeoutMs,
secure: true,
lifecycle: { onTimeout: 'kill' },
...proxy === undefined ? {} : { proxy },
})
try {
await sandbox.files.makeDir(this.cwd)
+46
View File
@@ -0,0 +1,46 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { Context } from '@deepseek-ai/cordis'
import E2bRuntime from '../src/index.ts'
describe('e2b egress', () => {
it('reaches the control plane through the proxy', async () => {
const observed = await observe(async () => {
const ctx = new Context()
const fiber = await ctx.plugin(E2bRuntime, { apiKey: `e2b_${'0'.repeat(40)}`, cwd: '/home/user', timeoutMs: 5_000 })
await ctx.e2b.getSandbox().catch(() => undefined)
await fiber.dispose()
})
expect(observed.join('|')).toContain('api.e2b.app:443')
})
})
+6 -1
View File
@@ -4,7 +4,9 @@
"rootDir": "src",
"outDir": "lib/types"
},
"include": ["src"],
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cosmokit"
@@ -20,6 +22,9 @@
},
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../net/http-proxy"
}
]
}
+4 -3
View File
@@ -48,16 +48,17 @@
"@deepseek-ai/schemastery": "workspace:^"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-attachment": "workspace:^",
"@deepseek-ai/dsh-authorization": "workspace:^",
"@deepseek-ai/dsh-credentials": "workspace:^",
"@deepseek-ai/dsh-fs": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-llm-deepseek": "workspace:^",
"@deepseek-ai/dsh-settings": "workspace:^",
"@deepseek-ai/dsh-timeout": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/dsh-timeout": "workspace:^"
}
}
@@ -0,0 +1,39 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { discoverModels } from '../src/discovery.ts'
describe('pi-ai discovery egress', () => {
it('goes through the proxy', async () => {
const observed = await observe(() => discoverModels({ baseURL: 'http://pi-probe.invalid/v1', api: 'openai-completions', apiKey: 'probe' }))
expect(observed.join('|')).toContain('pi-probe.invalid')
})
})
+3
View File
@@ -43,6 +43,9 @@
},
{
"path": "../../util/timeout"
},
{
"path": "../../net/http-proxy"
}
]
}
+3 -2
View File
@@ -47,8 +47,10 @@
"zod": "^4.4.3"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-attachment": "workspace:^",
"@deepseek-ai/dsh-attachment-local": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-scope": "workspace:^",
@@ -56,7 +58,6 @@
"@deepseek-ai/dsh-timeout": "workspace:^",
"@deepseek-ai/dsh-tools": "workspace:^",
"@modelcontextprotocol/server-everything": "^2026.7.4",
"@modelcontextprotocol/server-filesystem": "^2026.7.4",
"@deepseek-ai/cordis": "workspace:^"
"@modelcontextprotocol/server-filesystem": "^2026.7.4"
}
}
@@ -0,0 +1,40 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
describe('mcp streamable-http egress', () => {
it('goes through the proxy', async () => {
const t = new StreamableHTTPClientTransport(new URL('http://mcp-probe.invalid/mcp'))
const observed = await observe(() => t.send({ jsonrpc: '2.0', id: 1, method: 'ping' }))
expect(observed.join('|')).toContain('mcp-probe.invalid')
})
})
+6 -1
View File
@@ -4,7 +4,9 @@
"rootDir": "src",
"outDir": "lib/types"
},
"include": ["src"],
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cosmokit"
@@ -32,6 +34,9 @@
},
{
"path": "../../util/timeout"
},
{
"path": "../../net/http-proxy"
}
]
}
+6
View File
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/net/README.md
README.md: 21aa924afd94e3232b67a3648ca236fd8396b437
README.zh.md: 9dec251f6e5b546d6fc8308eb8c13754a65c562b
+44
View File
@@ -0,0 +1,44 @@
---
description: "Package map for the network group: process-wide outbound transport policy that applies to every request the harness makes."
kind: "package-group"
---
# net/ — outbound network transport
English | [中文](README.zh.md)
## Summary
The `net/` group owns transport-level decisions that apply to every outbound request the harness makes, regardless of which capability makes it. Today that is one decision — whether a request goes through an HTTP proxy — and one package that owns it. The group exists because such a decision belongs to no single capability: an LLM adapter, a web-search backend, an MCP transport, and a telemetry exporter all inherit it without knowing about each other, and putting it inside any of their groups would make the other three depend backwards. These packages are not capability seams: transport policy has one implementation and one answer per process, so there is nothing to swap.
## Table of Contents
- [Packages](#packages)
- [Related documentation](#related-documentation)
- [Dev Note](#dev-note)
-----
<a id="packages"></a>
## Packages
| Package | Role | ctx key |
|---|---|---|
| [`http-proxy/`](http-proxy/README.md) | Resolves one outbound proxy policy and installs it as the process's global dispatcher | none — installed by the launcher |
-----
<a id="related-documentation"></a>
## Related documentation
- [Network proxy guide](../../docs/user/guide/network-proxy.md) — the user-facing page: what to export, and why a browser is proxied when a terminal is not.
<a id="dev-note"></a>
## Dev Note
<details>
<summary>Working context for maintainers — click to expand</summary>
None.
</details>
+44
View File
@@ -0,0 +1,44 @@
---
description: "network 组的包地图:适用于 Harness 发出的每一个请求的进程级出站传输策略。"
kind: "package-group"
---
# net/ — 出站网络传输
[English](README.md) | 中文
## 概述
`net/` 组负责传输层面的决策——它们适用于 Harness 发出的每一个出站请求,与由哪个能力发起无关。目前这样的决策只有一个:请求是否经由 HTTP 代理;对应的包也只有一个。该组之所以存在,是因为这类决策不属于任何单一能力:LLM(大语言模型)适配器、web 搜索后端、MCP 传输与遥测导出器都在彼此无感的情况下继承它,而把它放进其中任何一组,都会让另外三组产生反向依赖。这些包不是能力接缝:传输策略每个进程只有一种实现、一个答案,没有可替换的对象。
## 目录
- [包](#packages)
- [相关文档](#related-documentation)
- [开发备注](#dev-note)
-----
<a id="packages"></a>
## 包
| 包 | 角色 | ctx key |
|---|---|---|
| [`http-proxy/`](http-proxy/README.zh.md) | 解析一份出站代理策略,并将其装为进程的全局 dispatcher | 无——由启动器安装 |
-----
<a id="related-documentation"></a>
## 相关文档
- [网络代理指南](../../docs/user/guide/network-proxy.zh.md)——面向用户的页面:需要导出什么,以及为什么浏览器走代理而终端不走。
<a id="dev-note"></a>
## 开发备注
<details>
<summary>面向维护者的工作上下文——点击展开</summary>
无。
</details>
+6
View File
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/net/http-proxy/README.md
README.md: 17c92824b70bb017b11a0635edbdbbad9e8f48ae
README.zh.md: b18db4e5a91edc499b33369c13f62b2fbba374ca
+117
View File
@@ -0,0 +1,117 @@
---
description: "Outbound HTTP proxy support for the harness: how one policy resolved from the launch environment reaches every request Node's fetch would otherwise send direct."
kind: "package-reference"
---
# @deepseek-ai/dsh-http-proxy
English | [中文](README.zh.md)
## Summary
Node's built-in `fetch` ignores `HTTP_PROXY` and `HTTPS_PROXY`, so a harness behind a proxy would connect directly no matter what the user exported — the LLM request, every web search, MCP over HTTP, telemetry, and the sandbox SDK alike. This package resolves one proxy policy from the launcher's environment snapshot and installs it as undici's global dispatcher, which is exactly what `fetch` resolves. Ordinary call sites therefore need no change and no import: they write `fetch()` and are proxied. The package also owns the three places a global dispatcher cannot reach — a caller that needs its own agent options, a worker thread with its own `globalThis`, and a spawned child Node — and gives each one a single supported way through.
## Table of Contents
- [Use this package](#use-this-package)
- [Understand the implementation](#understand-the-implementation)
- [Further Exploration](#further-exploration)
- [Model Experience](#model-experience)
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
- [Dev Note](#dev-note)
-----
<a id="use-this-package"></a>
## Use this package
Nothing to mount. The `dsh` launcher resolves and installs the policy for every profile before the first plugin loads, so a user who exports `HTTPS_PROXY` is proxied everywhere. Mount the plugin only when a composition wants the policy declared in `cordis.yml` instead of the environment.
### Writing a new outbound call
Plain `fetch()` is proxied, and so is any SDK that reaches `globalThis.fetch` — the MCP HTTP transport and the pi-ai provider stack both do. An SDK that builds its own transport does **not**, and two of the ones this repository ships turned out to: the OTLP exporter posts through `node:http`, and the E2B SDK constructs its own undici dispatcher. Assume nothing about an SDK; check it.
| You are writing | Use |
|---|---|
| A call needing its own agent options (pool size, timeouts, a DNS lookup) | `createDispatcher(url, options)` |
| An SDK that takes a `node:http` agent | `createNodeHttpAgent(protocol, options)` |
| An SDK that takes a proxy URL of its own | `proxyUrlFor(url)` |
| A worker thread, or a spawn whose environment you build yourself | merge `childProxyEnv()` into its environment |
Constructing `new Agent(...)` and passing it as `dispatcher` overrides the global one and silently bypasses the proxy. `verify-no-bare-dispatcher` rejects that outside this package; a line that must genuinely ignore the proxy says so with a `proxy-exempt:` comment.
That gate cannot see inside an SDK, so every outbound call site in the repository also carries an `egress.spec.ts` that drives its real code path through a fake proxy and asserts the proxy saw the request. A new call site adds one. It is the only thing that catches an SDK changing transports underneath us — which is exactly how the OTLP and E2B gaps were found.
### What the policy reads
`http_proxy`, `https_proxy`, `no_proxy`, and `all_proxy`, lowercase first and uppercase as the fallback, with a blank value treated as unset. `ALL_PROXY` backs both schemes, and HTTPS falls back to the HTTP proxy last — neither Node nor undici derives the first of these on its own. Values come from the launcher's snapshot, so a proxy declared in a project or `$DSH_HOME` `.env` layer works too; real environment variables still outrank both.
Loopback is always bypassed. The harness's own Web UI, Connection transport, and every local test server would otherwise route through the proxy and loop.
### Failures
A proxy value the package cannot use — a SOCKS or PAC URL, an unparseable string, an unsupported scheme — is reported and skipped, and the process connects directly. That variable may have been exported for other tools, so it must not stop the agent from starting. The same value supplied through this plugin's `Config` throws at load instead: that is the harness's own configuration surface, where a typo has to be loud.
-----
<a id="understand-the-implementation"></a>
## Understand the implementation
### Design philosophy
**One resolution, two readers.** `proxyForUrl()` and the installed dispatcher must never disagree about a URL, or `dsh-web-fetch-http` would pin a connection the dispatcher meant to tunnel. Installation therefore publishes the resolved policy into the proxy environment variables and constructs `EnvHttpProxyAgent` with no options, so the agent reads back exactly what was resolved rather than re-parsing the raw environment under slightly different rules.
**Publishing the policy is also how children inherit it.** The same write normalizes what every spawned process sees: the `ALL_PROXY` fallback becomes a concrete `HTTP_PROXY`, and the bypass list arrives with loopback already merged.
### Source map
| File | Holds |
|---|---|
| `src/policy.ts` | Resolution, bypass matching, and redaction. Imports no transport, so it stays loadable where undici is absent. |
| `src/install.ts` | The global dispatcher, the active-policy record, `createDispatcher`, and `childProxyEnv`. Imports undici dynamically. |
| `src/index.ts` | Re-exports both halves and the optional Cordis plugin. |
### Bypass matching
An entry matches an exact host, a `.suffix` or `*.suffix` domain, an optional `:port`, or `*` for everything. A bracketed or bare IPv6 literal matches either way — a bare `::1` is *not* read as host `:` port `1`, which is how undici's own matcher fails and why the resolved list carries both `::1` and `[::1]`. CIDR is not matched: an operating system's bypass list often carries `10.0.0.0/8`, which has to be rewritten as suffixes.
-----
<a id="further-exploration"></a>
## Further Exploration
- [Network proxy guide](../../../docs/user/guide/network-proxy.md) — what to export, and why a browser is proxied when a terminal is not.
- [`dsh-web-fetch-http`](../../web/web-fetch-http/README.md) — the one consumer whose safety rules change under a proxy.
-----
<a id="model-experience"></a>
## Model Experience
None, as transport policy only: it changes how bytes reach the network and registers no prompt, schema, or result text.
#### KV Cache effect
No direct invalidation: the package contributes no request tokens and never mutates a request prefix, so provider cache reuse is unaffected.
## Known Limitations and Deferred Work
<a id="known-limitations-and-deferred-work"></a>
These limits define when the package is a poor fit. They are current package constraints.
- **No SOCKS, PAC, or operating-system proxy detection** — only `http(s)://` proxy URLs from the environment or configuration. A macOS or Windows system-proxy setting is not read, so a user who only toggled it in a proxy application must still export the variables; a SOCKS URL is reported and skipped rather than silently ignored.
- **No custom certificate authority** — a TLS-intercepting corporate proxy needs `NODE_EXTRA_CA_CERTS` set on the process before launch, which this package neither sets nor validates.
- **A separate Node context matches bypass entries by Node's rules, not these** — a child process or worker thread honors the policy through Node's own `NODE_USE_ENV_PROXY` support, whose `NO_PROXY` parsing differs in separators and IPv4-range handling, and which exists only on Node 22.21+ and 24+. An older runtime keeps that context direct.
- **The `code-runtime` worker is deliberately excluded** — model-authored programs run with no ambient environment at all, and a proxy URL may carry credentials.
<a id="dev-note"></a>
### Dev Note
<details>
<summary>Working context for maintainers — click to expand</summary>
Reaching Node's built-in `fetch` from a userland undici relies on both writing the legacy `Symbol.for('undici.globalDispatcher.1')` slot. That is an implicit cross-version coupling, not a contract — see [corepack#834](https://github.com/nodejs/corepack/issues/834) for it breaking. `tests/install.spec.ts` asserts a real request reaches a loopback proxy, so a version bump that breaks the coupling fails there rather than in the field.
</details>
+117
View File
@@ -0,0 +1,117 @@
---
description: "Harness 的出站 HTTP 代理支持:从启动环境解析出的一份策略,如何覆盖到 Node fetch 本来会直连的每一个请求。"
kind: "package-reference"
---
# @deepseek-ai/dsh-http-proxy
[English](README.md) | 中文
## 概述
Node 内置的 `fetch` 会忽略 `HTTP_PROXY` 与 `HTTPS_PROXY`,因此在代理后面运行的 Harness 无论用户导出了什么都会直连——LLM(大语言模型)请求、每次 web 搜索、走 HTTP 的 MCP、遥测与沙箱 SDK 一概如此。本包从启动器的环境快照解析出一份代理策略,并把它装成 undici 的全局 dispatcher,而这正是 `fetch` 解析的对象。因此普通调用点无需改动、也无需引入本包:写 `fetch()` 就已经走代理。本包还负责全局 dispatcher 覆盖不到的三处——需要自定义 agent 选项的调用方、拥有独立 `globalThis` 的 worker 线程、以及派生出的子 Node 进程——并为每一处给出唯一受支持的走法。
## 目录
- [使用本包](#use-this-package)
- [理解实现](#understand-the-implementation)
- [进一步探索](#further-exploration)
- [模型体验](#model-experience)
- [已知限制与延期工作](#known-limitations-and-deferred-work)
- [开发备注](#dev-note)
-----
<a id="use-this-package"></a>
## 使用本包
无需挂载。`dsh` 启动器会在第一个插件加载之前,为每个 profile 解析并安装策略,因此导出了 `HTTPS_PROXY` 的用户在所有位置都会走代理。只有当某个组合希望把策略写在 `cordis.yml` 而非环境中时,才需要挂载本插件。
### 编写新的出站调用
普通 `fetch()` 已经走代理,任何最终落到 `globalThis.fetch` 的 SDK 也一样——MCP HTTP 传输与 pi-ai 提供方栈都是如此。但自建传输的 SDK **不会**,而本仓库随附的 SDK 里就有两个属于此类:OTLP 导出器通过 `node:http` 投递,E2B SDK 自建 undici dispatcher。不要对任何 SDK 想当然,去查。
| 你要写的东西 | 使用 |
|---|---|
| 需要自定义 agent 选项的调用(连接池、超时、DNS 查询) | `createDispatcher(url, options)` |
| 接受 `node:http` agent 的 SDK | `createNodeHttpAgent(protocol, options)` |
| 接受自有代理 URL 的 SDK | `proxyUrlFor(url)` |
| worker 线程,或由你自己构造环境的派生进程 | 把 `childProxyEnv()` 并入其环境 |
构造 `new Agent(...)` 再作为 `dispatcher` 传入会覆盖全局 dispatcher,从而静默绕开代理。`verify-no-bare-dispatcher` 会在本包之外拒绝该写法;确实必须忽略代理的行用 `proxy-exempt:` 注释说明理由。
该门禁看不进 SDK 内部,因此仓库中每一个出网点都另有一份 `egress.spec.ts`:它驱动该点的真实代码路径穿过一个假代理,并断言代理确实收到了请求。新增出网点就补一份。它是唯一能发现 SDK 在我们脚下更换传输的手段——OTLP 与 E2B 这两个漏洞正是这样被发现的。
### 策略读取哪些值
`http_proxy`、`https_proxy`、`no_proxy` 与 `all_proxy`,小写优先、大写兜底,空值视为未设置。`ALL_PROXY` 为两种协议兜底,HTTPS 最后回退到 HTTP 代理——其中第一条 Node 与 undici 都不会自行推导。取值来自启动器的快照,因此写在项目或 `$DSH_HOME` 的 `.env` 层中的代理同样生效;真实环境变量仍然高于两者。
loopback 始终被绕过。否则 Harness 自己的 Web UI、Connection 传输以及每一个本地测试服务器都会经由代理并形成回环。
### 失败处理
本包无法使用的代理值——SOCKS 或 PAC URL、无法解析的字符串、不受支持的协议——会被报告并跳过,进程转为直连。该变量可能是用户为其他工具导出的,不应因此阻止 agent 启动。同样的值若通过本插件的 `Config` 提供,则在加载期抛出:那是 Harness 自己的配置面,笔误必须立刻响。
-----
<a id="understand-the-implementation"></a>
## 理解实现
### 设计理念
**一次解析,两个读者。** `proxyForUrl()` 与已安装的 dispatcher 绝不能对同一个 URL 给出不同答案,否则 `dsh-web-fetch-http` 会把 dispatcher 本打算隧道转发的连接固定到某个地址上。因此安装时会把解析出的策略发布到代理环境变量中,并以无选项方式构造 `EnvHttpProxyAgent`,让该 agent 读回的正是解析结果,而不是按略有差异的规则重新解析原始环境。
**发布策略同时也是子进程继承的途径。** 同一次写入还规范化了每个派生进程看到的内容:`ALL_PROXY` 兜底落为具体的 `HTTP_PROXY`,绕过列表也已并入 loopback。
### 源码地图
| 文件 | 承载 |
|---|---|
| `src/policy.ts` | 解析、绕过匹配与脱敏。不引入任何传输实现,因此在没有 undici 的环境中仍可加载。 |
| `src/install.ts` | 全局 dispatcher、生效策略记录、`createDispatcher` 与 `childProxyEnv`。动态引入 undici。 |
| `src/index.ts` | 重导出两半,以及可选的 Cordis 插件。 |
### 绕过匹配
一个条目可匹配精确主机、`.suffix` 或 `*.suffix` 域名、可选的 `:port`,或用 `*` 匹配全部。带方括号与裸写的 IPv6 字面量都能匹配——裸写的 `::1` **不会**被读成主机 `:` 端口 `1`,而 undici 自带的匹配器正是这样出错的,这也是解析结果中同时携带 `::1` 与 `[::1]` 的原因。CIDR 不参与匹配:操作系统的绕过列表常含 `10.0.0.0/8`,必须改写成后缀形式。
-----
<a id="further-exploration"></a>
## 进一步探索
- [网络代理指南](../../../docs/user/guide/network-proxy.zh.md)——需要导出什么,以及为什么浏览器走代理而终端不走。
- [`dsh-web-fetch-http`](../../web/web-fetch-http/README.zh.md)——唯一一个安全规则会因代理而改变的消费方。
-----
<a id="model-experience"></a>
## 模型体验
无。本包只承担传输策略:它改变字节如何抵达网络,不注册任何提示词、schema 或结果文本。
#### KV Cache 影响
不会直接失效:本包不贡献任何请求 token,也从不改变请求前缀,因此提供方缓存复用不受影响。
## 已知限制与延期工作
<a id="known-limitations-and-deferred-work"></a>
这些限制界定了本包不适用的场景,属于当前的包级约束。
- **不支持 SOCKS、PAC 或操作系统代理探测**——只接受来自环境或配置的 `http(s)://` 代理 URL。不会读取 macOS 或 Windows 的系统代理设置,因此仅在代理软件里拨了开关的用户仍须导出环境变量;SOCKS URL 会被报告并跳过,而不是静默忽略。
- **不支持自定义证书颁发机构**——做 TLS 拦截的企业代理需要在启动前为进程设置 `NODE_EXTRA_CA_CERTS`,本包既不设置也不校验它。
- **独立的 Node 上下文按 Node 自己的规则匹配绕过条目,而非本包的规则**——子进程或 worker 线程通过 Node 自带的 `NODE_USE_ENV_PROXY` 支持来遵循策略,而它的 `NO_PROXY` 解析在分隔符与 IPv4 区间处理上与此处不同,且仅存在于 Node 22.21+ 与 24+。更旧的运行时会让该上下文保持直连。
- **`code-runtime` worker 被刻意排除在外**——模型编写的程序运行时完全没有环境变量,而代理 URL 可能携带凭据。
<a id="dev-note"></a>
### 开发备注
<details>
<summary>面向维护者的工作上下文——点击展开</summary>
userland undici 能触及 Node 内置的 `fetch`,依赖的是两者都会写入 legacy 的 `Symbol.for('undici.globalDispatcher.1')` 槽位。那是跨版本的隐式耦合,不是约定——参见 [corepack#834](https://github.com/nodejs/corepack/issues/834) 中它失效的实例。`tests/install.spec.ts` 断言真实请求会抵达一个 loopback 代理,因此破坏该耦合的版本升级会在那里失败,而不是流到线上。
</details>
+48
View File
@@ -0,0 +1,48 @@
{
"name": "@deepseek-ai/dsh-http-proxy",
"description": "Process-wide outbound HTTP proxy policy for DeepSeek Harness: resolve it from the launch environment and install it as undici's global dispatcher",
"version": "0.1.1-rc.2",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
"directory": "packages/net/http-proxy"
},
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./invariant": {
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/types/**/*.d.ts"
],
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^"
},
"dependencies": {
"@deepseek-ai/schemastery": "workspace:^",
"undici": "^8.10.0"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^"
}
}
+86
View File
@@ -0,0 +1,86 @@
/**
* Outbound HTTP proxy support for DeepSeek Harness.
*
* Node's built-in `fetch` ignores `HTTP_PROXY` and friends, so every harness request would connect
* directly no matter what the user exported. This package resolves one policy from the launch
* environment and installs it as undici's global dispatcher, which is what `fetch` resolves — so
* LLM adapters, web search, MCP over HTTP, telemetry, and sandbox SDKs are all covered without
* touching their code.
*
* The launcher installs the environment-derived policy for every profile. This plugin exists for a
* composition that wants the policy in `cordis.yml` instead: it replaces the launcher's dispatcher
* for as long as it is mounted, and restores it on disposal. It is not part of any shipped bundle,
* so the default path installs exactly once.
* @module @deepseek-ai/dsh-http-proxy
*/
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
import { installGlobalProxy } from './install.ts'
import { describeProxyPolicy, resolveProxyPolicy, type ProxyConfig } from './policy.ts'
export {
bypassesProxy,
describeProxyPolicy,
proxyForUrl,
resolveProxyPolicy,
DIRECT_POLICY,
LOOPBACK_NO_PROXY,
type ProxyConfig,
type ProxyDiagnostic,
type ProxyPolicy,
type ProxyResolution,
} from './policy.ts'
export {
childProxyEnv,
createDispatcher,
createNodeHttpAgent,
currentProxyPolicy,
installGlobalProxy,
proxyUrlFor,
} from './install.ts'
/** Cordis plugin name. */
export const name = 'http-proxy'
/** Composition-declared proxy settings; every field is optional and the environment outranks them. */
export interface Config extends ProxyConfig {}
/** Schema for {@link Config}; a malformed proxy URL here fails the load rather than warning. */
export const Config: z<Config> = z.object({
mode: z.union([z.const('env'), z.const('custom'), z.const('off')]).description(
'Whether to resolve from the environment (`env`, the default), do the same for a composition that supplies its own proxy (`custom`), or keep this process direct (`off`).',
),
httpProxy: z.string().description('Proxy for `http:` origins when the environment supplies none.'),
httpsProxy: z.string().description('Proxy for `https:` origins when the environment supplies none.'),
noProxy: z.string().description('Bypass list when the environment supplies none; loopback is always added.'),
})
/**
* Install the composition's proxy policy for as long as this plugin is mounted.
*
* A value this plugin's own `Config` supplied and that failed validation throws: it is the harness's
* configuration surface, where a typo must be loud. A rejected *environment* value only warns,
* because the same variable may have been exported for other tools and must not stop the agent from
* starting.
*
* Installing IS this plugin's lifetime, so the disposer is returned as the startup effect rather than
* registered through `ctx.effect()`: a caller awaiting the mount must observe an installed dispatcher,
* which a separately-scheduled async effect would not guarantee.
*
* @param ctx - the mounting context, read for the launch environment snapshot and the logger.
* @param config - composition-declared settings.
* @returns the disposer restoring the previous dispatcher, policy, and environment.
*/
export async function apply(ctx: Context, config: Config): Promise<() => Promise<void>> {
const { policy, diagnostics } = resolveProxyPolicy(launchEnvironmentOf(ctx), config)
const fatal = diagnostics.filter(diagnostic => diagnostic.origin.startsWith('config.'))
if (fatal.length > 0) {
throw new Error(`http-proxy: ${fatal.map(diagnostic => diagnostic.message).join('; ')}`)
}
for (const diagnostic of diagnostics) ctx.logger.warn('http-proxy: %s', diagnostic.message)
if (policy.source !== 'none') ctx.logger.debug('http-proxy: %s', describeProxyPolicy(policy))
return await installGlobalProxy(policy)
}
+185
View File
@@ -0,0 +1,185 @@
/**
* Proxy installation: the transport half of this package. It owns undici's global dispatcher, the
* process-wide record of which policy is active, and the dispatcher factory every other package uses
* instead of constructing a bare agent.
*
* `undici` is imported dynamically so the pure {@link ProxyPolicy} half stays loadable where no Node
* transport exists, matching how `dsh-web-fetch-http` defers its own transport import.
* @module @deepseek-ai/dsh-http-proxy/install
*/
import type { Agent, Dispatcher } from 'undici'
import { DIRECT_POLICY, proxyForUrl, type ProxyPolicy } from './policy.ts'
/**
* The environment names each policy field owns, lowercase first. Both casings are written together:
* undici reads the lowercase name first, so leaving a stale uppercase value behind would let it
* shadow the resolved one on Windows, where the two names are the same variable.
*/
const POLICY_ENV_NAMES = {
httpProxy: ['http_proxy', 'HTTP_PROXY'],
httpsProxy: ['https_proxy', 'HTTPS_PROXY'],
noProxy: ['no_proxy', 'NO_PROXY'],
} as const
/** The active policy, or `undefined` until one is installed. Process-wide, like the dispatcher it tracks. */
let active: ProxyPolicy | undefined
/**
* The policy governing this process's outbound requests.
*
* @returns the installed policy, or `undefined` when {@link installGlobalProxy} has not run. A caller
* that only needs to route a URL can treat `undefined` as {@link DIRECT_POLICY}.
*/
export function currentProxyPolicy(): ProxyPolicy | undefined {
return active
}
/**
* Publish a policy through the proxy environment variables so both undici and every spawned child
* observe the one resolved answer — including the `ALL_PROXY` fallback and the merged loopback
* bypass, neither of which they would derive on their own.
*
* @param policy - the policy to publish.
* @returns a function restoring every name this call changed.
*/
function applyPolicyEnv(policy: ProxyPolicy): () => void {
const previous = new Map<string, string | undefined>()
for (const [field, names] of Object.entries(POLICY_ENV_NAMES)) {
const value = policy[field as keyof typeof POLICY_ENV_NAMES]
for (const name of names) {
previous.set(name, process.env[name])
if (value === undefined || value === '') Reflect.deleteProperty(process.env, name)
else process.env[name] = value
}
}
return () => {
for (const [name, value] of previous) {
if (value === undefined) Reflect.deleteProperty(process.env, name)
else process.env[name] = value
}
}
}
/**
* Route this process's outbound HTTP through `policy`.
*
* Installing replaces undici's global dispatcher, which is what Node's built-in `fetch` resolves, so
* every caller that issues a plain `fetch()` is covered without knowing this package exists. A policy
* that proxies nothing installs no dispatcher and leaves the environment untouched.
*
* Worker threads do not inherit the global dispatcher; each one calls this with the policy its host
* passed through `workerData`.
*
* @param policy - the resolved policy to install.
* @returns a disposer restoring the previous dispatcher, policy, and environment, then closing the agent.
*/
export async function installGlobalProxy(policy: ProxyPolicy): Promise<() => Promise<void>> {
const previousPolicy = active
if (policy.source === 'none') {
active = policy
return () => {
active = previousPolicy
return Promise.resolve()
}
}
const restoreEnv = applyPolicyEnv(policy)
const { EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } = await import('undici')
const previousDispatcher = getGlobalDispatcher()
// Constructed with no options on purpose: it reads the names applyPolicyEnv just wrote, so the
// agent and `proxyForUrl` answer from the same values instead of each parsing the raw environment.
const agent = new EnvHttpProxyAgent()
setGlobalDispatcher(agent)
active = policy
return async () => {
setGlobalDispatcher(previousDispatcher)
active = previousPolicy
restoreEnv()
await agent.close()
}
}
/**
* Build a dispatcher for one request URL that honors the active policy.
*
* Use this wherever a call site needs its own agent options — connection limits, timeouts, a custom
* DNS lookup. Constructing `new Agent(...)` directly and passing it as `dispatcher` silently bypasses
* the global one and therefore the proxy, which is the defect this function exists to prevent.
* `verify-no-bare-dispatcher` enforces that outside this package.
*
* @param url - the request URL, which decides whether the policy proxies or bypasses it.
* @param options - agent options; applied to whichever agent the policy selects.
* @returns a dispatcher the caller owns and must close once the response body is consumed.
*/
export async function createDispatcher(url: URL, options: Agent.Options = {}): Promise<Dispatcher> {
const undici = await import('undici')
const proxy = proxyForUrl(active ?? DIRECT_POLICY, url)
if (proxy === undefined) return new undici.Agent(options)
return new undici.ProxyAgent({ ...options, uri: proxy })
}
/**
* Build a `node:http` or `node:https` Agent that honors the active policy.
*
* The global dispatcher reaches undici, and therefore `fetch`, but not `node:http`. An SDK that
* issues requests through the core modules — the OTLP exporter is the one this repository ships —
* accepts an agent instead, and this is the agent to give it.
*
* Node's own `proxyEnv` option does the routing, reading the names {@link installGlobalProxy}
* published. It reaches Node 22.21+ and 24.5+; an older runtime ignores the unknown option and
* connects directly, the same seam a spawned child Node has.
*
* @param protocol - the target's protocol, `https:` selecting the TLS agent.
* @param options - agent options merged under the proxy routing.
* @returns an agent the caller passes to the SDK that needs one.
*/
export async function createNodeHttpAgent(
protocol: string,
options: Readonly<Record<string, unknown>> = {},
): Promise<import('node:http').Agent> {
const core = protocol === 'https:' ? await import('node:https') : await import('node:http')
const proxied = active !== undefined && active.source !== 'none'
// `proxyEnv` postdates the @types/node this workspace pins, so the option is applied through a
// widened record rather than the typed constructor overload.
const agentOptions = { ...options, ...proxied ? { proxyEnv: process.env } : {} }
return new core.Agent(agentOptions as ConstructorParameters<typeof core.Agent>[0])
}
/**
* The proxy this URL is reached through, for an SDK that takes a proxy URL of its own rather than a
* dispatcher or an agent. `undefined` means the SDK should connect directly.
*
* @param url - the endpoint the SDK will call.
* @returns the proxy URL to hand the SDK, or `undefined` for a direct connection.
*/
export function proxyUrlFor(url: URL): string | undefined {
return proxyForUrl(active ?? DIRECT_POLICY, url)
}
/**
* The proxy environment a separate Node execution context needs: the resolved policy plus the flag
* that makes Node's built-in HTTP clients honor it.
*
* This covers both shapes DSH spawns. A child process inherits the parent environment, so the proxy
* names merely restate what {@link installGlobalProxy} already published and the flag is what it
* gains. A worker thread is given an explicit, near-empty environment instead, so it needs the names
* as well — and worker threads do not inherit the global dispatcher, which is why they are handled
* here rather than left to the parent's installation.
*
* The flag reaches only Node 22.21+ and 24+; an older runtime keeps that context direct. Such a
* context also matches bypass entries with Node's own `NO_PROXY` rules, which differ from this
* package's in their separators and IPv4-range support. Non-Node children (curl, git, pnpm) ignore
* the flag and read the variables themselves.
*
* @returns names to merge into the child or worker environment, or an empty object when no proxy is active.
*/
export function childProxyEnv(): Record<string, string> {
if (active === undefined || active.source === 'none') return {}
const env: Record<string, string> = { NODE_USE_ENV_PROXY: '1' }
for (const [field, names] of Object.entries(POLICY_ENV_NAMES)) {
const value = active[field as keyof typeof POLICY_ENV_NAMES]
if (value === undefined || value === '') continue
for (const name of names) env[name] = value
}
return env
}
+31
View File
@@ -0,0 +1,31 @@
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-http-proxy`.
* @module @deepseek-ai/dsh-http-proxy/invariant
*/
/* jscpd:ignore-start */
import type { Context } from '@deepseek-ai/cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-http-proxy'
/** Cordis companion plugin name. */
export const name = 'http-proxy-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/**
* No runtime invariant: this package owns no event stream, and its one piece of mutable state — the
* active policy — is asserted against the dispatcher it installs by unit tests that dispose the
* registration and observe a real loopback proxy.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */
+302
View File
@@ -0,0 +1,302 @@
/**
* Proxy policy resolution: the pure, transport-free half of this package. It turns the launch
* environment plus optional configuration into one {@link ProxyPolicy}, and answers which proxy
* (if any) a given URL goes through.
*
* Nothing here imports `undici`, so the module stays loadable in the browser-worker runtime that
* evaluates `dsh-web-fetch-http` without a Node transport.
* @module @deepseek-ai/dsh-http-proxy/policy
*/
import type { LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
/**
* Loopback entries merged into every policy's `noProxy`. A proxy that also serves the harness's own
* loopback traffic turns the Web UI, the Connection transport, and every local test server into a
* routing loop, so the bypass is not optional.
*
* `::1` and `[::1]` are both listed because the resolved string is also handed to undici, whose
* matcher reads a bare `::1` as host `:` port `1` and therefore never bypasses it.
*/
export const LOOPBACK_NO_PROXY: readonly string[] = ['localhost', '127.0.0.1', '::1', '[::1]']
/** Proxy URL schemes this package routes through. Everything else is reported, never silently dropped. */
const SUPPORTED_PROTOCOLS = new Set(['http:', 'https:'])
/** Schemes recognised well enough to name in a diagnostic instead of calling them malformed. */
const SOCKS_PROTOCOLS = new Set(['socks:', 'socks4:', 'socks4a:', 'socks5:', 'socks5h:'])
/**
* One resolved outbound proxy policy. Plain data with no methods: worker threads receive it through
* `workerData`'s structured clone, so both sides run the identical policy rather than each re-reading
* an environment they may not share.
*/
export interface ProxyPolicy {
/** Proxy for `http:` origins, or absent for a direct connection. Always a validated `http(s):` URL. */
readonly httpProxy?: string
/** Proxy for `https:` origins, or absent for a direct connection. Always a validated `http(s):` URL. */
readonly httpsProxy?: string
/** The bypass list, already merged with {@link LOOPBACK_NO_PROXY}. Empty when nothing is bypassed. */
readonly noProxy: string
/** Which layer supplied the winning proxy URL; `env` when either field came from the environment. */
readonly source: 'env' | 'config' | 'none'
}
/** A policy that proxies nothing. Callers that have not installed a policy resolve URLs against this. */
export const DIRECT_POLICY: ProxyPolicy = { noProxy: '', source: 'none' }
/** Why one candidate proxy value was not used. Callers decide whether this warns or fails the load. */
export interface ProxyDiagnostic {
/** `socks` for a SOCKS or PAC URL this package cannot route; `invalid` for anything unparseable. */
readonly kind: 'socks' | 'invalid'
/** Where the rejected value came from: an environment variable name, or `config.<field>`. */
readonly origin: string
/** Operator-facing sentence naming the rejection and the way forward. Carries no credential. */
readonly message: string
}
/**
* Proxy settings a composition may declare in `cordis.yml`. Real environment variables win over every
* field here except `mode`, which governs whether the environment is consulted at all.
*/
export interface ProxyConfig {
/**
* `env` (default) resolves from the environment and lets the fields below fill the gaps; `custom`
* does the same but is the honest label for a composition that supplies its own proxy; `off`
* ignores every source and keeps the harness's own requests direct.
*
* `off` governs requests this process issues. It does not strip proxy variables from the
* environment child tools inherit, because those belong to the user, not to the harness.
*/
mode?: 'env' | 'custom' | 'off'
/** Proxy for `http:` origins when the environment supplies none. */
httpProxy?: string
/** Proxy for `https:` origins when the environment supplies none. */
httpsProxy?: string
/** Bypass list when the environment supplies none. {@link LOOPBACK_NO_PROXY} is merged in regardless. */
noProxy?: string
}
/** A resolved policy plus every candidate value that was rejected on the way to it. */
export interface ProxyResolution {
/** The policy to install. Never carries a rejected value. */
readonly policy: ProxyPolicy
/** Rejections, in the order the candidates were considered. Empty on a clean resolution. */
readonly diagnostics: readonly ProxyDiagnostic[]
}
/**
* Read one environment name in undici's precedence order — lowercase first, uppercase as the
* fallback — treating a blank value as unset. Blank matters: undici's own `??` chain lets an empty
* lowercase name shadow a populated uppercase one.
*
* @param env - the launch environment snapshot to read.
* @param lower - the lowercase variable name.
* @returns the trimmed value and the name that supplied it, or `undefined` when neither is set.
*/
function readEnv(
env: LaunchEnvironmentSnapshot,
lower: string,
): { value: string; name: string } | undefined {
for (const name of [lower, lower.toUpperCase()]) {
const value = env.get(name)?.value.trim()
if (value !== undefined && value !== '') return { value, name }
}
return undefined
}
/**
* Validate one candidate proxy URL.
*
* @param candidate - the raw value and the origin to name in a diagnostic.
* @param diagnostics - collector the rejection is appended to.
* @returns the candidate when it is a usable `http(s):` proxy URL, otherwise `undefined`.
*/
function acceptProxyUrl(
candidate: { value: string; name: string } | undefined,
diagnostics: ProxyDiagnostic[],
): string | undefined {
if (candidate === undefined) return undefined
const parsed = URL.parse(candidate.value)
if (parsed === null) {
diagnostics.push({
kind: 'invalid',
origin: candidate.name,
message: `${candidate.name} is not a valid URL; connecting directly`,
})
return undefined
}
if (SOCKS_PROTOCOLS.has(parsed.protocol)) {
diagnostics.push({
kind: 'socks',
origin: candidate.name,
message: `${candidate.name} names a SOCKS proxy, which is not supported; set an http:// or https:// proxy URL instead`,
})
return undefined
}
if (!SUPPORTED_PROTOCOLS.has(parsed.protocol)) {
diagnostics.push({
kind: 'invalid',
origin: candidate.name,
message: `${candidate.name} uses the unsupported ${parsed.protocol}// scheme; set an http:// or https:// proxy URL instead`,
})
return undefined
}
return candidate.value
}
/**
* Merge {@link LOOPBACK_NO_PROXY} into a bypass list, preserving the caller's entries and order.
* A list of `*` already bypasses everything and is returned unchanged.
*
* @param noProxy - the bypass list as the environment or configuration supplied it.
* @returns the effective bypass list.
*/
function withLoopback(noProxy: string | undefined): string {
const entries = (noProxy ?? '').split(/[,\s]+/).map(entry => entry.trim()).filter(entry => entry !== '')
if (entries.includes('*')) return '*'
const present = new Set(entries.map(entry => entry.toLowerCase()))
return [...entries, ...LOOPBACK_NO_PROXY.filter(entry => !present.has(entry))].join(',')
}
/**
* Split one bypass entry into host and optional port.
*
* A bare IPv6 literal carries several colons and no port, so only a single-colon entry splits;
* a bracketed literal takes its port from after the bracket. Getting this wrong is how undici
* turns `::1` into host `:` port `1`.
*
* @param entry - one already-trimmed bypass entry.
* @returns the entry's host and, when it carries one, its port.
*/
function splitHostPort(entry: string): { host: string; port?: string } {
if (entry.startsWith('[')) {
const close = entry.indexOf(']')
if (close !== -1) {
const rest = entry.slice(close + 1)
const host = entry.slice(1, close)
return rest.startsWith(':') ? { host, port: rest.slice(1) } : { host }
}
}
const colon = entry.indexOf(':')
if (colon !== -1 && entry.indexOf(':', colon + 1) === -1) {
return { host: entry.slice(0, colon), port: entry.slice(colon + 1) }
}
return { host: entry }
}
/**
* Decide whether a bypass list exempts one URL. Entries match an exact host, a `.suffix` or
* `*.suffix` domain, an optional `:port`, or `*` for everything. CIDR notation is not matched —
* an operating system's bypass list often carries `10.0.0.0/8`, which must be rewritten as suffixes.
*
* @param noProxy - the effective bypass list.
* @param url - the request URL.
* @returns true when the URL must bypass the proxy.
*/
export function bypassesProxy(noProxy: string, url: URL): boolean {
// `URL.hostname` keeps the brackets around an IPv6 literal, while a bypass entry may be written
// either way, so both sides are unbracketed before they are compared.
const host = url.hostname.replace(/^\[|\]$/g, '').replace(/\.$/, '').toLowerCase()
const port = url.port !== '' ? url.port : url.protocol === 'https:' ? '443' : '80'
for (const raw of noProxy.split(/[,\s]+/)) {
const entry = raw.trim().toLowerCase()
if (entry === '') continue
if (entry === '*') return true
const split = splitHostPort(entry)
if (split.port !== undefined && split.port !== port) continue
const candidate = split.host.replace(/^\*?\./, '').replace(/\.$/, '')
if (candidate === '') continue
if (host === candidate || host.endsWith(`.${candidate}`)) return true
}
return false
}
/**
* Resolve the outbound proxy policy for this process.
*
* Precedence is environment first, configuration second: a value the user exported wins over one a
* composition declares, and `ALL_PROXY` backs both schemes. HTTPS falls back to the HTTP proxy last,
* matching undici, so this function and the installed dispatcher never disagree about one URL.
*
* @param env - the launch environment snapshot, whose own layering already prefers real variables over `.env` files.
* @param config - optional composition-declared settings.
* @returns the policy to install plus every rejected candidate.
*/
export function resolveProxyPolicy(
env: LaunchEnvironmentSnapshot,
config: ProxyConfig = {},
): ProxyResolution {
const diagnostics: ProxyDiagnostic[] = []
if (config.mode === 'off') return { policy: DIRECT_POLICY, diagnostics }
const all = acceptProxyUrl(readEnv(env, 'all_proxy'), diagnostics)
const httpFromEnv = acceptProxyUrl(readEnv(env, 'http_proxy'), diagnostics) ?? all
const httpsFromEnv = acceptProxyUrl(readEnv(env, 'https_proxy'), diagnostics) ?? all
const httpFromConfig = acceptProxyUrl(
config.httpProxy === undefined ? undefined : { value: config.httpProxy, name: 'config.httpProxy' },
diagnostics,
)
const httpsFromConfig = acceptProxyUrl(
config.httpsProxy === undefined ? undefined : { value: config.httpsProxy, name: 'config.httpsProxy' },
diagnostics,
)
const httpProxy = httpFromEnv ?? httpFromConfig
// HTTPS falls back to the HTTP proxy, so an undefined result here means no layer supplied any
// proxy at all — one check covers both schemes.
const httpsProxy = httpsFromEnv ?? httpsFromConfig ?? httpProxy
if (httpsProxy === undefined) return { policy: DIRECT_POLICY, diagnostics }
const noProxy = withLoopback(readEnv(env, 'no_proxy')?.value ?? config.noProxy)
const source = httpFromEnv !== undefined || httpsFromEnv !== undefined ? 'env' : 'config'
return {
policy: {
...httpProxy === undefined ? {} : { httpProxy },
httpsProxy,
noProxy,
source,
},
diagnostics,
}
}
/**
* Resolve which proxy one URL goes through under a policy.
*
* This is the single answer both the installed dispatcher and `dsh-web-fetch-http` consult, so a URL
* can never be pinned to a resolved address by one and tunnelled by the other.
*
* @param policy - the active policy.
* @param url - the request URL.
* @returns the proxy URL to tunnel through, or `undefined` for a direct connection.
*/
export function proxyForUrl(policy: ProxyPolicy, url: URL): string | undefined {
const proxy = url.protocol === 'https:' ? policy.httpsProxy : url.protocol === 'http:' ? policy.httpProxy : undefined
if (proxy === undefined) return undefined
return bypassesProxy(policy.noProxy, url) ? undefined : proxy
}
/**
* Render a policy for an operator, with any proxy password replaced. The username survives because it
* identifies the account without granting it, which is what makes the line useful in a bug report.
*
* @param policy - a policy whose URLs {@link resolveProxyPolicy} already validated.
* @returns one line naming the effective proxies and bypass list.
*/
export function describeProxyPolicy(policy: ProxyPolicy): string {
if (policy.source === 'none') return 'no proxy (direct)'
const redact = (value: string): string => {
const url = new URL(value)
if (url.password !== '') url.password = '***'
return url.toString()
}
const parts = [
`http=${policy.httpProxy === undefined ? 'direct' : redact(policy.httpProxy)}`,
`https=${policy.httpsProxy === undefined ? 'direct' : redact(policy.httpsProxy)}`,
`no_proxy=${policy.noProxy}`,
`from=${policy.source}`,
]
return parts.join(' ')
}
@@ -0,0 +1,276 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterEach, beforeAll, afterAll, describe, expect, it } from 'vitest'
import { getGlobalDispatcher } from 'undici'
import http from 'node:http'
import https from 'node:https'
import {
childProxyEnv,
createDispatcher,
createNodeHttpAgent,
currentProxyPolicy,
installGlobalProxy,
proxyUrlFor,
} from '../src/install.ts'
import { DIRECT_POLICY, type ProxyPolicy } from '../src/policy.ts'
/** Absolute-form request targets the fake proxy received; a populated entry proves a request was tunnelled. */
let proxied: string[] = []
let proxy: Server
let origin: Server
let proxyUrl: string
let originUrl: string
function listen(server: Server): Promise<AddressInfo> {
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => { resolve(server.address() as AddressInfo) })
})
}
function close(server: Server): Promise<void> {
return new Promise((resolve) => { server.close(() => { resolve() }) })
}
beforeAll(async () => {
proxy = createServer((request, response) => {
proxied.push(`${request.method} ${request.url}`)
response.writeHead(200, { 'content-type': 'text/plain' })
response.end('VIA-PROXY')
})
origin = createServer((_request, response) => { response.end('DIRECT') })
const [proxyAddress, originAddress] = await Promise.all([listen(proxy), listen(origin)])
proxyUrl = `http://127.0.0.1:${String(proxyAddress.port)}`
originUrl = `http://127.0.0.1:${String(originAddress.port)}/probe`
})
afterAll(async () => {
await Promise.all([close(proxy), close(origin)])
})
afterEach(() => {
proxied = []
})
/** A policy proxying everything, since the resolved default always bypasses the loopback these tests use. */
function proxyAll(noProxy = ''): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy, source: 'env' }
}
describe('installGlobalProxy', () => {
it('routes the built-in global fetch through the proxy', async () => {
const dispose = await installGlobalProxy(proxyAll())
try {
await expect((await fetch(originUrl)).text()).resolves.toBe('VIA-PROXY')
expect(proxied).toEqual([`GET ${originUrl}`])
} finally {
await dispose()
}
})
it('connects directly when the bypass list covers the target', async () => {
const dispose = await installGlobalProxy(proxyAll('127.0.0.1'))
try {
await expect((await fetch(originUrl)).text()).resolves.toBe('DIRECT')
expect(proxied).toEqual([])
} finally {
await dispose()
}
})
it('publishes the policy through the proxy environment in both casings', async () => {
const dispose = await installGlobalProxy(proxyAll('example.com'))
try {
expect(process.env.http_proxy).toBe(proxyUrl)
expect(process.env.HTTP_PROXY).toBe(proxyUrl)
expect(process.env.no_proxy).toBe('example.com')
expect(process.env.NO_PROXY).toBe('example.com')
} finally {
await dispose()
}
})
it('removes an environment name the policy leaves unset', async () => {
process.env.HTTPS_PROXY = 'http://stale.example'
const dispose = await installGlobalProxy({ httpProxy: proxyUrl, noProxy: '', source: 'env' })
try {
expect(process.env.HTTPS_PROXY).toBeUndefined()
} finally {
await dispose()
expect(process.env.HTTPS_PROXY).toBe('http://stale.example')
delete process.env.HTTPS_PROXY
}
})
it('restores the dispatcher, the policy, and the environment on disposal', async () => {
const before = getGlobalDispatcher()
const beforeEnv = process.env.HTTP_PROXY
const beforePolicy = currentProxyPolicy()
const dispose = await installGlobalProxy(proxyAll())
expect(getGlobalDispatcher()).not.toBe(before)
expect(currentProxyPolicy()).not.toBe(beforePolicy)
await dispose()
expect(getGlobalDispatcher()).toBe(before)
expect(currentProxyPolicy()).toBe(beforePolicy)
expect(process.env.HTTP_PROXY).toBe(beforeEnv)
await expect((await fetch(originUrl)).text()).resolves.toBe('DIRECT')
})
it('installs no dispatcher and touches no environment for a direct policy', async () => {
const before = getGlobalDispatcher()
process.env.HTTP_PROXY = 'http://untouched.example'
const dispose = await installGlobalProxy(DIRECT_POLICY)
try {
expect(getGlobalDispatcher()).toBe(before)
expect(process.env.HTTP_PROXY).toBe('http://untouched.example')
expect(currentProxyPolicy()).toBe(DIRECT_POLICY)
} finally {
await dispose()
delete process.env.HTTP_PROXY
}
expect(currentProxyPolicy()).toBeUndefined()
})
})
describe('createDispatcher', () => {
it('tunnels through the proxy when the policy covers the URL', async () => {
const dispose = await installGlobalProxy(proxyAll())
const dispatcher = await createDispatcher(new URL(originUrl))
try {
const undici = await import('undici')
const response = await undici.fetch(originUrl, { dispatcher })
await expect(response.text()).resolves.toBe('VIA-PROXY')
} finally {
await dispatcher.close()
await dispose()
}
})
it('connects directly when the policy bypasses the URL', async () => {
const dispose = await installGlobalProxy(proxyAll('127.0.0.1'))
const dispatcher = await createDispatcher(new URL(originUrl))
try {
const undici = await import('undici')
const response = await undici.fetch(originUrl, { dispatcher })
await expect(response.text()).resolves.toBe('DIRECT')
expect(proxied).toEqual([])
} finally {
await dispatcher.close()
await dispose()
}
})
it('connects directly when no policy is installed', async () => {
const dispatcher = await createDispatcher(new URL(originUrl))
try {
const undici = await import('undici')
await expect((await undici.fetch(originUrl, { dispatcher })).text()).resolves.toBe('DIRECT')
} finally {
await dispatcher.close()
}
})
})
describe('childProxyEnv', () => {
it('is empty when no policy is installed', () => {
expect(childProxyEnv()).toEqual({})
})
it('is empty under a direct policy, so a child sees no flag it cannot use', async () => {
const dispose = await installGlobalProxy(DIRECT_POLICY)
try {
expect(childProxyEnv()).toEqual({})
} finally {
await dispose()
}
})
it('carries the resolved policy and the flag that makes a child Node honor it', async () => {
const dispose = await installGlobalProxy(proxyAll('example.com'))
try {
expect(childProxyEnv()).toEqual({
NODE_USE_ENV_PROXY: '1',
http_proxy: proxyUrl,
HTTP_PROXY: proxyUrl,
https_proxy: proxyUrl,
HTTPS_PROXY: proxyUrl,
no_proxy: 'example.com',
NO_PROXY: 'example.com',
})
} finally {
await dispose()
}
})
it('omits a scheme the policy leaves direct, so a worker inherits no stale name', async () => {
const dispose = await installGlobalProxy({ httpProxy: proxyUrl, noProxy: '', source: 'env' })
try {
expect(childProxyEnv()).not.toHaveProperty('HTTPS_PROXY')
expect(childProxyEnv()).not.toHaveProperty('NO_PROXY')
} finally {
await dispose()
}
})
})
describe('createNodeHttpAgent', () => {
/** Drive a real `node:http` request, which the global dispatcher never reaches. */
function get(target: string, agent: http.Agent): Promise<string> {
return new Promise((resolve) => {
http.get(target, { agent }, (response) => {
let body = ''
response.on('data', (chunk: Buffer) => { body += chunk.toString() })
response.on('end', () => { resolve(body) })
}).on('error', (error: NodeJS.ErrnoException) => { resolve(`ERR ${error.code ?? ''}`) })
})
}
it('routes a node:http request through the proxy', async () => {
const dispose = await installGlobalProxy(proxyAll())
const agent = await createNodeHttpAgent('http:')
try {
await expect(get(originUrl, agent)).resolves.toBe('VIA-PROXY')
} finally {
agent.destroy()
await dispose()
}
})
it('connects directly when no policy is installed', async () => {
const agent = await createNodeHttpAgent('http:', { keepAlive: false })
try {
await expect(get(originUrl, agent)).resolves.toBe('DIRECT')
} finally {
agent.destroy()
}
})
it('selects the TLS agent for an https target', async () => {
const agent = await createNodeHttpAgent('https:')
try {
expect(agent).toBeInstanceOf(https.Agent)
} finally {
agent.destroy()
}
})
})
describe('proxyUrlFor', () => {
it('names the proxy an SDK with its own transport must use', async () => {
const dispose = await installGlobalProxy(proxyAll())
try {
expect(proxyUrlFor(new URL('https://api.example.com/v1'))).toBe(proxyUrl)
} finally {
await dispose()
}
})
it('names none for a bypassed host, and none at all without a policy', async () => {
const dispose = await installGlobalProxy(proxyAll('api.example.com'))
try {
expect(proxyUrlFor(new URL('https://api.example.com/v1'))).toBeUndefined()
} finally {
await dispose()
}
expect(proxyUrlFor(new URL('https://api.example.com/v1'))).toBeUndefined()
})
})
@@ -0,0 +1,106 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import InvariantRegistry from '@deepseek-ai/dsh-invariants'
import { getGlobalDispatcher } from 'undici'
import * as HttpProxy from '../src/index.ts'
import * as HttpProxyInvariant from '../src/invariant.ts'
const PROXY = 'http://127.0.0.1:7897'
/**
* Every proxy name in both casings. The suite clears all of them so a developer's own exported proxy
* cannot decide the outcome — the lowercase names matter most, since resolution reads those first.
*/
const PROXY_ENV_NAMES = [
'http_proxy', 'HTTP_PROXY', 'https_proxy', 'HTTPS_PROXY',
'no_proxy', 'NO_PROXY', 'all_proxy', 'ALL_PROXY',
] as const
let saved: Record<string, string | undefined> = {}
beforeEach(() => {
saved = Object.fromEntries(PROXY_ENV_NAMES.map(name => [name, process.env[name]]))
for (const name of PROXY_ENV_NAMES) Reflect.deleteProperty(process.env, name)
})
afterEach(() => {
for (const [name, value] of Object.entries(saved)) {
if (value === undefined) Reflect.deleteProperty(process.env, name)
else process.env[name] = value
}
})
/** The launcher normally provides a snapshot; without one the plugin reads the process environment. */
function withEnv(values: Record<string, string>): void {
for (const [name, value] of Object.entries(values)) process.env[name] = value
}
describe('http-proxy plugin', () => {
it('installs the configured policy and restores the dispatcher on disposal', async () => {
const before = getGlobalDispatcher()
const ctx = new Context()
const fiber = await ctx.plugin(HttpProxy, { httpProxy: PROXY })
expect(HttpProxy.currentProxyPolicy()?.httpProxy).toBe(PROXY)
expect(getGlobalDispatcher()).not.toBe(before)
await fiber.dispose()
expect(HttpProxy.currentProxyPolicy()).toBeUndefined()
expect(getGlobalDispatcher()).toBe(before)
})
it('lets a real environment variable outrank the configured proxy', async () => {
withEnv({ HTTP_PROXY: PROXY })
const ctx = new Context()
const fiber = await ctx.plugin(HttpProxy, { httpProxy: 'http://127.0.0.1:9' })
try {
expect(HttpProxy.currentProxyPolicy()?.httpProxy).toBe(PROXY)
} finally {
await fiber.dispose()
}
})
it('installs nothing under mode off, even with a proxy in the environment', async () => {
withEnv({ HTTP_PROXY: PROXY })
const before = getGlobalDispatcher()
const ctx = new Context()
const fiber = await ctx.plugin(HttpProxy, { mode: 'off' })
try {
expect(HttpProxy.currentProxyPolicy()?.source).toBe('none')
expect(getGlobalDispatcher()).toBe(before)
} finally {
await fiber.dispose()
}
})
it('reports an unusable environment value and connects directly instead of failing the load', async () => {
withEnv({ HTTP_PROXY: 'socks5://127.0.0.1:1080' })
const before = getGlobalDispatcher()
const ctx = new Context()
const fiber = await ctx.plugin(HttpProxy, {})
try {
expect(HttpProxy.currentProxyPolicy()?.source).toBe('none')
expect(getGlobalDispatcher()).toBe(before)
} finally {
await fiber.dispose()
}
})
it('fails the load when the composition itself declares an unusable proxy', async () => {
const ctx = new Context()
await expect(ctx.plugin(HttpProxy, { httpsProxy: 'socks5://127.0.0.1:1080' }))
.rejects.toThrow(/SOCKS proxy/)
})
})
describe('http-proxy invariant companion', () => {
it('reserves the package name against duplicate registration', async () => {
const ctx = new Context()
await ctx.plugin(InvariantRegistry)
await ctx.plugin(HttpProxyInvariant)
expect(() => {
ctx.invariants.register('@deepseek-ai/dsh-http-proxy', () => {})
}).toThrow(/already registered/)
})
})
@@ -0,0 +1,209 @@
import { describe, expect, it } from 'vitest'
import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import {
bypassesProxy,
describeProxyPolicy,
proxyForUrl,
resolveProxyPolicy,
DIRECT_POLICY,
} from '../src/policy.ts'
const PROXY = 'http://127.0.0.1:7897'
const OTHER = 'http://127.0.0.1:8080'
function env(values: Record<string, string>): ReturnType<typeof createLaunchEnvironmentSnapshot> {
return createLaunchEnvironmentSnapshot([{ source: 'process', values }])
}
describe('resolveProxyPolicy', () => {
it('resolves nothing when the environment carries no proxy', () => {
const { policy, diagnostics } = resolveProxyPolicy(env({}))
expect(policy).toEqual(DIRECT_POLICY)
expect(diagnostics).toEqual([])
})
it('reads both schemes and merges loopback into the bypass list', () => {
const { policy } = resolveProxyPolicy(env({ HTTP_PROXY: PROXY, HTTPS_PROXY: OTHER, NO_PROXY: 'example.com' }))
expect(policy.httpProxy).toBe(PROXY)
expect(policy.httpsProxy).toBe(OTHER)
expect(policy.noProxy).toBe('example.com,localhost,127.0.0.1,::1,[::1]')
expect(policy.source).toBe('env')
})
it('prefers the lowercase name, matching undici', () => {
const { policy } = resolveProxyPolicy(env({ http_proxy: PROXY, HTTP_PROXY: OTHER }))
expect(policy.httpProxy).toBe(PROXY)
})
it('treats a blank lowercase value as unset instead of letting it shadow the uppercase one', () => {
const { policy } = resolveProxyPolicy(env({ http_proxy: ' ', HTTP_PROXY: PROXY }))
expect(policy.httpProxy).toBe(PROXY)
})
it('backs both schemes with ALL_PROXY, which neither Node nor undici reads', () => {
const { policy } = resolveProxyPolicy(env({ ALL_PROXY: PROXY }))
expect(policy.httpProxy).toBe(PROXY)
expect(policy.httpsProxy).toBe(PROXY)
})
it('lets a scheme-specific value outrank ALL_PROXY', () => {
const { policy } = resolveProxyPolicy(env({ ALL_PROXY: PROXY, HTTPS_PROXY: OTHER }))
expect(policy.httpProxy).toBe(PROXY)
expect(policy.httpsProxy).toBe(OTHER)
})
it('falls HTTPS back to the HTTP proxy last, so the dispatcher and proxyForUrl agree', () => {
const { policy } = resolveProxyPolicy(env({ HTTP_PROXY: PROXY }))
expect(policy.httpsProxy).toBe(PROXY)
})
it('keeps a bypass list of * unchanged', () => {
const { policy } = resolveProxyPolicy(env({ HTTP_PROXY: PROXY, NO_PROXY: '*' }))
expect(policy.noProxy).toBe('*')
})
it('does not repeat a loopback entry the user already listed', () => {
const { policy } = resolveProxyPolicy(env({ HTTP_PROXY: PROXY, NO_PROXY: 'localhost, 127.0.0.1' }))
expect(policy.noProxy).toBe('localhost,127.0.0.1,::1,[::1]')
})
it('reports a SOCKS proxy instead of silently ignoring it', () => {
const { policy, diagnostics } = resolveProxyPolicy(env({ HTTP_PROXY: 'socks5://127.0.0.1:7890' }))
expect(policy).toEqual(DIRECT_POLICY)
expect(diagnostics).toHaveLength(1)
expect(diagnostics[0]?.kind).toBe('socks')
expect(diagnostics[0]?.message).toMatch(/SOCKS proxy, which is not supported/)
})
it('reports an unparseable proxy URL', () => {
const { policy, diagnostics } = resolveProxyPolicy(env({ HTTP_PROXY: 'not a url' }))
expect(policy).toEqual(DIRECT_POLICY)
expect(diagnostics[0]?.kind).toBe('invalid')
expect(diagnostics[0]?.origin).toBe('HTTP_PROXY')
})
it('reports a proxy URL whose scheme is neither http(s) nor SOCKS', () => {
const { diagnostics } = resolveProxyPolicy(env({ HTTP_PROXY: 'ftp://proxy.example' }))
expect(diagnostics[0]?.message).toMatch(/unsupported ftp:\/\/ scheme/)
})
it('lets configuration fill a gap the environment leaves', () => {
const { policy } = resolveProxyPolicy(env({}), { httpProxy: PROXY, noProxy: 'internal.example' })
expect(policy.httpProxy).toBe(PROXY)
expect(policy.httpsProxy).toBe(PROXY)
expect(policy.noProxy).toBe('internal.example,localhost,127.0.0.1,::1,[::1]')
expect(policy.source).toBe('config')
})
it('lets the environment outrank configuration', () => {
const { policy } = resolveProxyPolicy(env({ HTTP_PROXY: PROXY }), { httpProxy: OTHER })
expect(policy.httpProxy).toBe(PROXY)
expect(policy.source).toBe('env')
})
it('names configuration as the origin of a rejected configured value', () => {
const { diagnostics } = resolveProxyPolicy(env({}), { httpsProxy: 'socks5://127.0.0.1:1080' })
expect(diagnostics[0]?.origin).toBe('config.httpsProxy')
})
it('ignores every source under mode off', () => {
const { policy } = resolveProxyPolicy(env({ HTTP_PROXY: PROXY }), { mode: 'off' })
expect(policy).toEqual(DIRECT_POLICY)
})
})
describe('bypassesProxy', () => {
const cases: [string, string, boolean][] = [
['example.com', 'http://example.com/a', true],
['example.com', 'http://sub.example.com/a', true],
['example.com', 'http://notexample.com/a', false],
['.example.com', 'http://sub.example.com/a', true],
['*.example.com', 'http://sub.example.com/a', true],
['example.com', 'http://example.com./a', true],
['*', 'http://anything.example/a', true],
['example.com:8080', 'http://example.com:8080/a', true],
['example.com:8080', 'http://example.com:9090/a', false],
['example.com:80', 'http://example.com/a', true],
['example.com:443', 'https://example.com/a', true],
['EXAMPLE.com', 'http://example.COM/a', true],
['localhost', 'http://localhost:3000/a', true],
['127.0.0.1', 'http://127.0.0.1:7777/a', true],
]
it.each(cases)('bypass %j against %j is %s', (noProxy, url, expected) => {
expect(bypassesProxy(noProxy, new URL(url))).toBe(expected)
})
it('bypasses a bare IPv6 loopback, which undici reads as host ":" port "1"', () => {
expect(bypassesProxy('::1', new URL('http://[::1]:3000/a'))).toBe(true)
})
it('bypasses the bracketed IPv6 form as well', () => {
expect(bypassesProxy('[::1]', new URL('http://[::1]/a'))).toBe(true)
})
it('honors a port on a bracketed IPv6 entry', () => {
expect(bypassesProxy('[::1]:3000', new URL('http://[::1]:3000/a'))).toBe(true)
expect(bypassesProxy('[::1]:3000', new URL('http://[::1]:4000/a'))).toBe(false)
})
it('does not match CIDR notation, so an OS bypass list must be rewritten as suffixes', () => {
expect(bypassesProxy('10.0.0.0/8', new URL('http://10.1.2.3/a'))).toBe(false)
})
it('skips blank and bracket-only entries', () => {
expect(bypassesProxy(' , , [ , .', new URL('http://example.com/a'))).toBe(false)
})
})
describe('proxyForUrl', () => {
const { policy } = resolveProxyPolicy(env({ HTTP_PROXY: PROXY, HTTPS_PROXY: OTHER, NO_PROXY: 'direct.example' }))
it('routes http through the http proxy', () => {
expect(proxyForUrl(policy, new URL('http://example.com/'))).toBe(PROXY)
})
it('routes https through the https proxy', () => {
expect(proxyForUrl(policy, new URL('https://example.com/'))).toBe(OTHER)
})
it('returns nothing for a bypassed host', () => {
expect(proxyForUrl(policy, new URL('https://direct.example/'))).toBeUndefined()
})
it('returns nothing for loopback, which is always bypassed', () => {
expect(proxyForUrl(policy, new URL('http://127.0.0.1:9000/'))).toBeUndefined()
})
it('returns nothing for a non-http scheme', () => {
expect(proxyForUrl(policy, new URL('ws://example.com/'))).toBeUndefined()
})
it('returns nothing under a direct policy', () => {
expect(proxyForUrl(DIRECT_POLICY, new URL('https://example.com/'))).toBeUndefined()
})
})
describe('describeProxyPolicy', () => {
it('names a direct policy', () => {
expect(describeProxyPolicy(DIRECT_POLICY)).toBe('no proxy (direct)')
})
it('replaces the password and keeps the username', () => {
const { policy } = resolveProxyPolicy(env({ HTTP_PROXY: 'http://alice:[email protected]:8080' }))
const described = describeProxyPolicy(policy)
expect(described).toContain('alice')
expect(described).toContain('***')
expect(described).not.toContain('s3cret')
})
it('reports a scheme left direct', () => {
expect(describeProxyPolicy({ httpsProxy: PROXY, noProxy: '', source: 'env' })).toContain('http=direct')
expect(describeProxyPolicy({ httpProxy: PROXY, noProxy: '', source: 'env' })).toContain('https=direct')
})
it('resolves an https-only environment without an http proxy', () => {
const { policy } = resolveProxyPolicy(env({ HTTPS_PROXY: PROXY }))
expect(policy.httpProxy).toBeUndefined()
expect(policy.httpsProxy).toBe(PROXY)
})
})
+18
View File
@@ -0,0 +1,18 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": [
"src"
],
"references": [
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../util/launch-environment"
}
]
}
@@ -41,21 +41,25 @@
"@deepseek-ai/schemastery": "workspace:^"
},
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-anonymous-user-id": "workspace:^",
"@deepseek-ai/dsh-command-feedback": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-session-telemetry": "workspace:^",
"@deepseek-ai/dsh-anonymous-user-id": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/dsh-session-telemetry": "workspace:^"
},
"devDependencies": {
"@deepseek-ai/cordis-plugin-logger-console": "workspace:^",
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/cordis-plugin-loader": "workspace:^",
"@deepseek-ai/cordis-plugin-logger-console": "workspace:^",
"@deepseek-ai/dsh-agent-spine-demo": "workspace:^",
"@deepseek-ai/dsh-anonymous-user-id": "workspace:^",
"@deepseek-ai/dsh-app-boot": "workspace:^",
"@deepseek-ai/dsh-bash-local": "workspace:^",
"@deepseek-ai/dsh-command-feedback": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-loader-smoke": "workspace:^",
@@ -63,8 +67,6 @@
"@deepseek-ai/dsh-session-checkpoint-policy": "workspace:^",
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^",
"@deepseek-ai/dsh-session-telemetry": "workspace:^",
"@deepseek-ai/dsh-subprocess-local": "workspace:^",
"@deepseek-ai/dsh-anonymous-user-id": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/dsh-subprocess-local": "workspace:^"
}
}
@@ -32,6 +32,7 @@ import {
type BatchLogRecordProcessorOptions,
} from '@opentelemetry/sdk-logs'
import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'
import { createNodeHttpAgent } from '@deepseek-ai/dsh-http-proxy'
import type { OTLPExporterNodeConfigBase } from '@opentelemetry/otlp-exporter-base'
import { SeverityNumber, type AnyValue, type Logger } from '@opentelemetry/api-logs'
import { resourceFromAttributes } from '@opentelemetry/resources'
@@ -212,7 +213,15 @@ export class OpenTelemetrySessionBackend extends SessionTelemetryBackend {
// ignore the rest. App identity travels in the Resource
// (service.name/version); the transport-level user-agent is the
// SDK's own, per the axiom.
exporter: new OTLPLogExporter(config.exporter),
//
// The one added default is the agent. On Node this exporter posts through `node:http`,
// which undici's global dispatcher does not reach, so telemetry would be the one egress
// that ignores a configured proxy. A composition supplying its own `httpAgentOptions`
// keeps it.
exporter: new OTLPLogExporter({
httpAgentOptions: (protocol: string) => createNodeHttpAgent(protocol, { keepAlive: true }),
...config.exporter,
}),
}),
],
})
@@ -0,0 +1,71 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Context } from '@deepseek-ai/cordis'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import OpenTelemetrySessionBackend, { SessionTelemetryMode } from '../src/index.ts'
let home: string
let previousHome: string | undefined
beforeAll(() => {
home = mkdtempSync(join(tmpdir(), 'dsh-otel-egress-'))
previousHome = process.env.DSH_HOME
process.env.DSH_HOME = home
})
afterAll(() => {
if (previousHome === undefined) delete process.env.DSH_HOME
else process.env.DSH_HOME = previousHome
rmSync(home, { recursive: true, force: true })
})
/** Mount the shipping backend against an unresolvable collector and let it try to export. */
async function exportThroughBackend(): Promise<void> {
const ctx = new Context()
await ctx.plugin(SessionStore)
const fiber = await ctx.plugin(OpenTelemetrySessionBackend, {
mode: SessionTelemetryMode.FULL,
exporter: { url: 'http://otel-probe.invalid/v1/logs' },
})
const session = ctx.sessions.create(SessionId('egress'), { meta: { cwd: '/tmp/e' } })
session.append('turn/start', { turn: 1 })
ctx.sessionTelemetry.emit({ channel: 'ledger', time: Date.now(), severity: 'info', event: { type: 'probe' } } as never)
await fiber.dispose()
}
describe('session-telemetry-otel egress', () => {
it('exports through the proxy', async () => {
expect((await observe(exportThroughBackend)).join('|')).toContain('otel-probe.invalid')
})
})
@@ -34,6 +34,9 @@
},
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../net/http-proxy"
}
]
}
+6 -4
View File
@@ -32,11 +32,13 @@
],
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^"
},
"devDependencies": {
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^"
}
}
+7 -1
View File
@@ -9,6 +9,7 @@
*/
import { Context, Service } from '@deepseek-ai/cordis'
import { childProxyEnv } from '@deepseek-ai/dsh-http-proxy'
import { DSH_ENV_PREFIX } from './types.ts'
import type { SubprocessHandle, SubprocessSpawnSpec } from './types.ts'
import type { SubprocessTerminalHandle, SubprocessTerminalSpawnSpec } from './types.ts'
@@ -55,6 +56,9 @@ export const SENSITIVE_ENV_PATTERN = /KEY|PASSWORD|SECRET|TOKEN/i
* deliberate lowercase `dsh_*` names on POSIX are implausible. Exported as a plain function so spawners
* that cannot route through the service (node-pty backends, SDK-managed
* transports) share the one scrub definition.
*
* When a proxy is active the result also carries the resolved proxy names and the flag a child Node
* needs to honor them, so a child inherits the same routing as its parent.
* @returns a fresh environment object safe to hand to a child spawn.
*/
export function scrubbedParentEnv(): Record<string, string> {
@@ -62,7 +66,9 @@ export function scrubbedParentEnv(): Record<string, string> {
for (const [key, value] of Object.entries(process.env)) {
if (value !== undefined && !SENSITIVE_ENV_PATTERN.test(key) && !key.toUpperCase().startsWith(DSH_ENV_PREFIX)) env[key] = value
}
return env
// A child Node ignores the inherited proxy variables unless the flag this adds is set, so an MCP
// stdio server or subagent CLI would connect directly while its parent proxies.
return { ...env, ...childProxyEnv() }
}
declare module '@deepseek-ai/cordis' {
@@ -0,0 +1,57 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { spawn } from 'node:child_process'
import { scrubbedParentEnv } from '../src/index.ts'
/** Run a child Node that fetches, using exactly the environment every harness spawner builds. */
function childFetch(target: string, env: Record<string, string>): Promise<string> {
return new Promise((resolve) => {
const child = spawn(process.execPath, ['-e', `fetch(${JSON.stringify(target)}).then(r=>r.text()).then(t=>console.log(t)).catch(e=>console.log('ERR'+String(e.cause?.code)))`],
{ env, stdio: ['ignore', 'pipe', 'ignore'] })
let out = ''
child.stdout.on('data', (c: Buffer) => { out += c.toString() })
child.on('close', () => { resolve(out.trim()) })
})
}
describe('child process egress', () => {
it('a child Node honors the parent policy through scrubbedParentEnv', async () => {
let childEnv: Record<string, string> = {}
const observed = await observe(async () => {
childEnv = scrubbedParentEnv()
await childFetch('http://child-probe.invalid/x', childEnv)
})
expect(childEnv.NODE_USE_ENV_PROXY).toBe('1')
expect(observed.join('|')).toContain('child-probe.invalid')
})
})
@@ -16,6 +16,9 @@
},
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../net/http-proxy"
}
]
}
+2
View File
@@ -33,6 +33,7 @@
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-timeout": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^"
@@ -44,6 +45,7 @@
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-timeout": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^"
+50 -6
View File
@@ -9,7 +9,8 @@
import { lookup as systemLookup } from 'node:dns/promises'
import type { LookupAddress, LookupOptions } from 'node:dns'
import { isIP } from 'node:net'
import type { Response } from 'undici'
import type { Agent, Response } from 'undici'
import { createDispatcher } from '@deepseek-ai/dsh-http-proxy'
import ipaddr from 'ipaddr.js'
import { WebError } from '@deepseek-ai/dsh-web'
@@ -173,14 +174,56 @@ export async function requestPinned(
headers: Record<string, string>,
signal: AbortSignal,
): Promise<PinnedResponse> {
// Keep the Node-only transport out of browser-worker startup. The preview
// can load the provider and fail loud at its DNS stub without evaluating
// Undici; a real request on Node resolves this maintained dependency here.
const { Agent, fetch } = await import('undici')
const dispatcher = new Agent({
return await requestWith(url, headers, signal, {
autoSelectFamily: true,
connect: { lookup: createPinnedLookup(addresses) },
})
}
/**
* Fetch through the active proxy, letting it resolve the origin.
*
* No address set is pinned because none exists to pin: the proxy performs the lookup, and a
* connection pinned to a locally resolved address would reach the origin directly and defeat the
* proxy. Configuring a proxy therefore delegates destination selection to it; the URL-level policy
* in `policy.ts` still applies to every hop.
*
* @param url - validated HTTP(S) URL the active policy routes through a proxy.
* @param headers - request headers.
* @param signal - request and body-read cancellation signal.
* @returns a response plus the dispatcher disposer its consumer must call.
*/
export async function requestProxied(
url: URL,
headers: Record<string, string>,
signal: AbortSignal,
): Promise<PinnedResponse> {
return await requestWith(url, headers, signal, {})
}
/**
* Issue one request on a policy-aware dispatcher the caller then owns.
*
* The dispatcher comes from `dsh-http-proxy` rather than a bare `new Agent`, which would bypass the
* global dispatcher and with it the proxy — the defect this package had before proxy support existed.
*
* @param url - validated HTTP(S) URL.
* @param headers - request headers.
* @param signal - request and body-read cancellation signal.
* @param options - agent options applied to whichever agent the policy selects.
* @returns a response plus the dispatcher disposer its consumer must call.
*/
async function requestWith(
url: URL,
headers: Record<string, string>,
signal: AbortSignal,
options: Agent.Options,
): Promise<PinnedResponse> {
// Keep the Node-only transport out of browser-worker startup. The preview
// can load the provider and fail loud at its DNS stub without evaluating
// Undici; a real request on Node resolves this maintained dependency here.
const { fetch } = await import('undici')
const dispatcher = await createDispatcher(url, options)
try {
const response = await fetch(url, { method: 'GET', redirect: 'manual', headers, signal, dispatcher })
return { response, close: async () => { await dispatcher.close() } }
@@ -194,6 +237,7 @@ export async function requestPinned(
export const publicHttpNetwork = {
resolve: resolvePublicAddresses,
request: requestPinned,
requestProxied,
}
type LookupCallback = (
+13 -4
View File
@@ -10,6 +10,7 @@ import { WebError } from '@deepseek-ai/dsh-web'
import type { WebFetchBody, WebFetchProvider, WebFetchRequest, WebFetchResult } from '@deepseek-ai/dsh-web'
import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout'
import type { Response } from 'undici'
import { currentProxyPolicy, proxyForUrl, DIRECT_POLICY } from '@deepseek-ai/dsh-http-proxy'
import { publicHttpNetwork } from './network.ts'
import type { PublicAddress } from './network.ts'
import { classifyContentType, decoderForCharset, isSameOrigin, parseCharset, validateFetchUrl } from './policy.ts'
@@ -114,12 +115,20 @@ export class HttpFetchProvider implements WebFetchProvider {
}
private async requestOnce(url: URL, signal: AbortSignal) {
const headers = {
'user-agent': this.limits.userAgent,
'accept': 'text/html,application/xhtml+xml,text/*;q=0.9,application/json;q=0.8',
}
try {
// A proxied hop skips public-address resolution and pinning: the proxy performs the origin's
// DNS, so there is no local address to validate, and pinning one would connect directly and
// bypass the proxy. A hop the policy bypasses — every loopback and every `NO_PROXY` entry —
// still takes the resolved-and-pinned path unchanged.
if (proxyForUrl(currentProxyPolicy() ?? DIRECT_POLICY, url) !== undefined) {
return await publicHttpNetwork.requestProxied(url, headers, signal)
}
const addresses = await this.resolveAddresses(url.hostname, signal)
return await publicHttpNetwork.request(url, addresses, {
'user-agent': this.limits.userAgent,
'accept': 'text/html,application/xhtml+xml,text/*;q=0.9,application/json;q=0.8',
}, signal)
return await publicHttpNetwork.request(url, addresses, headers, signal)
} catch (error: unknown) {
if (error instanceof WebError) throw error
throw translateAbortOrNetwork(error, signal)
@@ -0,0 +1,119 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
import { HttpFetchProvider } from '@deepseek-ai/dsh-web-fetch-http'
import type { HttpFetchLimits } from '@deepseek-ai/dsh-web-fetch-http'
import { publicHttpNetwork } from '../src/network.ts'
const limits: HttpFetchLimits = {
maxResponseBytes: 5_000_000,
maxBodyChars: 100_000,
timeoutMs: 5_000,
maxRedirects: 5,
userAgent: 'test-agent/1.0',
}
/** Absolute-form targets the fake proxy saw; a populated entry proves the hop was tunnelled. */
let proxied: string[]
let proxy: Server
let origin: Server
let proxyUrl: string
let originUrl: string
let disposeProxy: (() => Promise<void>) | undefined
function listen(server: Server): Promise<AddressInfo> {
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => { resolve(server.address() as AddressInfo) })
})
}
function respond(_request: IncomingMessage, response: ServerResponse, body: string): void {
response.writeHead(200, { 'content-type': 'text/plain' })
response.end(body)
}
beforeEach(async () => {
proxied = []
proxy = createServer((request, response) => {
proxied.push(request.url ?? '')
respond(request, response, 'via-proxy')
})
origin = createServer((request, response) => { respond(request, response, 'direct') })
const [proxyAddress, originAddress] = await Promise.all([listen(proxy), listen(origin)])
proxyUrl = `http://127.0.0.1:${String(proxyAddress.port)}`
originUrl = `http://127.0.0.1:${String(originAddress.port)}/page`
})
afterEach(async () => {
await disposeProxy?.()
disposeProxy = undefined
vi.restoreAllMocks()
await Promise.all([
new Promise<void>((resolve) => { proxy.close(() => { resolve() }) }),
new Promise<void>((resolve) => { origin.close(() => { resolve() }) }),
])
})
/** A policy proxying everything, since a resolved policy always bypasses the loopback used here. */
function policy(noProxy = ''): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy, source: 'env' }
}
describe('fetching through a proxy', () => {
it('tunnels the request and never resolves a public address for it', async () => {
const resolve = vi.spyOn(publicHttpNetwork, 'resolve')
disposeProxy = await installGlobalProxy(policy())
const result = await new HttpFetchProvider(limits).fetch({ url: originUrl })
expect(result.body.content).toBe('via-proxy')
expect(proxied).toEqual([originUrl])
// Through a proxy the origin's DNS happens proxy-side, so the resolver that rejects non-public
// destinations is not consulted at all.
expect(resolve).not.toHaveBeenCalled()
})
it('keeps resolving and pinning a hop the bypass list covers', async () => {
const resolve = vi.spyOn(publicHttpNetwork, 'resolve')
.mockResolvedValue([{ address: '127.0.0.1', family: 4 }])
disposeProxy = await installGlobalProxy(policy('127.0.0.1'))
const result = await new HttpFetchProvider(limits).fetch({ url: originUrl })
expect(result.body.content).toBe('direct')
expect(proxied).toEqual([])
expect(resolve).toHaveBeenCalledOnce()
})
it('resolves and pins when no proxy is installed', async () => {
const resolve = vi.spyOn(publicHttpNetwork, 'resolve')
.mockResolvedValue([{ address: '127.0.0.1', family: 4 }])
const result = await new HttpFetchProvider(limits).fetch({ url: originUrl })
expect(result.body.content).toBe('direct')
expect(resolve).toHaveBeenCalledOnce()
})
it('still refuses a cross-origin redirect on the proxied path', async () => {
proxy.removeAllListeners('request')
proxy.on('request', (request, response) => {
proxied.push(request.url ?? '')
response.writeHead(302, { location: 'http://elsewhere.example/next' })
response.end()
})
disposeProxy = await installGlobalProxy(policy())
await expect(new HttpFetchProvider(limits).fetch({ url: originUrl }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_REDIRECT_BLOCKED' }))
})
it('still refuses a URL the transport policy rejects before any hop', async () => {
disposeProxy = await installGlobalProxy(policy())
await expect(new HttpFetchProvider(limits).fetch({ url: 'ftp://example.com/x' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_INVALID_URL' }))
expect(proxied).toEqual([])
})
})
@@ -25,6 +25,9 @@
},
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../net/http-proxy"
}
]
}
@@ -45,14 +45,15 @@
"@deepseek-ai/schemastery": "workspace:^"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-credentials": "workspace:^",
"@deepseek-ai/dsh-credentials-local": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^",
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-settings": "workspace:^"
"@deepseek-ai/dsh-settings": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^"
}
}
@@ -0,0 +1,39 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { DeepSeekSearchProvider } from '../src/provider.ts'
describe('deepseek search egress', () => {
it('goes through the proxy', async () => {
const p = new DeepSeekSearchProvider(() => ({ apiKey: 'probe', baseURL: 'http://dsk-probe.invalid', model: 'm', apiVersion: '2023-06-01', maxTokens: 16, maxUses: 1 }))
expect(await observe(() => p.search({ query: 'probe' }))).toEqual(['REQ http://dsk-probe.invalid/messages'])
})
})
@@ -37,6 +37,9 @@
},
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../net/http-proxy"
}
]
}
+4 -3
View File
@@ -41,9 +41,10 @@
"@deepseek-ai/schemastery": "workspace:^"
},
"devDependencies": {
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^"
}
}
@@ -0,0 +1,39 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { ExaSearchProvider } from '../src/provider.ts'
describe('exa egress', () => {
it('goes through the proxy', async () => {
const p = new ExaSearchProvider({ apiKey: 'probe', baseURL: 'http://exa-probe.invalid', searchType: 'auto', highlightsPerResult: 1 })
expect(await observe(() => p.search({ query: 'probe' }))).toEqual(['REQ http://exa-probe.invalid/search'])
})
})
@@ -25,6 +25,9 @@
},
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../net/http-proxy"
}
]
}
@@ -41,9 +41,10 @@
"@deepseek-ai/schemastery": "workspace:^"
},
"devDependencies": {
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^"
}
}
@@ -0,0 +1,39 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { PerplexitySearchProvider } from '../src/provider.ts'
describe('perplexity egress', () => {
it('goes through the proxy', async () => {
const p = new PerplexitySearchProvider({ apiKey: 'probe', baseURL: 'http://ppx-probe.invalid', model: 'm', maxTokens: 16 })
expect(await observe(() => p.search({ query: 'probe' }))).toEqual(['REQ http://ppx-probe.invalid/chat/completions'])
})
})
@@ -25,6 +25,9 @@
},
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../net/http-proxy"
}
]
}
@@ -65,6 +65,7 @@
"@deepseek-ai/dsh-workflow": "workspace:^",
"@deepseek-ai/cordis": "workspace:^",
"tsx": "^4.19.2",
"@deepseek-ai/dsh-session-projection": "workspace:^"
"@deepseek-ai/dsh-session-projection": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^"
}
}
@@ -8,6 +8,7 @@
import { tmpdir } from 'node:os'
import { Worker } from 'node:worker_threads'
import { childProxyEnv } from '@deepseek-ai/dsh-http-proxy'
import type { WorkerOptions } from 'node:worker_threads'
import { fileURLToPath } from 'node:url'
import type { Context } from '@deepseek-ai/cordis'
@@ -30,7 +31,9 @@ interface ChildRecord {
}
/**
* The scrubbed worker environment: no ambient credentials, no loader flags.
* The scrubbed worker environment: no ambient credentials, no loader flags, plus the active proxy
* policy — a worker thread does not inherit the host's global dispatcher, so this is the only way
* its requests reach the same proxy the host uses.
* Windows derives `os.tmpdir()` from `TMP`/`TEMP` and falls back to the
* literal relative path `undefined\temp` when the environment is empty, so
* tsx's transform cache would land in a cwd-relative `undefined/temp`
@@ -46,7 +49,11 @@ export function workerSpawnEnv(
platform: NodeJS.Platform = process.platform,
tsconfigPath?: string,
): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {}
// A worker thread gets its own globalThis and therefore does NOT inherit the host's undici global
// dispatcher, so a workflow that fetches would connect directly while its host proxies. This
// near-empty environment is the only channel it has: the proxy names plus Node's own opt-in flag
// reach the worker's pre-execution setup, which runs per thread.
const env: NodeJS.ProcessEnv = { ...childProxyEnv() }
if (platform === 'win32') {
const tmp = tmpdir()
env.TMP = tmp
@@ -0,0 +1,51 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { installGlobalProxy, type ProxyPolicy } from '@deepseek-ai/dsh-http-proxy'
let seen: string[] = []
let proxy: Server
let proxyUrl: string
beforeAll(async () => {
proxy = createServer((request, response) => {
seen.push(`REQ ${request.url ?? ''}`)
response.writeHead(502); response.end('fake-proxy')
})
proxy.on('connect', (request, socket) => {
seen.push(`CONNECT ${request.url ?? ''}`)
socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.end()
})
const a = await new Promise<AddressInfo>((r) => { proxy.listen(0, '127.0.0.1', () => { r(proxy.address() as AddressInfo) }) })
proxyUrl = `http://127.0.0.1:${String(a.port)}`
})
afterAll(async () => { await new Promise<void>((r) => { proxy.close(() => { r() }) }) })
function policy(): ProxyPolicy {
return { httpProxy: proxyUrl, httpsProxy: proxyUrl, noProxy: '', source: 'env' }
}
async function observe(run: () => Promise<unknown>): Promise<string[]> {
seen = []
const dispose = await installGlobalProxy(policy())
try { await run().catch(() => undefined) } finally { await dispose() }
return seen
}
import { Worker } from 'node:worker_threads'
import { once } from 'node:events'
import { workerSpawnEnv } from '../src/host.ts'
describe('worker thread egress', () => {
it('a worker honors the host policy through workerSpawnEnv', async () => {
const observed = await observe(async () => {
const worker = new Worker(
`import { parentPort, workerData } from 'node:worker_threads'
let out; try { out = await (await fetch(workerData.u)).text() } catch (e) { out = 'ERR' + String(e.cause?.code) }
parentPort.postMessage(out)`,
{ eval: true, workerData: { u: 'http://worker-probe.invalid/x' }, env: workerSpawnEnv(), execArgv: [] },
)
await once(worker, 'message')
await worker.terminate()
})
expect(observed.join('|')).toContain('worker-probe.invalid')
})
})
@@ -40,6 +40,9 @@
},
{
"path": "../../runtime-diagnostics/invariants"
},
{
"path": "../../net/http-proxy"
}
]
}
+55
View File
@@ -198,6 +198,9 @@ importers:
'@deepseek-ai/dsh-hooks-codex':
specifier: workspace:^
version: link:../../packages/hooks/hooks-codex
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../packages/net/http-proxy
'@deepseek-ai/dsh-jobs-local':
specifier: workspace:^
version: link:../../packages/jobs/jobs-local
@@ -4583,6 +4586,9 @@ importers:
'@deepseek-ai/dsh-fs-e2b':
specifier: workspace:^
version: link:../fs-e2b
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -6486,6 +6492,9 @@ importers:
'@deepseek-ai/dsh-fs':
specifier: workspace:^
version: link:../../fs/fs
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -6762,6 +6771,9 @@ importers:
'@deepseek-ai/dsh-attachment-local':
specifier: workspace:^
version: link:../../attachment/attachment-local
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -6787,6 +6799,25 @@ importers:
specifier: ^2026.7.4
version: 2026.7.10([email protected])
packages/net/http-proxy:
dependencies:
'@deepseek-ai/schemastery':
specifier: link:../../../vendor/schemastery
version: link:../../../vendor/schemastery
undici:
specifier: ^8.10.0
version: 8.10.0
devDependencies:
'@deepseek-ai/cordis':
specifier: workspace:^
version: link:../../../vendor/cordis
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
'@deepseek-ai/dsh-launch-environment':
specifier: workspace:^
version: link:../../util/launch-environment
packages/plan/plan-mode:
dependencies:
zod:
@@ -7622,6 +7653,9 @@ importers:
'@deepseek-ai/dsh-command-feedback':
specifier: workspace:^
version: link:../../feedback/command-feedback
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -9155,6 +9189,9 @@ importers:
'@deepseek-ai/cordis':
specifier: workspace:^
version: link:../../../vendor/cordis
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -9835,6 +9872,9 @@ importers:
'@deepseek-ai/cordis':
specifier: workspace:^
version: link:../../../vendor/cordis
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -9863,6 +9903,9 @@ importers:
'@deepseek-ai/dsh-credentials-local':
specifier: workspace:^
version: link:../../credentials/credentials-local
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -9888,6 +9931,9 @@ importers:
'@deepseek-ai/cordis':
specifier: workspace:^
version: link:../../../vendor/cordis
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -9907,6 +9953,9 @@ importers:
'@deepseek-ai/cordis':
specifier: workspace:^
version: link:../../../vendor/cordis
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -10130,6 +10179,9 @@ importers:
'@deepseek-ai/dsh-brand':
specifier: workspace:^
version: link:../../util/brand
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../runtime-diagnostics/invariants
@@ -10317,6 +10369,9 @@ importers:
'@deepseek-ai/dsh-hooks-codex':
specifier: workspace:^
version: link:../../packages/hooks/hooks-codex
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:^
version: link:../../packages/net/http-proxy
'@deepseek-ai/dsh-invariants':
specifier: workspace:^
version: link:../../packages/runtime-diagnostics/invariants
+26 -25
View File
@@ -5,6 +5,7 @@
"private": true,
"type": "module",
"dependencies": {
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/cordis-plugin-group": "workspace:^",
"@deepseek-ai/cordis-plugin-include": "workspace:^",
"@deepseek-ai/cordis-plugin-loader": "workspace:^",
@@ -13,14 +14,15 @@
"@deepseek-ai/dsh": "workspace:^",
"@deepseek-ai/dsh-acp": "workspace:^",
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-agent-instructions": "workspace:^",
"@deepseek-ai/dsh-agent-loop": "workspace:^",
"@deepseek-ai/dsh-agent-spine-demo": "workspace:^",
"@deepseek-ai/dsh-agent-tool-presentation": "workspace:^",
"@deepseek-ai/dsh-anonymous-user-id": "workspace:^",
"@deepseek-ai/dsh-app-boot": "workspace:^",
"@deepseek-ai/dsh-attachment": "workspace:^",
"@deepseek-ai/dsh-atomic-write": "workspace:^",
"@deepseek-ai/dsh-shell": "workspace:^",
"@deepseek-ai/dsh-shell-env": "workspace:^",
"@deepseek-ai/dsh-attachment": "workspace:^",
"@deepseek-ai/dsh-authorization": "workspace:^",
"@deepseek-ai/dsh-bash-local": "workspace:^",
"@deepseek-ai/dsh-brand": "workspace:^",
"@deepseek-ai/dsh-code-runtime": "workspace:^",
@@ -32,45 +34,44 @@
"@deepseek-ai/dsh-compaction-basic": "workspace:^",
"@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:^",
"@deepseek-ai/dsh-cordis-host-runner": "workspace:^",
"@deepseek-ai/dsh-authorization": "workspace:^",
"@deepseek-ai/dsh-credentials": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:^",
"@deepseek-ai/dsh-fs": "workspace:^",
"@deepseek-ai/dsh-fs-local": "workspace:^",
"@deepseek-ai/dsh-fs-observation-policy": "workspace:^",
"@deepseek-ai/dsh-fs-sandbox": "workspace:^",
"@deepseek-ai/dsh-goal": "workspace:^",
"@deepseek-ai/dsh-goal-round-driver": "workspace:^",
"@deepseek-ai/dsh-home-paths": "workspace:^",
"@deepseek-ai/dsh-hook-protocol": "workspace:^",
"@deepseek-ai/dsh-hooks-claude-code": "workspace:^",
"@deepseek-ai/dsh-hooks-codex": "workspace:^",
"@deepseek-ai/dsh-http-proxy": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-sdk-jsonrpc-server": "workspace:^",
"@deepseek-ai/dsh-jobs": "workspace:^",
"@deepseek-ai/dsh-jobs-local": "workspace:^",
"@deepseek-ai/dsh-launch-environment": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-llm-deepseek": "workspace:^",
"@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:^",
"@deepseek-ai/dsh-plugin-package-inventory-deepseek": "workspace:^",
"@deepseek-ai/dsh-session-log-deepseek": "workspace:^",
"@deepseek-ai/dsh-llm-pi-ai": "workspace:^",
"@deepseek-ai/dsh-llm-retry": "workspace:^",
"@deepseek-ai/dsh-mcp-client": "workspace:^",
"@deepseek-ai/dsh-home-paths": "workspace:^",
"@deepseek-ai/dsh-permission-presets": "workspace:^",
"@deepseek-ai/dsh-plan-mode": "workspace:^",
"@deepseek-ai/dsh-persona": "workspace:^",
"@deepseek-ai/dsh-pwsh-local": "workspace:^",
"@deepseek-ai/dsh-tool-pwsh-persistent": "workspace:^",
"@deepseek-ai/dsh-terminal": "workspace:^",
"@deepseek-ai/dsh-terminal-bash": "workspace:^",
"@deepseek-ai/dsh-repeat-tool-reminder": "workspace:^",
"@deepseek-ai/dsh-output-retention": "workspace:^",
"@deepseek-ai/dsh-permission-presets": "workspace:^",
"@deepseek-ai/dsh-persona": "workspace:^",
"@deepseek-ai/dsh-plan-mode": "workspace:^",
"@deepseek-ai/dsh-plugin-package-inventory-deepseek": "workspace:^",
"@deepseek-ai/dsh-pwsh-local": "workspace:^",
"@deepseek-ai/dsh-repeat-tool-reminder": "workspace:^",
"@deepseek-ai/dsh-sandbox": "workspace:^",
"@deepseek-ai/dsh-sandbox-local": "workspace:^",
"@deepseek-ai/dsh-sandbox-policy": "workspace:^",
"@deepseek-ai/dsh-scope": "workspace:^",
"@deepseek-ai/dsh-sdk-jsonrpc-server": "workspace:^",
"@deepseek-ai/dsh-sdk-protocol": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-session-checkpoint-policy": "workspace:^",
"@deepseek-ai/dsh-session-log-deepseek": "workspace:^",
"@deepseek-ai/dsh-session-persistence": "workspace:^",
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^",
"@deepseek-ai/dsh-session-persistence-sqlite": "workspace:^",
@@ -81,6 +82,8 @@
"@deepseek-ai/dsh-session-telemetry": "workspace:^",
"@deepseek-ai/dsh-session-title": "workspace:^",
"@deepseek-ai/dsh-settings": "workspace:^",
"@deepseek-ai/dsh-shell": "workspace:^",
"@deepseek-ai/dsh-shell-env": "workspace:^",
"@deepseek-ai/dsh-skill": "workspace:^",
"@deepseek-ai/dsh-skill-filesystem": "workspace:^",
"@deepseek-ai/dsh-spill": "workspace:^",
@@ -92,32 +95,32 @@
"@deepseek-ai/dsh-subprocess": "workspace:^",
"@deepseek-ai/dsh-subprocess-local": "workspace:^",
"@deepseek-ai/dsh-system-prompt": "workspace:^",
"@deepseek-ai/dsh-jobs": "workspace:^",
"@deepseek-ai/dsh-jobs-local": "workspace:^",
"@deepseek-ai/dsh-terminal": "workspace:^",
"@deepseek-ai/dsh-terminal-bash": "workspace:^",
"@deepseek-ai/dsh-timeout": "workspace:^",
"@deepseek-ai/dsh-tool-call-timeout-policy": "workspace:^",
"@deepseek-ai/dsh-token-meter": "workspace:^",
"@deepseek-ai/dsh-tool-ask-user": "workspace:^",
"@deepseek-ai/dsh-tool-bash": "workspace:^",
"@deepseek-ai/dsh-tool-bash-persistent": "workspace:^",
"@deepseek-ai/dsh-tool-call-timeout-policy": "workspace:^",
"@deepseek-ai/dsh-tool-cordis": "workspace:^",
"@deepseek-ai/dsh-tool-fs": "workspace:^",
"@deepseek-ai/dsh-tool-fs-search": "workspace:^",
"@deepseek-ai/dsh-tool-goal": "workspace:^",
"@deepseek-ai/dsh-tool-jobs": "workspace:^",
"@deepseek-ai/dsh-tool-pwsh": "workspace:^",
"@deepseek-ai/dsh-tool-pwsh-persistent": "workspace:^",
"@deepseek-ai/dsh-tool-ralph": "workspace:^",
"@deepseek-ai/dsh-tool-skill": "workspace:^",
"@deepseek-ai/dsh-tool-str-replace-editor": "workspace:^",
"@deepseek-ai/dsh-tool-subagent": "workspace:^",
"@deepseek-ai/dsh-tool-subagent-control": "workspace:^",
"@deepseek-ai/dsh-tool-jobs": "workspace:^",
"@deepseek-ai/dsh-tool-todo": "workspace:^",
"@deepseek-ai/dsh-tool-web": "workspace:^",
"@deepseek-ai/dsh-tool-workflow": "workspace:^",
"@deepseek-ai/dsh-tools": "workspace:^",
"@deepseek-ai/dsh-typert-protocol": "workspace:^",
"@deepseek-ai/dsh-user-approval": "workspace:^",
"@deepseek-ai/dsh-anonymous-user-id": "workspace:^",
"@deepseek-ai/dsh-user-questions": "workspace:^",
"@deepseek-ai/dsh-util-time": "workspace:^",
"@deepseek-ai/dsh-web": "workspace:^",
@@ -127,8 +130,6 @@
"@deepseek-ai/dsh-web-search-perplexity": "workspace:^",
"@deepseek-ai/dsh-workflow": "workspace:^",
"@deepseek-ai/dsh-workflow-worker-thread": "workspace:^",
"@deepseek-ai/dsh-agent-instructions": "workspace:^",
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/schemastery": "workspace:^"
}
}
+2
View File
@@ -286,6 +286,7 @@ function ciSharedStaticGates(): Gate[] {
}),
pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
pnpmScript('no-bare-dispatcher', 'verify-no-bare-dispatcher', { label: 'proxy-aware dispatchers' }),
pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
]
}
@@ -680,6 +681,7 @@ function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
}),
pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
pnpmScript('client-ui-i18n', 'verify-client-ui-i18n', { label: 'client UI i18n' }),
pnpmScript('no-bare-dispatcher', 'verify-no-bare-dispatcher', { label: 'proxy-aware dispatchers' }),
]
}
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest'
import { findDispatcherViolations, scanRepository, DISPATCHER_OWNER } from './verify-no-bare-dispatcher.ts'
const FILE = 'packages/web/web-fetch-http/src/network.ts'
function reasons(source: string, file = FILE): string[] {
return findDispatcherViolations(file, source).map(violation => violation.what)
}
describe('bare dispatcher check', () => {
it('rejects the shape that silently bypassed the proxy before this rule existed', () => {
expect(reasons(`
const dispatcher = new Agent({ connect: { lookup } })
const response = await fetch(url, { dispatcher })
`)).toEqual(['constructs an undici agent'])
})
it('rejects an explicit dispatcher option however the agent was obtained', () => {
expect(reasons(" const response = await fetch(url, { method: 'GET', dispatcher: pooled })"))
.toEqual(['passes an explicit `dispatcher`'])
})
it('rejects a namespaced construction', () => {
expect(reasons(' const agent = new undici.ProxyAgent(uri)')).toEqual(['constructs an undici agent'])
})
it('reports the offending line number and text', () => {
expect(findDispatcherViolations(FILE, 'const a = 1\nconst b = new Agent({})')).toEqual([
{ file: FILE, line: 2, what: 'constructs an undici agent', text: 'const b = new Agent({})' },
])
})
it('accepts the sanctioned factory', () => {
expect(reasons(' const dispatcher = await createDispatcher(url, options)')).toEqual([])
})
it('accepts an annotated exemption', () => {
expect(reasons(' const agent = new Agent({}) // proxy-exempt: loopback transport for the local test server'))
.toEqual([])
})
it('exempts the package that owns dispatcher construction', () => {
expect(reasons('const agent = new EnvHttpProxyAgent()', `${DISPATCHER_OWNER}src/install.ts`)).toEqual([])
})
it('normalizes native separators before exempting the owning package', () => {
expect(reasons('const agent = new Agent({})', DISPATCHER_OWNER.replaceAll('/', '\\') + 'src\\install.ts')).toEqual([])
})
it('passes on the current tree', () => {
expect(scanRepository()).toEqual([])
})
})
+91
View File
@@ -0,0 +1,91 @@
/**
* Verify that no package builds its own undici agent or hands `fetch` an explicit dispatcher.
*
* Node's built-in `fetch` routes through undici's global dispatcher, which `@deepseek-ai/dsh-http-proxy`
* installs at launch. An explicitly supplied `dispatcher` overrides that global one, so a call site
* that constructs `new Agent(...)` itself connects directly no matter what proxy the user configured
* — the exact defect `web-fetch-http` carried before proxy support existed, where its DNS-pinning
* agent silently bypassed every proxy.
*
* `createDispatcher()` from that package is the sanctioned way to get agent options AND the policy.
*/
import { globSync, readFileSync } from 'node:fs'
import { resolve } from 'node:path'
const root = resolve(import.meta.dirname, '..')
/** The package that owns dispatcher construction; its own agents are the implementation. */
export const DISPATCHER_OWNER = 'packages/net/http-proxy/'
/** A line carrying this marker states why it is exempt and is left alone. */
export const ALLOW_MARKER = 'proxy-exempt:'
/** Constructing an undici agent, or naming a `dispatcher` option, outside the owning package. */
const PATTERNS: readonly { readonly probe: RegExp; readonly what: string }[] = [
{ probe: /\bnew\s+(?:undici\.)?(?:Agent|ProxyAgent|EnvHttpProxyAgent)\s*\(/, what: 'constructs an undici agent' },
{ probe: /\bdispatcher\s*:/, what: 'passes an explicit `dispatcher`' },
]
/** One source line that would bypass the configured proxy. */
export interface DispatcherViolation {
/** Repository-relative path, in POSIX separators. */
readonly file: string
/** One-based line number. */
readonly line: number
/** Which rule the line broke. */
readonly what: string
/** The offending line, trimmed. */
readonly text: string
}
/**
* Find every bare-dispatcher line in one source file.
*
* @param file - repository-relative path, used to exempt the owning package and to report location.
* @param sourceText - the file's contents.
* @returns one violation per offending line, in file order.
*/
export function findDispatcherViolations(file: string, sourceText: string): DispatcherViolation[] {
const posix = file.replaceAll('\\', '/')
if (posix.startsWith(DISPATCHER_OWNER)) return []
const violations: DispatcherViolation[] = []
sourceText.split('\n').forEach((text, index) => {
if (text.includes(ALLOW_MARKER)) return
for (const { probe, what } of PATTERNS) {
if (probe.test(text)) violations.push({ file: posix, line: index + 1, what, text: text.trim() })
}
})
return violations
}
/**
* Scan every package and app source file in the repository.
*
* @returns every violation found, grouped by the order the files were scanned.
*/
export function scanRepository(): DispatcherViolation[] {
const files = [
...globSync('packages/*/*/src/**/*.ts', { cwd: root }),
...globSync('apps/*/src/**/*.ts', { cwd: root }),
]
return files.flatMap(file => findDispatcherViolations(file, readFileSync(resolve(root, file), 'utf8')))
}
function main(): void {
const violations = scanRepository()
if (violations.length === 0) {
console.log(`verify-no-bare-dispatcher: no bare dispatcher outside ${DISPATCHER_OWNER}.`)
return
}
console.error('verify-no-bare-dispatcher: a dispatcher built outside @deepseek-ai/dsh-http-proxy bypasses the configured proxy.\n')
for (const violation of violations) {
console.error(` ${violation.file}:${String(violation.line)} ${violation.what}`)
console.error(` ${violation.text}`)
}
console.error('\nUse `createDispatcher(url, options)` from @deepseek-ai/dsh-http-proxy, or annotate the line')
console.error(`with a \`${ALLOW_MARKER} <reason>\` comment when the request must genuinely ignore the proxy.`)
process.exit(1)
}
if (import.meta.filename === resolve(process.argv[1] ?? '')) main()
@@ -62,6 +62,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/typert/registry': { kind: 'none', reason: 'Runtime type registry; consumers (cordis_inspect, wire faces, gates) own any model-visible projection of registry contents.' },
'packages/typert/loader': { kind: 'none', reason: 'Loader integration only registers generated artifacts; consumers own any model-visible projection.' },
'packages/e2b/e2b': { kind: 'none', reason: 'The shared remote-runtime owner registers no model context; provider adapters and consumers own rendered effects.' },
'packages/net/http-proxy': { kind: 'none', reason: 'Transport policy only: it changes how bytes reach the network and registers no prompt, schema, or result text.' },
'packages/client/hmr': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
'packages/client/modules': { kind: 'none', reason: 'Browser-side module-loading kernel machinery; registers nothing model-facing.' },
'packages/test-support/client-runtime': { kind: 'none', reason: 'Browser-side test infrastructure (jsdom bench); registers nothing model-facing.' },
+1
View File
@@ -20,6 +20,7 @@ export const GROUPS_WITHOUT_SUBSYSTEM_PAGE: Readonly<Record<string, string>> = {
bundle: 'Composition patch carriers whose mounted packages own all runtime contracts.',
examples: 'Non-product demonstration compositions whose mounted packages own all runtime contracts.',
hooks: 'External hook-protocol bridges over existing interception points, not a new Harness service.',
net: 'Process-wide transport policy with no service, no seam, and no runtime vocabulary of its own; the user guide and the one package README own it.',
sdk: 'Out-of-process protocol and client packages whose package READMEs own the SDK contracts.',
util: 'Low-level primitives whose business semantics remain with their consuming subsystems.',
}
+2
View File
@@ -337,6 +337,8 @@
"@deepseek-ai/dsh-hooks-claude-code/invariant": ["./packages/hooks/hooks-claude-code/src/invariant.ts"],
"@deepseek-ai/dsh-hooks-codex": ["./packages/hooks/hooks-codex/src"],
"@deepseek-ai/dsh-hooks-codex/invariant": ["./packages/hooks/hooks-codex/src/invariant.ts"],
"@deepseek-ai/dsh-http-proxy": ["./packages/net/http-proxy/src"],
"@deepseek-ai/dsh-http-proxy/invariant": ["./packages/net/http-proxy/src/invariant.ts"],
"@deepseek-ai/dsh-invariants/invariant": ["./packages/runtime-diagnostics/invariants/src/invariant.ts"],
"@deepseek-ai/dsh-jobs": ["./packages/jobs/jobs/src"],
"@deepseek-ai/dsh-jobs/invariant": ["./packages/jobs/jobs/src/invariant.ts"],
+1
View File
@@ -127,6 +127,7 @@
{ "path": "./vendor/hmr" },
{ "path": "./vendor/logger-console" },
{ "path": "./packages/util/brand" },
{ "path": "./packages/net/http-proxy" },
{ "path": "./packages/util/launch-environment" },
{ "path": "./packages/util/native-command" },
{ "path": "./packages/util/home-paths" },
+8
View File
@@ -130,6 +130,14 @@ const homeAndGuide = pairedPages([
section: { root: '入门', en: 'Guide' },
order: 2,
},
{
source: 'docs/user/guide/network-proxy.md',
route: 'guide/network-proxy.md',
label: { root: '网络代理', en: 'Network proxy' },
sidebar: { root: 'zh-guide', en: 'en-guide' },
section: { root: '入门', en: 'Guide' },
order: 3,
},
{
source: 'docs/user/guide/python-sdk.md',
route: 'guide/python-sdk.md',