@alicloud/autowonder 0.3.43 → 0.3.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,10 +18,10 @@ Browser Use 的源码、测试、依赖和发布统一在本 runtime 仓库维
18
18
 
19
19
  ```bash
20
20
  # Qoder CLI(模型使用 provider model ID;Context Window 使用固定档位)
21
- npx -y @alicloud/autowonder@0.3.43 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qoder --model qmodel_latest --reasoning-effort medium --context-window 260000
21
+ npx -y @alicloud/autowonder@0.3.45 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qoder --model qmodel_latest --reasoning-effort medium --context-window 260000
22
22
 
23
23
  # Qoder CLI CN
24
- npx -y @alicloud/autowonder@0.3.43 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qodercn
24
+ npx -y @alicloud/autowonder@0.3.45 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qodercn
25
25
  ```
26
26
 
27
27
  `connect` 会安装当前 npm 包内置的 daemon,并使用页面生成的 WebSocket endpoint、Token 和执行器 ID 建立连接。客户端只支持通过 Qoder 系列 CLI 启动(`qoder` 对应 `qodercli`,`qodercn` 对应 `qodercn`),其他 `--provider` 取值会在启动 daemon 前直接报错拦截并提示 `Unsupported provider`。选择 Qoder CLI 或 Qoder CLI CN 时需要 Node.js 20+;runtime 会在缺少对应 CLI 时自动通过 npm 安装,并在尚未登录时打开浏览器登录。runtime 会继承当前用户的 HOME、环境变量和 CLI 登录状态。
@@ -195,7 +195,7 @@ daemon 默认启用显式发布边界(`explicit_refs_v1`):上传集合由
195
195
  - 服务端可在派单里下发更严格的限制(`artifactProtocolVersion` = 2,以及每请求文件数与字节数、单文件、文本证据单文件与总量上限);字段缺省时 runtime 使用保守默认值,旧服务端与旧执行器组合行为不变。
196
196
  - `AUTOWONDER_ARTIFACT_SELECTION_MODE=legacy_all_typed` 仅供平台 operator 在线上事故回滚时使用(设置后需重启 daemon),会恢复旧的目录级收集语义及其资源放大风险,问题解除后应立即移除;不得把它下发给客户 SDLC、Agent、Soul、提示词或 assignment 配置。
197
197
 
198
- checkpoint 使用 `autowonder.runtimeCheckpoint.v2`:相同 digest 的已发布字节只保存一份,恢复前在隔离 staging 中完整校验 manifest 与 payload 的对应关系。v2 reader 兼容历史 v1 checkpoint;旧版 runtime 会因 schema 不匹配拒绝 v2,需要回滚旧版时应选择保留的 v1 checkpoint,不能把 v2 改标成 v1。
198
+ checkpoint 默认使用 `autowonder.runtimeCheckpoint.lightweight.v1`:不保存仓库快照(不生成 git bundle),已发布字节只保留引用,未发布字节按 digest 只保存一份,恢复前在隔离 staging 中完整校验 manifest 与 payload 的对应关系。新 reader 兼容历史 v1/v2 checkpoint;旧版 runtime 会因 schema 不匹配拒绝新格式(服务端只把含新格式候选的恢复派给声明 `CHECKPOINT_LIGHTWEIGHT_V1` 的执行器,请先升级服务端再升级 runtime),需要回滚旧版时应选择保留的旧格式 checkpoint,不能把新格式改标成旧格式。
199
199
 
200
200
  ## 发布构建
201
201
 
@@ -217,7 +217,7 @@ mv "$queue/.assignment.tmp" "$queue/assignment.json"
217
217
  也可以直接提交到本地 API:
218
218
 
219
219
  ```bash
220
- npx -y @alicloud/autowonder@0.3.43 dispatch ./assignment.json
220
+ npx -y @alicloud/autowonder@0.3.45 dispatch ./assignment.json
221
221
  ```
222
222
 
223
223
  ## 上传工单附件
@@ -225,7 +225,7 @@ npx -y @alicloud/autowonder@0.3.43 dispatch ./assignment.json
225
225
  把本地需求/设计文档直接上传到工单,避免在会话里传递大文件:
226
226
 
227
227
  ```bash
228
- npx -y @alicloud/autowonder@0.3.43 workitem upload --server-url <autowonder-server-url> --workitem-id <id> --file <filepath-1> --file <filepath-2> --json
228
+ npx -y @alicloud/autowonder@0.3.45 workitem upload --server-url <autowonder-server-url> --workitem-id <id> --file <filepath-1> --file <filepath-2> --json
229
229
  ```
230
230
 
231
231
  上传令牌通过 MCP 工具 `autowonder.workitem_cli_upload_token` 签发,经 `--token` 或 `AUTOWONDER_UPLOAD_TOKEN` 环境变量传入。`--file` 可重复指定多个文件;`--json` 输出机器可读结果。失败时按错误类型返回不同退出码(401→3、403→4、404→5、409→6、413→7、其他 4xx→8、网络/重定向→9)。
@@ -235,7 +235,7 @@ npx -y @alicloud/autowonder@0.3.43 workitem upload --server-url <autowonder-serv
235
235
  把工单上已有的需求/设计文档下载到本地目录,再用本地文件工具阅读,避免把大文件或二进制附件搬进会话上下文:
236
236
 
237
237
  ```bash
238
- npx -y @alicloud/autowonder@0.3.43 workitem download --server-url <autowonder-server-url> --workitem-id <id> --file <name-or-id> --output-dir <dir> --json
238
+ npx -y @alicloud/autowonder@0.3.45 workitem download --server-url <autowonder-server-url> --workitem-id <id> --file <name-or-id> --output-dir <dir> --json
239
239
  ```
240
240
 
241
241
  下载令牌通过 MCP 工具 `autowonder.workitem_cli_download_token` 签发(与上传令牌相互独立),经 `--token` 或 `AUTOWONDER_DOWNLOAD_TOKEN` 环境变量传入。`--file` 可重复指定文档名或 artifact id,省略则下载该工单的全部附件;`--output-dir` 默认为当前目录;`--json` 输出机器可读结果,含每个文件的 `id`、`name`、`path`、`size`。退出码约定与 `workitem upload` 相同(401→3、403→4、404→5、409→6、413→7、其他 4xx→8、网络/重定向→9)。
@@ -245,7 +245,7 @@ npx -y @alicloud/autowonder@0.3.43 workitem download --server-url <autowonder-se
245
245
  把需求/设计文档上传到 7x24 定时任务,用法与工单附件一致(同一套上传令牌与预检规则):
246
246
 
247
247
  ```bash
248
- npx -y @alicloud/autowonder@0.3.43 scheduled-task upload --server-url <autowonder-server-url> --scheduled-task-id <id> --file <filepath-1> --file <filepath-2> --json
248
+ npx -y @alicloud/autowonder@0.3.45 scheduled-task upload --server-url <autowonder-server-url> --scheduled-task-id <id> --file <filepath-1> --file <filepath-2> --json
249
249
  ```
250
250
 
251
251
  上传令牌同样通过 `autowonder.workitem_cli_upload_token` 签发(令牌为用户级,对当前可修改的任意定时任务生效),经 `--token` 或 `AUTOWONDER_UPLOAD_TOKEN` 传入;退出码约定与 `workitem upload` 相同。
@@ -253,8 +253,8 @@ npx -y @alicloud/autowonder@0.3.43 scheduled-task upload --server-url <autowonde
253
253
  ## 管理 daemon
254
254
 
255
255
  ```bash
256
- npx -y @alicloud/autowonder@0.3.43 status
257
- npx -y @alicloud/autowonder@0.3.43 stop
256
+ npx -y @alicloud/autowonder@0.3.45 status
257
+ npx -y @alicloud/autowonder@0.3.45 stop
258
258
  ```
259
259
 
260
260
  默认 API 是 `http://127.0.0.1:34989`,日志位于 `~/.autowonder/daemon.log`。npm 包不包含任何 agent、MCP 或服务端凭证。
@@ -277,7 +277,7 @@ daemon 内置独立于工作区 GC 的保留清扫:默认每小时运行一次
277
277
  ## 调试
278
278
 
279
279
  ```bash
280
- npx -y @alicloud/autowonder@0.3.43 connect ... --debug
280
+ npx -y @alicloud/autowonder@0.3.45 connect ... --debug
281
281
  ```
282
282
 
283
283
  `--debug` 会让 CLI 以 `AUTOWONDER_DEBUG=1` 启动 daemon,把完整的 daemon 与 agent 活动(runtime 事件流、provider 事件解码、重试退避与会话门等待、空闲时的阻塞点)同时输出到控制台和会话调试日志。调试日志不做脱敏,仅用于本机排障;不传 `--debug` 时该环境变量不会注入。
package/bin/cli.js CHANGED
@@ -519,6 +519,9 @@ async function cmdConnect(args) {
519
519
  env.AUTOWONDER_TOKEN_PROXY_PORT = String(proxy.port);
520
520
  env.AUTOWONDER_TOKEN_PROXY_MANAGED = "1";
521
521
  env.AUTOWONDER_TOKEN_PROXY_LEGACY_ALLOWED = "1";
522
+ // Capability, not version: a healthy legacy/older shared listener answers
523
+ // 405 to plain HTTP, so it must never receive HTTP_PROXY traffic.
524
+ env.AUTOWONDER_TOKEN_PROXY_HTTP_FORWARD = ready && ready.httpForward === true ? "1" : "0";
522
525
  env.AUTOWONDER_TOKEN_PROXY_BASE_DIR = proxy.baseDir;
523
526
  env.AUTOWONDER_TOKEN_PROXY_NODE_PATH = process.execPath;
524
527
  env.AUTOWONDER_TOKEN_PROXY_SCRIPT_PATH = path.join(__dirname, "token-proxy.js");
@@ -3,26 +3,69 @@ const path = require('path');
3
3
  const crypto = require('crypto');
4
4
  const { configuration, HEALTH_PATH, SERVICE } = require('./token-proxy-manager');
5
5
  const { ensureManagedCA, resolveOpenSSL } = require('./token-proxy-ca');
6
- async function startManagedProxy(port) {
7
- const { createProxyServer, getHostCert, createRotatingWriter, installDiagLog } = require('./token-proxy');
8
- const cfg = configuration({ port, dataDir: process.env.AUTOWONDER_TOKEN_PROXY_BASE_DIR });
9
- let ca, state = 'starting', retry = 0, timer, closed = false, failure = '', writer;
10
- const instanceId = crypto.randomUUID();
11
- const server = createProxyServer({ ca: {}, hostCertificate: host => getHostCert(host, ca) });
12
- const handlers = server.listeners('connect');
6
+
7
+ // wrapProxyServer adds the shared-service health endpoint and refuses work while
8
+ // the managed CA is not ready. It wraps the proxy's own connect/request/upgrade
9
+ // handlers instead of replacing them: replacing the request handler is what made
10
+ // every plain-HTTP request (the platform-injected HTTP MCP endpoint) fail with
11
+ // 405 even though the proxy could forward it.
12
+ function wrapProxyServer(server, status) {
13
+ const connectHandlers = server.listeners('connect');
13
14
  server.removeAllListeners('connect');
14
15
  server.on('connect', (...args) => {
15
- if (state !== 'ready') { args[1].end('HTTP/1.1 503 TokenProxy recovering\r\nConnection: close\r\n\r\n'); return; }
16
- for (const handler of handlers) handler(...args);
16
+ if (status().state !== 'ready') { args[1].end('HTTP/1.1 503 TokenProxy recovering\r\nConnection: close\r\n\r\n'); return; }
17
+ for (const handler of connectHandlers) handler(...args);
17
18
  });
19
+ const requestHandlers = server.listeners('request');
18
20
  server.removeAllListeners('request');
19
21
  server.on('request', (req, res) => {
20
- if (req.method !== 'GET' || req.url !== HEALTH_PATH) { res.writeHead(405); res.end(); return; }
21
- res.setHeader('Content-Type', 'application/json');
22
- res.setHeader('Cache-Control', 'no-store');
23
- res.end(JSON.stringify({ service: SERVICE, protocol: 1, scope: cfg.scope, state, instanceId,
24
- pid: process.pid, fingerprint: ca && ca.fingerprint, generation: ca && ca.generation, error: failure }));
22
+ const current = status();
23
+ if (req.method === 'GET' && req.url === HEALTH_PATH) {
24
+ res.setHeader('Content-Type', 'application/json');
25
+ res.setHeader('Cache-Control', 'no-store');
26
+ res.end(JSON.stringify(current.health));
27
+ return;
28
+ }
29
+ if (current.state !== 'ready') {
30
+ res.writeHead(503, { 'Content-Type': 'text/plain', Connection: 'close' });
31
+ res.end('TokenProxy recovering');
32
+ return;
33
+ }
34
+ for (const handler of requestHandlers) handler(req, res);
25
35
  });
36
+ const upgradeHandlers = server.listeners('upgrade');
37
+ server.removeAllListeners('upgrade');
38
+ server.on('upgrade', (req, socket, head) => {
39
+ if (status().state !== 'ready') { socket.end('HTTP/1.1 503 TokenProxy recovering\r\nConnection: close\r\n\r\n'); return; }
40
+ for (const handler of upgradeHandlers) handler(req, socket, head);
41
+ });
42
+ return server;
43
+ }
44
+
45
+ // proxyHealth is the shared proxy's advertisement. httpForward is a capability
46
+ // flag: a daemon must not route plain HTTP into a listener that cannot forward
47
+ // it, which is exactly what older shared proxies do (405 Only CONNECT supported).
48
+ function proxyHealth({ cfg, state, instanceId, ca, failure }) {
49
+ return {
50
+ service: SERVICE, protocol: 1, scope: cfg.scope, state, instanceId,
51
+ pid: process.pid, fingerprint: ca && ca.fingerprint, generation: ca && ca.generation,
52
+ error: failure, httpForward: true,
53
+ };
54
+ }
55
+
56
+ async function startManagedProxy(port) {
57
+ const { createProxyServer, getHostCert, createRotatingWriter, installDiagLog, createProxyIdentity } = require('./token-proxy');
58
+ const cfg = configuration({ port, dataDir: process.env.AUTOWONDER_TOKEN_PROXY_BASE_DIR });
59
+ let ca, state = 'starting', retry = 0, timer, closed = false, failure = '', writer;
60
+ const instanceId = crypto.randomUUID();
61
+ // Diagnostics carry the same instance id the health endpoint advertises, so a
62
+ // line can be matched to the listener that wrote it after an upgrade.
63
+ const server = createProxyServer({ ca: {}, hostCertificate: host => getHostCert(host, ca),
64
+ identity: createProxyIdentity({ instance: instanceId }) });
65
+ wrapProxyServer(server, () => ({
66
+ state,
67
+ health: proxyHealth({ cfg, state, instanceId, ca, failure }),
68
+ }));
26
69
  server.on('error', e => {
27
70
  // Losing a bind race is normal; losers never touch shared CA/log files.
28
71
  if (e.code !== 'EADDRINUSE') console.error(`[token-proxy] listen failed: ${e.code || e.message}`);
@@ -54,4 +97,4 @@ async function startManagedProxy(port) {
54
97
  await maintain();
55
98
  return server;
56
99
  }
57
- module.exports = { startManagedProxy };
100
+ module.exports = { startManagedProxy, wrapProxyServer, proxyHealth };
@@ -3,8 +3,9 @@
3
3
  * token-proxy.js — Qoder/QoderCN token usage 旁路采集 proxy
4
4
  *
5
5
  * 单文件,零 npm 依赖,仅用 Node 内置模块。
6
- * 作为 HTTPS forward proxy 运行,透传所有流量,从 Qoder API 的 SSE 响应中
7
- * 提取 token usage 数据写入 JSONL 文件。
6
+ * 作为 forward proxy 运行,透传所有流量,从 Qoder API 的 SSE 响应中
7
+ * 提取 token usage 数据写入 JSONL 文件。HTTPS 走 CONNECT 隧道,普通 HTTP
8
+ * 请求(absolute-form)按原方法/路径/头/体转发,支持 SSE 与 Upgrade。
8
9
  *
9
10
  * 用法:
10
11
  * node token-proxy.js start [--port 19876] 启动 proxy
@@ -13,8 +14,9 @@
13
14
  *
14
15
  * 降级策略:
15
16
  * - 所有解析逻辑被 try-catch 包裹,解析失败只丢 token 数据,不断流量
16
- * - proxy 启动失败时,wrapper 不注入 HTTPS_PROXY,daemon 正常直连
17
+ * - proxy 启动失败时,wrapper 不注入代理变量,daemon 正常直连
17
18
  * - 运行中的代理连接失败会关闭隧道,由客户端处理重试;不承诺自动直连
19
+ * - 普通 HTTP 转发失败返回 502,不伪造目标响应
18
20
  */
19
21
 
20
22
  'use strict';
@@ -168,6 +170,34 @@ function installDiagLog(logPath = DIAG_LOG_PATH) {
168
170
  return writer;
169
171
  }
170
172
 
173
+ // ─── Proxy instance identity ─────────────────────────────────────────────────
174
+
175
+ // Recovery reuses a verified listener whose script an earlier release installed,
176
+ // so a diagnostic line is only attributable when it names the process and the
177
+ // script revision that wrote it. The digest separates "still the old proxy"
178
+ // from "the installed script misbehaves".
179
+ function scriptRevision(file = __filename) {
180
+ try {
181
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex').slice(0, 12);
182
+ } catch (_) {
183
+ return 'unknown';
184
+ }
185
+ }
186
+
187
+ function createProxyIdentity({ instance } = {}) {
188
+ return {
189
+ pid: process.pid,
190
+ instance: instance || `${process.pid}-${crypto.randomBytes(4).toString('hex')}`,
191
+ revision: scriptRevision(),
192
+ };
193
+ }
194
+
195
+ function instanceTag(identity) {
196
+ return `pid=${identity.pid} instance=${identity.instance} rev=${identity.revision}`;
197
+ }
198
+
199
+ const DEFAULT_IDENTITY = createProxyIdentity();
200
+
171
201
  // ─── CA Certificate (auto-generated, only for this proxy) ────────────────────
172
202
 
173
203
  // readCertPair rejects missing, zero-byte and unparsable pairs so a partial
@@ -815,39 +845,103 @@ function createLineScanner(onLine, { maxLineBytes = DEFAULT_MAX_LINE_BYTES } = {
815
845
 
816
846
  // ─── Forward Proxy (CONNECT method) ─────────────────────────────────────────
817
847
 
848
+ // The same ECONNRESET can mean a client cancellation or a broken upstream.
849
+ // Only an error on the client socket, or an upstream error after an observed
850
+ // client close, proves client teardown. A request half-close is not cancellation.
851
+ const PEER_TEARDOWN_CODES = new Set(['EPIPE', 'ECONNRESET']);
852
+ const PEER_TEARDOWN_TEXT = /socket disconnected before secure TLS connection|client network socket disconnected|socket hang up/i;
853
+
854
+ function isPeerTeardown(error, { side, clientClosed = false } = {}) {
855
+ if (!error) return false;
856
+ if (PEER_TEARDOWN_CODES.has(String(error.code || ''))) return clientClosed || side === 'client';
857
+ return clientClosed && PEER_TEARDOWN_TEXT.test(String(error.message || error));
858
+ }
859
+
860
+ // tunnelDiagnostic keeps genuine tunnel/TLS failures as errors and reports a
861
+ // peer-initiated teardown as a closed connection instead.
862
+ function tunnelDiagnostic(label, error, context) {
863
+ const detail = String((error && error.message) || error || 'unknown error').split('\n')[0].slice(0, 200);
864
+ return isPeerTeardown(error, context) ? `${label} closed: ${detail}` : `${label} error: ${detail}`;
865
+ }
866
+
867
+ // connectionDiagnostic adds the connection's side and handshake phase so a line
868
+ // can be attributed without the raw socket state. A local idle timeout is the
869
+ // proxy reclaiming a silent socket: it is neither a peer teardown nor evidence
870
+ // of an upstream TLS failure, so it keeps its own keyword instead of the
871
+ // `error:` wording the upgrade gate counts as a regression.
872
+ function connectionDiagnostic(label, error, { side, phase, cause, clientClosed, setupComplete } = {}) {
873
+ const detail = String((error && error.message) || error || 'unknown error').split('\n')[0].slice(0, 200);
874
+ const body = cause === 'idle-timeout' ? `${label} idle-timeout: ${detail}` : tunnelDiagnostic(label, error, { side, clientClosed, setupComplete });
875
+ return [body, side && `side=${side}`,
876
+ clientClosed !== undefined && `clientClosed=${clientClosed}`, phase && `phase=${phase}`].filter(Boolean).join(' ');
877
+ }
878
+
818
879
  // Bound connection setup separately from idle time: a peer can trickle bytes
819
880
  // during TLS negotiation, so a socket inactivity timeout alone is insufficient.
820
- function guardConnection(sockets, { readyEvents, connectTimeoutMs = 15000,
821
- idleTimeoutMs = 120000, onCleanup = () => {}, onError = () => {} }) {
881
+ // `sides` labels the sockets; cleanup receives the cause that closed the pair.
882
+ function guardConnection(sockets, { readyEvents, sides = ['client', 'upstream'], connectTimeoutMs = 15000,
883
+ idleTimeoutMs = 120000, onCleanup = () => {}, onError = () => {}, clientSocket = sockets[0],
884
+ clientHasData = () => true }) {
822
885
  let closed = false;
886
+ let clientClosed = false;
887
+ let reason = 'closed';
823
888
  const pending = new Set(sockets);
824
- const cleanup = () => {
889
+ const cleanup = cause => {
825
890
  if (closed) return;
826
891
  closed = true;
892
+ if (typeof cause === 'string') reason = cause;
827
893
  clearTimeout(connectTimer);
828
894
  for (const socket of sockets) {
829
895
  socket.setTimeout(0);
830
896
  socket.destroy();
831
897
  }
832
- onCleanup();
898
+ onCleanup(reason);
899
+ };
900
+ // One cause decides the connection: errors that its own destroy provokes on
901
+ // the other half (an unfinished TLS handshake reporting a disconnect after a
902
+ // local idle timeout, say) are lifecycle fallout, not separate failures.
903
+ const report = (socket, cause, error, phase) => {
904
+ if (closed) return;
905
+ const side = socket ? (sides[sockets.indexOf(socket)] || 'connection') : 'connection';
906
+ onError(error, { side, phase: phase || (socket && pending.has(socket) ? 'setup' : 'forwarding'), cause,
907
+ clientClosed: clientClosed || !!clientSocket.destroyed, setupComplete: pending.size === 0 });
833
908
  };
834
909
  const connectTimer = setTimeout(() => {
835
- onError(new Error('proxy connection setup timed out'));
836
- cleanup();
910
+ report(null, 'setup-timeout', new Error('proxy connection setup timed out'), 'setup');
911
+ cleanup('setup-timeout');
837
912
  }, connectTimeoutMs);
838
913
  connectTimer.unref();
839
914
  sockets.forEach((socket, i) => {
840
915
  socket.setTimeout(idleTimeoutMs);
841
916
  socket.on('timeout', () => {
842
- onError(new Error('proxy connection idle timeout'));
843
- cleanup();
917
+ report(socket, 'idle-timeout', new Error('proxy connection idle timeout'));
918
+ cleanup('idle-timeout');
919
+ });
920
+ socket.on('close', () => {
921
+ if (i === 0) clientClosed = true;
922
+ cleanup('peer-close');
923
+ });
924
+ socket.on('error', error => {
925
+ report(socket, 'socket-error', error);
926
+ cleanup(isPeerTeardown(error, { side: sides[i],
927
+ clientClosed: clientClosed || !!clientSocket.destroyed }) ? 'peer-teardown' : 'socket-error');
844
928
  });
845
- socket.on('close', cleanup);
846
- socket.on('error', error => { onError(error); cleanup(); });
847
929
  // Flush queued bytes before closing the other half. The idle timer still
848
930
  // bounds a peer that never completes shutdown.
849
931
  socket.on('end', () => {
850
- for (const peer of sockets) if (peer !== socket) peer.end();
932
+ if (closed) return;
933
+ // EOF before the client TLS handshake completes is an aborted CONNECT,
934
+ // not a request half-close. Do not .end() a still-handshaking upstream:
935
+ // Node then synthesizes ECONNRESET for that locally initiated shutdown.
936
+ if (i === 0 && (pending.has(socket) || !clientHasData())) { cleanup(); return; }
937
+ sockets.forEach((peer, peerIndex) => {
938
+ if (peer === socket) return;
939
+ const end = () => { if (!closed && !peer.destroyed) peer.end(); };
940
+ // Preserve half-close, but do not end TLS before secureConnect. Node
941
+ // can otherwise report our shutdown as a failed upstream handshake.
942
+ if (pending.has(peer)) peer.once(readyEvents[peerIndex], end);
943
+ else end();
944
+ });
851
945
  });
852
946
  const readyEvent = readyEvents[i];
853
947
  if (!readyEvent) pending.delete(socket);
@@ -856,19 +950,211 @@ function guardConnection(sockets, { readyEvents, connectTimeoutMs = 15000,
856
950
  if (!pending.size) clearTimeout(connectTimer);
857
951
  });
858
952
  });
953
+ // A TLSSocket may not emit its own close before tlsUpstream reports the
954
+ // reset caused by aborting the underlying CONNECT socket during setup.
955
+ // Observe that raw socket too, and fence late errors after pair cleanup.
956
+ if (clientSocket !== sockets[0]) {
957
+ clientSocket.on('end', () => {
958
+ if (pending.has(sockets[0]) || !clientHasData()) { clientClosed = true; cleanup(); }
959
+ });
960
+ clientSocket.on('close', () => { clientClosed = true; cleanup(); });
961
+ clientSocket.on('error', error => {
962
+ if (closed) return;
963
+ report(sockets[0], 'socket-error', error);
964
+ cleanup(isPeerTeardown(error, { side: 'client', clientClosed: true }) ? 'peer-teardown' : 'socket-error');
965
+ });
966
+ }
859
967
  if (!pending.size) clearTimeout(connectTimer);
860
968
  return cleanup;
861
969
  }
862
970
 
971
+ // ─── Plain HTTP forwarding ──────────────────────────────────────────────────
972
+
973
+ // A proxy client sends absolute-form targets for plain http:// requests
974
+ // (RFC 7230 §5.3.2). Origin-form requests keep the historical 405: they carry
975
+ // no origin port, the shared-proxy probe classifies that reply as "legacy", and
976
+ // forwarding them could loop a request back into this listener.
977
+ const HOP_BY_HOP_HEADERS = new Set([
978
+ 'connection', 'proxy-connection', 'keep-alive', 'proxy-authenticate',
979
+ 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade',
980
+ ]);
981
+
982
+ // Default inactivity limit for CONNECT tunnels, forwarded plain-HTTP requests
983
+ // and upgraded sockets. It bounds silence, not connection lifetime: MCP SSE and
984
+ // WebSocket peers stay quiet between messages, so the old two-minute limit
985
+ // killed healthy traffic that simply had nothing to say.
986
+ const DEFAULT_IDLE_MS = 600000;
987
+
988
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);
989
+
990
+ // Target names this proxy's own listener when it is loopback on the bound port;
991
+ // relaying it would bounce the request until the idle deadline.
992
+ function isOwnListener(resolved, port) {
993
+ return port !== null && port !== undefined && resolved.port === port && LOOPBACK_HOSTS.has(resolved.hostname.toLowerCase());
994
+ }
995
+
996
+ function proxyRequestTarget(raw) {
997
+ const value = String(raw || '');
998
+ if (!/^http:\/\//i.test(value)) return null;
999
+ let parsed;
1000
+ try { parsed = new URL(value); } catch (_) { return null; }
1001
+ if (!parsed.hostname) return null;
1002
+ return {
1003
+ hostname: parsed.hostname.replace(/^\[(.*)\]$/, '$1'),
1004
+ port: parsed.port ? Number(parsed.port) : 80,
1005
+ path: `${parsed.pathname || '/'}${parsed.search}`,
1006
+ };
1007
+ }
1008
+
1009
+ // Hop-by-hop headers are single-connection and must never be relayed. This also
1010
+ // drops the credentials this proxy was given, so Proxy-Authorization cannot
1011
+ // leak to the target site after per-step attribution used it locally.
1012
+ function withoutHopByHop(headers) {
1013
+ const named = new Set(String(headers.connection || '').toLowerCase().split(',')
1014
+ .map(value => value.trim()).filter(Boolean));
1015
+ const relayed = {};
1016
+ for (const [name, value] of Object.entries(headers)) {
1017
+ const lower = name.toLowerCase();
1018
+ if (HOP_BY_HOP_HEADERS.has(lower) || named.has(lower)) continue;
1019
+ relayed[name] = value;
1020
+ }
1021
+ return relayed;
1022
+ }
1023
+
1024
+ function rawHead(statusCode, statusMessage, rawHeaders) {
1025
+ let head = `HTTP/1.1 ${statusCode} ${statusMessage || ''}\r\n`;
1026
+ for (let i = 0; i < rawHeaders.length; i += 2) head += `${rawHeaders[i]}: ${rawHeaders[i + 1]}\r\n`;
1027
+ return head + '\r\n';
1028
+ }
1029
+
1030
+ // createPlainHTTPForwarder relays absolute-form plain-HTTP proxy requests.
1031
+ // Method, path, business headers, body, status and response bytes are preserved
1032
+ // verbatim: redirects are never followed and bodies are never decoded or
1033
+ // rewritten. Both directions use stream pipe, so backpressure is the socket's.
1034
+ function createPlainHTTPForwarder({ connectTimeoutMs = 15000, idleTimeoutMs = DEFAULT_IDLE_MS,
1035
+ target = proxyRequestTarget, isSelfTarget = () => false, onError = () => {} } = {}) {
1036
+ function connect(req, resolved, headers) {
1037
+ const upstream = http.request({
1038
+ host: resolved.hostname, port: resolved.port, method: req.method,
1039
+ path: resolved.path, headers, agent: false,
1040
+ });
1041
+ upstream.setTimeout(connectTimeoutMs, () => {
1042
+ upstream.destroy(Object.assign(new Error('proxy upstream connect timed out'), { code: 'ETIMEDOUT' }));
1043
+ });
1044
+ upstream.on('socket', socket => {
1045
+ if (socket.connecting) socket.once('connect', () => upstream.setTimeout(idleTimeoutMs));
1046
+ else upstream.setTimeout(idleTimeoutMs);
1047
+ });
1048
+ return upstream;
1049
+ }
1050
+
1051
+ function forward(req, res) {
1052
+ const resolved = target(req.url);
1053
+ if (!resolved) {
1054
+ res.writeHead(405, { 'Content-Type': 'text/plain', Connection: 'close' });
1055
+ res.end('Only CONNECT supported');
1056
+ return;
1057
+ }
1058
+ if (isSelfTarget(resolved)) {
1059
+ res.writeHead(400, { 'Content-Type': 'text/plain', Connection: 'close' });
1060
+ res.end('proxy forwarding loop refused');
1061
+ return;
1062
+ }
1063
+ let answered = false;
1064
+ const upstream = connect(req, resolved, withoutHopByHop(req.headers));
1065
+ const fail = error => {
1066
+ onError(error);
1067
+ if (answered) return;
1068
+ answered = true;
1069
+ try {
1070
+ res.writeHead(502, { 'Content-Type': 'text/plain', Connection: 'close' });
1071
+ res.end('TokenProxy could not reach the target');
1072
+ } catch (_) {}
1073
+ };
1074
+ upstream.on('continue', () => { try { res.writeContinue(); } catch (_) {} });
1075
+ upstream.on('error', fail);
1076
+ upstream.on('response', upstreamRes => {
1077
+ answered = true;
1078
+ try {
1079
+ res.writeHead(upstreamRes.statusCode, upstreamRes.statusMessage || undefined, withoutHopByHop(upstreamRes.headers));
1080
+ // Headers first: an SSE client must see the stream open before the
1081
+ // first event arrives.
1082
+ res.flushHeaders();
1083
+ } catch (error) {
1084
+ fail(error);
1085
+ upstreamRes.destroy();
1086
+ return;
1087
+ }
1088
+ upstreamRes.on('error', error => { onError(error); res.destroy(); });
1089
+ upstreamRes.pipe(res);
1090
+ });
1091
+ req.on('aborted', () => upstream.destroy());
1092
+ req.pipe(upstream);
1093
+ res.on('close', () => { if (!res.writableFinished) upstream.destroy(); });
1094
+ }
1095
+
1096
+ // The switch itself travels as hop-by-hop headers, so they are re-added here
1097
+ // after the shared filter removed them.
1098
+ function forwardUpgrade(req, clientSocket, head) {
1099
+ const resolved = target(req.url);
1100
+ if (!resolved) {
1101
+ clientSocket.end('HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');
1102
+ return;
1103
+ }
1104
+ if (isSelfTarget(resolved)) {
1105
+ clientSocket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');
1106
+ return;
1107
+ }
1108
+ const headers = withoutHopByHop(req.headers);
1109
+ headers.connection = 'Upgrade';
1110
+ if (req.headers.upgrade) headers.upgrade = req.headers.upgrade;
1111
+ const upstream = connect(req, resolved, headers);
1112
+ upstream.on('upgrade', (upstreamRes, upstreamSocket, upstreamHead) => {
1113
+ clientSocket.write(rawHead(upstreamRes.statusCode, upstreamRes.statusMessage || 'Switching Protocols', upstreamRes.rawHeaders));
1114
+ if (upstreamHead && upstreamHead.length) clientSocket.write(upstreamHead);
1115
+ for (const socket of [clientSocket, upstreamSocket]) {
1116
+ socket.setTimeout(idleTimeoutMs);
1117
+ socket.on('error', error => { onError(error); socket.destroy(); });
1118
+ }
1119
+ if (head && head.length) upstreamSocket.write(head);
1120
+ upstreamSocket.pipe(clientSocket);
1121
+ clientSocket.pipe(upstreamSocket);
1122
+ });
1123
+ // A refused switch is an ordinary response; relay it instead of hiding it.
1124
+ upstream.on('response', upstreamRes => {
1125
+ clientSocket.write(rawHead(upstreamRes.statusCode, upstreamRes.statusMessage, upstreamRes.rawHeaders));
1126
+ upstreamRes.pipe(clientSocket);
1127
+ upstreamRes.on('end', () => clientSocket.end());
1128
+ });
1129
+ upstream.on('error', error => {
1130
+ onError(error);
1131
+ clientSocket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');
1132
+ });
1133
+ clientSocket.on('error', () => upstream.destroy());
1134
+ clientSocket.on('close', () => upstream.destroy());
1135
+ upstream.end();
1136
+ }
1137
+
1138
+ return { forward, forwardUpgrade };
1139
+ }
1140
+
863
1141
  function createProxyServer({ ca = ensureCA(), hostCertificate = getHostCert,
864
- connectTimeoutMs = 15000, idleTimeoutMs = 120000, sniffHosts = SNIFF_HOSTS,
865
- sniffSuffixes = SNIFF_HOST_SUFFIXES } = {}) {
1142
+ connectTimeoutMs = 15000, idleTimeoutMs = DEFAULT_IDLE_MS, sniffHosts = SNIFF_HOSTS,
1143
+ sniffSuffixes = SNIFF_HOST_SUFFIXES, identity = DEFAULT_IDENTITY } = {}) {
866
1144
  const dbg = DEBUG ? (...args) => console.log(...args) : () => {};
1145
+ const tag = instanceTag(identity);
867
1146
 
868
- const server = http.createServer((req, res) => {
869
- // Non-CONNECT requests: reject (we only handle CONNECT tunnels)
870
- res.writeHead(405);
871
- res.end('Only CONNECT supported');
1147
+ let listeningPort = null;
1148
+ const forwarder = createPlainHTTPForwarder({
1149
+ connectTimeoutMs, idleTimeoutMs,
1150
+ isSelfTarget: resolved => isOwnListener(resolved, listeningPort),
1151
+ onError: error => dbg(`[plain-http] ${String(error && error.message || error).split('\n')[0]}`),
1152
+ });
1153
+ const server = http.createServer((req, res) => forwarder.forward(req, res));
1154
+ server.on('upgrade', (req, clientSocket, head) => forwarder.forwardUpgrade(req, clientSocket, head));
1155
+ server.on('listening', () => {
1156
+ const address = server.address();
1157
+ listeningPort = address && typeof address === 'object' ? address.port : null;
872
1158
  });
873
1159
 
874
1160
  let connSeq = 0;
@@ -880,27 +1166,28 @@ function createProxyServer({ ca = ensureCA(), hostCertificate = getHostCert,
880
1166
  const shouldSniff = shouldSniffHost(hostname, sniffHosts, sniffSuffixes);
881
1167
  const { dispatchId, stepId } = extractDispatchInfo(req);
882
1168
 
883
- dbg(`[${ts()}] CONNECT #${seq} ${hostname}:${remotePort} sniff=${shouldSniff} dispatch=${dispatchId || 'none'} step=${stepId || 'none'}`);
1169
+ dbg(`[${ts()}] CONNECT #${seq} ${hostname}:${remotePort} sniff=${shouldSniff} dispatch=${dispatchId || 'none'} step=${stepId || 'none'} ${tag}`);
884
1170
 
885
1171
  const hostCert = shouldSniff ? hostCertificate(hostname, ca) : null;
886
1172
  if (!hostCert) {
887
- dbg(`[${ts()}] #${seq} → BLIND TUNNEL`);
1173
+ dbg(`[${ts()}] #${seq} → BLIND TUNNEL ${tag}`);
888
1174
  const upstream = net.connect(remotePort, hostname);
889
1175
  guardConnection([clientSocket, upstream], {
890
- readyEvents: [null, 'connect'], connectTimeoutMs, idleTimeoutMs,
891
- onError: e => dbg(`[${ts()}] #${seq} tunnel error: ${e.message}`),
1176
+ readyEvents: [null, 'connect'], sides: ['client', 'upstream'], connectTimeoutMs, idleTimeoutMs,
1177
+ onError: (e, info) => dbg(`[${ts()}] #${seq} ${connectionDiagnostic('tunnel', e, info)} ${tag}`),
892
1178
  });
893
1179
  upstream.once('connect', () => {
894
1180
  if (clientSocket.destroyed) return;
895
1181
  clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
896
1182
  if (head.length) upstream.write(head);
897
- upstream.pipe(clientSocket);
898
- clientSocket.pipe(upstream);
1183
+ // guardConnection owns half-close, including setup races.
1184
+ upstream.pipe(clientSocket, { end: false });
1185
+ clientSocket.pipe(upstream, { end: false });
899
1186
  });
900
1187
  return;
901
1188
  }
902
1189
 
903
- dbg(`[${ts()}] #${seq} → MITM (cert OK for ${hostname})`);
1190
+ dbg(`[${ts()}] #${seq} → MITM (cert OK for ${hostname}) ${tag}`);
904
1191
 
905
1192
  // Accept TLS from client (presenting our per-host cert signed by our CA)
906
1193
  clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
@@ -988,11 +1275,17 @@ function createProxyServer({ ca = ensureCA(), hostCertificate = getHostCert,
988
1275
  } catch (_) {}
989
1276
  });
990
1277
 
1278
+ // An empty TLS connection that ends never submitted an HTTP/model request.
1279
+ // Track decrypted bytes, not raw TLS handshake bytes, so an abandoned
1280
+ // preconnect can cancel the upstream without confusing request half-close.
1281
+ let clientBytes = 0;
1282
+ tlsClient.on('data', chunk => { clientBytes += chunk.length; });
991
1283
  // pipe() handles backpressure; accounting only observes the stream.
992
- tlsUpstream.pipe(tlsClient);
993
- tlsClient.pipe(tlsUpstream);
1284
+ // guardConnection ends the peer only after its handshake has completed.
1285
+ tlsUpstream.pipe(tlsClient, { end: false });
1286
+ tlsClient.pipe(tlsUpstream, { end: false });
994
1287
 
995
- const cleanup = () => {
1288
+ const cleanup = (reason = 'closed') => {
996
1289
  // Drain framing state, then scan any trailing data that lacked a newline.
997
1290
  try {
998
1291
  extractor.flush();
@@ -1000,18 +1293,15 @@ function createProxyServer({ ca = ensureCA(), hostCertificate = getHostCert,
1000
1293
  try {
1001
1294
  scanner.flush();
1002
1295
  } catch (_) {}
1003
- dbg(`[${ts()}] #${seq} CLOSED ${hostname} bytes=${totalBytes} usages=${usageCount} lines=${lineCount} responses=${extractor.responseCount} mode=${extractor.mode} raw=${extractor.sawRaw} encoding=${extractor.encoding || 'identity'} tlsClient=${tlsClientReady} tlsUpstream=${tlsUpstreamReady}`);
1296
+ dbg(`[${ts()}] #${seq} CLOSED ${hostname} reason=${reason} bytes=${totalBytes} usages=${usageCount} lines=${lineCount} responses=${extractor.responseCount} mode=${extractor.mode} raw=${extractor.sawRaw} encoding=${extractor.encoding || 'identity'} tlsClient=${tlsClientReady} tlsUpstream=${tlsUpstreamReady} ${tag}`);
1004
1297
  if (rawFd !== null) { try { fs.closeSync(rawFd); } catch (_) {} rawFd = null; }
1005
1298
  };
1006
1299
 
1007
- const closeConnection = guardConnection([tlsClient, tlsUpstream], {
1008
- readyEvents: ['secure', 'secureConnect'], connectTimeoutMs, idleTimeoutMs,
1009
- onCleanup: cleanup,
1010
- onError: e => dbg(`[${ts()}] #${seq} TLS error: ${e.message}`),
1300
+ guardConnection([tlsClient, tlsUpstream], {
1301
+ readyEvents: ['secure', 'secureConnect'], sides: ['client', 'upstream'], connectTimeoutMs, idleTimeoutMs,
1302
+ onCleanup: cleanup, clientSocket, clientHasData: () => clientBytes > 0,
1303
+ onError: (e, info) => dbg(`[${ts()}] #${seq} ${connectionDiagnostic('TLS', e, info)} ${tag}`),
1011
1304
  });
1012
- // Also fence an aborted raw CONNECT socket during TLS setup.
1013
- clientSocket.on('close', closeConnection);
1014
- clientSocket.on('error', closeConnection);
1015
1305
 
1016
1306
  });
1017
1307
 
@@ -1027,7 +1317,7 @@ function startProxy(port) {
1027
1317
  });
1028
1318
 
1029
1319
  server.listen(port, '127.0.0.1', () => {
1030
- console.log(`[token-proxy] listening on 127.0.0.1:${port}`);
1320
+ console.log(`[token-proxy] listening on 127.0.0.1:${port} ${instanceTag(DEFAULT_IDENTITY)}`);
1031
1321
  console.log(`[token-proxy] CA cert: ${CA_CERT_PATH}`);
1032
1322
  console.log(`[token-proxy] Usage log: ${USAGE_LOG_PATH}`);
1033
1323
  console.log(`[token-proxy] Sniffing hosts: ${[...SNIFF_HOSTS].join(', ')}`);
@@ -1140,5 +1430,8 @@ if (require.main === module) {
1140
1430
  module.exports = { extractUsageFromResponse, extractDispatchInfo, buildUsageRecord,
1141
1431
  guardConnection, createProxyServer, createRotatingWriter, rawLogFileName, rawSliceFor, installDiagLog,
1142
1432
  shouldSniffHost, createBodyDecoder, createResponseExtractor, createLineScanner,
1433
+ createPlainHTTPForwarder, proxyRequestTarget, withoutHopByHop, isOwnListener, DEFAULT_IDLE_MS,
1434
+ isPeerTeardown, tunnelDiagnostic, connectionDiagnostic,
1435
+ scriptRevision, createProxyIdentity, instanceTag, DEFAULT_IDENTITY,
1143
1436
  ensureCA, getHostCert,
1144
1437
  SNIFF_HOSTS, SNIFF_HOST_SUFFIXES, DEFAULT_MAX_LINE_BYTES };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@alicloud/autowonder",
3
- "version": "0.3.43",
3
+ "version": "0.3.45",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@alicloud/autowonder",
9
- "version": "0.3.43",
9
+ "version": "0.3.45",
10
10
  "license": "Apache-2.0",
11
11
  "bin": {
12
12
  "autowonder": "bin/cli.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alicloud/autowonder",
3
- "version": "0.3.43",
3
+ "version": "0.3.45",
4
4
  "description": "AutoWonder local runtime — execute AI agent dispatch packages on your machine",
5
5
  "bin": {
6
6
  "autowonder": "bin/cli.js"