@lincoln504/pi-research 1.7.23 → 1.7.25
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/agent-skill/pi-research/SKILL.md +1 -1
- package/dist/cli.mjs +621 -205
- package/dist/prompts/research-tool-usage.md +4 -5
- package/dist/prompts/researcher.md +6 -36
- package/dist/prompts/system-coordinator.md +1 -1
- package/dist/prompts/system-lead-synthesizer.md +5 -5
- package/dist/thread-worker.mjs +22 -9
- package/docs/CHANGELOG.md +159 -0
- package/docs/CONFIGURATION.md +4 -3
- package/docs/TROUBLESHOOTING.md +92 -0
- package/package.json +9 -9
- package/scripts/ddg-socks-proxy.mjs +105 -15
- package/src/cli.ts +32 -14
- package/src/config.ts +20 -7
- package/src/core/interfaces/health-check-interfaces.ts +23 -2
- package/src/core/interfaces/knowledge-interfaces.ts +7 -4
- package/src/core/interfaces/observer-interfaces.ts +1 -1
- package/src/core/interfaces/orchestration-interfaces.ts +17 -12
- package/src/core/interfaces/planning-interfaces.ts +5 -5
- package/src/core/interfaces/process-interfaces.ts +2 -2
- package/src/core/interfaces/state-manager-interfaces.ts +6 -5
- package/src/core/llm/agentic-repair.ts +6 -6
- package/src/core/llm/llm-utils.ts +7 -4
- package/src/core/llm/model-registry-factory.ts +11 -11
- package/src/core/llm/research-model-resolver.ts +11 -11
- package/src/core/pi-version.ts +10 -1
- package/src/core/planning-service.ts +40 -14
- package/src/core/planning-utils.ts +33 -7
- package/src/core/service-initialization.ts +1 -1
- package/src/core/service-registry.ts +18 -11
- package/src/healthcheck/index.ts +67 -5
- package/src/healthcheck/registry.ts +5 -18
- package/src/index.ts +12 -16
- package/src/infrastructure/browser/browser-client.ts +4 -4
- package/src/infrastructure/browser/browser-error-utils.ts +6 -1
- package/src/infrastructure/browser/browser-lifecycle.ts +8 -3
- package/src/infrastructure/browser/browser-server.ts +3 -3
- package/src/infrastructure/browser/browser-task-scheduler.ts +13 -9
- package/src/infrastructure/browser/priority-task-queue.ts +13 -10
- package/src/infrastructure/browser/proxy-health.ts +342 -0
- package/src/infrastructure/browser/thread-worker-browser.ts +14 -11
- package/src/infrastructure/browser/thread-worker-lifecycle.ts +21 -15
- package/src/infrastructure/browser/thread-worker-messaging.ts +39 -31
- package/src/infrastructure/browser/thread-worker-types.ts +3 -1
- package/src/infrastructure/browser/thread-worker.mjs +22 -9
- package/src/infrastructure/browser/thread-worker.ts +3 -2
- package/src/infrastructure/browser/worker-pool-manager.ts +5 -5
- package/src/infrastructure/gpu-resource-service.ts +16 -9
- package/src/infrastructure/knowledge-store-service.ts +13 -10
- package/src/infrastructure/scheduler-factory-service.ts +4 -3
- package/src/infrastructure/service-initialization.ts +1 -1
- package/src/infrastructure/state/state-manager-service.ts +2 -2
- package/src/infrastructure/state/state-manager.ts +3 -3
- package/src/infrastructure/state/state-validator.ts +9 -3
- package/src/infrastructure/types/state-types.ts +12 -91
- package/src/knowledge/embedder-init.ts +8 -8
- package/src/knowledge/embedder-utils.ts +7 -3
- package/src/knowledge/embedder.ts +14 -10
- package/src/knowledge/onnx-env.ts +2 -2
- package/src/knowledge/store.ts +12 -11
- package/src/logger.ts +1 -1
- package/src/orchestration/deep-research-orchestrator.ts +36 -7
- package/src/orchestration/headless-observer.ts +1 -1
- package/src/orchestration/orchestration-types.ts +2 -2
- package/src/orchestration/quick-research-orchestrator.ts +4 -4
- package/src/orchestration/research-orchestration-service.ts +13 -13
- package/src/orchestration/research-synthesis-service.ts +15 -8
- package/src/orchestration/researcher-executor.ts +51 -8
- package/src/orchestration/researcher.ts +19 -7
- package/src/orchestration/service-initialization.ts +1 -1
- package/src/prompts/research-tool-usage.md +4 -5
- package/src/prompts/researcher.md +6 -36
- package/src/prompts/system-coordinator.md +1 -1
- package/src/prompts/system-lead-synthesizer.md +5 -5
- package/src/research-config.ts +11 -9
- package/src/sdk.ts +10 -10
- package/src/skill-install/skill-installer.ts +19 -10
- package/src/tools/grep.ts +57 -5
- package/src/tools/index.ts +0 -3
- package/src/tools/read-guard.ts +12 -0
- package/src/tools/research-knowledge-search.ts +15 -13
- package/src/tools/research-tool-definition.ts +15 -10
- package/src/tools/scrape.ts +3 -2
- package/src/tui/research-panel.ts +1 -1
- package/src/types/extension-context.ts +2 -2
- package/src/types/llm.ts +8 -7
- package/src/types/research-panel-types.ts +3 -1
- package/src/types/state-types.ts +98 -0
- package/src/utils/coverage-digest.ts +27 -6
- package/src/utils/llm-usage.ts +3 -3
- package/src/utils/provider-errors.ts +61 -9
- package/src/utils/safe-unref.ts +2 -2
- package/src/utils/shutdown-manager.ts +6 -6
- package/src/utils/stdio-capture.ts +25 -10
- package/src/utils/text-utils.ts +35 -0
- package/src/web-research/browser-search.ts +13 -1
- package/src/web-research/retry-utils.ts +29 -1
- package/src/web-research/scraper-utils.ts +9 -3
- package/src/web-research/web-scraper.ts +25 -10
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Liveness probe for the configured SOCKS proxy.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS EXISTS
|
|
5
|
+
*
|
|
6
|
+
* `~/.pi/research/proxy.json` routes EVERY browser request through a local
|
|
7
|
+
* SOCKS5 proxy. Until this module, nothing verified that the proxy actually
|
|
8
|
+
* forwards traffic: the health registry only checked that the browser is
|
|
9
|
+
* installed, and the browser runtime check returns "ready (idle)" without
|
|
10
|
+
* probing when the scheduler is idle. On 2026-10-29 the shipped proxy
|
|
11
|
+
* (1.7.23) accepted the SOCKS handshake, connected upstream, and forwarded
|
|
12
|
+
* nothing — a one-directional `pipeline()` — and the only symptom was
|
|
13
|
+
* "Search completely failed: all 36 queries encountered worker errors" seven
|
|
14
|
+
* minutes later, with `health` reporting "All systems operational".
|
|
15
|
+
*
|
|
16
|
+
* The probe speaks the protocol the browser speaks: SOCKS5 no-auth greeting,
|
|
17
|
+
* CONNECT to an ordinary public host, one minimal HTTP request, and then it
|
|
18
|
+
* requires at least one byte BACK. A tunnel that connects but never returns a
|
|
19
|
+
* byte is the exact regression, so a connect-only check would not catch it.
|
|
20
|
+
*
|
|
21
|
+
* It is deliberately narrow: one host, one request, a few seconds. It is not a
|
|
22
|
+
* substitute for the DuckDuckGo readiness probe; it answers "is the proxy
|
|
23
|
+
* moving bytes", which is a different question from "is search working".
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import net from 'node:net';
|
|
27
|
+
import { getSocksProxyEndpoint, type SocksProxyEndpoint } from './proxy-prefs.ts';
|
|
28
|
+
|
|
29
|
+
export type ProxyProbeCode =
|
|
30
|
+
| 'ok'
|
|
31
|
+
| 'not-configured'
|
|
32
|
+
| 'unreachable'
|
|
33
|
+
| 'handshake-rejected'
|
|
34
|
+
| 'connect-rejected'
|
|
35
|
+
| 'no-data'
|
|
36
|
+
| 'protocol-error'
|
|
37
|
+
/** The caller's AbortSignal fired. Not a verdict on the proxy. */
|
|
38
|
+
| 'aborted';
|
|
39
|
+
|
|
40
|
+
export interface ProxyProbeResult {
|
|
41
|
+
readonly healthy: boolean;
|
|
42
|
+
readonly code: ProxyProbeCode;
|
|
43
|
+
readonly reason: string;
|
|
44
|
+
readonly endpoint: SocksProxyEndpoint | null;
|
|
45
|
+
readonly latencyMs: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface ProxyProbeOptions {
|
|
49
|
+
/** TCP connect + SOCKS handshake deadline. */
|
|
50
|
+
readonly timeoutMs?: number;
|
|
51
|
+
/** How long to wait for the first upstream byte after CONNECT succeeds. */
|
|
52
|
+
readonly dataTimeoutMs?: number;
|
|
53
|
+
/** Host:port the probe asks the proxy to reach. */
|
|
54
|
+
readonly targetHost?: string;
|
|
55
|
+
readonly targetPort?: number;
|
|
56
|
+
/** Cancel the probe. An aborted probe returns code 'aborted', not 'unhealthy'. */
|
|
57
|
+
readonly signal?: AbortSignal;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
61
|
+
const DEFAULT_DATA_TIMEOUT_MS = 8_000;
|
|
62
|
+
// DuckDuckGo's own front door on plain HTTP, deliberately NOT example.com: the
|
|
63
|
+
// proxy pins *.duckduckgo.com addresses and rotates past a dead pin. A probe to
|
|
64
|
+
// example.com resolves with ordinary DNS and never touches a pin, so it cannot
|
|
65
|
+
// catch the failure this proxy has actually had (both pins dying at once). DDG
|
|
66
|
+
// answers port 80 with a 301, and the probe only needs one byte back.
|
|
67
|
+
const DEFAULT_TARGET_HOST = 'lite.duckduckgo.com';
|
|
68
|
+
const DEFAULT_TARGET_PORT = 80;
|
|
69
|
+
/** The neutral fallback target used to separate "proxy broken" from "DDG unreachable". */
|
|
70
|
+
export const NEUTRAL_TARGET_HOST = 'example.com';
|
|
71
|
+
export const NEUTRAL_TARGET_PORT = 80;
|
|
72
|
+
|
|
73
|
+
function fail(
|
|
74
|
+
code: ProxyProbeCode,
|
|
75
|
+
reason: string,
|
|
76
|
+
endpoint: SocksProxyEndpoint | null,
|
|
77
|
+
startedAt: number,
|
|
78
|
+
): ProxyProbeResult {
|
|
79
|
+
return { healthy: false, code, reason, endpoint, latencyMs: Date.now() - startedAt };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Ask the proxy for one page and require bytes back.
|
|
84
|
+
* Never throws: every failure is a classified result.
|
|
85
|
+
*/
|
|
86
|
+
export function probeSocksProxyForwarding(
|
|
87
|
+
endpoint: SocksProxyEndpoint | null = getSocksProxyEndpoint(),
|
|
88
|
+
options: ProxyProbeOptions = {},
|
|
89
|
+
): Promise<ProxyProbeResult> {
|
|
90
|
+
const startedAt = Date.now();
|
|
91
|
+
if (!endpoint) {
|
|
92
|
+
return Promise.resolve({
|
|
93
|
+
healthy: true,
|
|
94
|
+
code: 'not-configured',
|
|
95
|
+
reason: 'no SOCKS proxy configured (browser connects directly)',
|
|
96
|
+
endpoint: null,
|
|
97
|
+
latencyMs: 0,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
102
|
+
const dataTimeoutMs = options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS;
|
|
103
|
+
const targetHost = options.targetHost ?? DEFAULT_TARGET_HOST;
|
|
104
|
+
const targetPort = options.targetPort ?? DEFAULT_TARGET_PORT;
|
|
105
|
+
const where = `${endpoint.host}:${endpoint.port}`;
|
|
106
|
+
|
|
107
|
+
return new Promise<ProxyProbeResult>((resolve) => {
|
|
108
|
+
const socket = net.connect({ host: endpoint.host, port: endpoint.port });
|
|
109
|
+
let stage: 'greet' | 'connect' | 'data' = 'greet';
|
|
110
|
+
let settled = false;
|
|
111
|
+
let buffer = Buffer.alloc(0);
|
|
112
|
+
// Declared before `finish` so the already-aborted path can clear them without
|
|
113
|
+
// a temporal-dead-zone ReferenceError.
|
|
114
|
+
let connectTimer: ReturnType<typeof setTimeout> | undefined;
|
|
115
|
+
let dataTimer: ReturnType<typeof setTimeout> | undefined;
|
|
116
|
+
|
|
117
|
+
const onAbort = () => {
|
|
118
|
+
finish(fail('aborted', 'proxy probe cancelled by the caller', endpoint, startedAt));
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const finish = (result: ProxyProbeResult) => {
|
|
122
|
+
if (settled) return;
|
|
123
|
+
settled = true;
|
|
124
|
+
clearTimeout(connectTimer);
|
|
125
|
+
clearTimeout(dataTimer);
|
|
126
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
127
|
+
socket.destroy();
|
|
128
|
+
resolve(result);
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
// A probe runs at the START of a run and on the health path, both of which a
|
|
132
|
+
// user can cancel. Without this, Esc during a dead proxy's 3s+4s+3s+4s probe
|
|
133
|
+
// sequence did nothing until the sequence finished.
|
|
134
|
+
if (options.signal?.aborted) {
|
|
135
|
+
onAbort();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
139
|
+
|
|
140
|
+
connectTimer = setTimeout(() => {
|
|
141
|
+
finish(fail(
|
|
142
|
+
stage === 'greet' ? 'unreachable' : 'no-data',
|
|
143
|
+
stage === 'greet'
|
|
144
|
+
? `proxy at ${where} did not accept a TCP connection within ${timeoutMs}ms`
|
|
145
|
+
: `proxy at ${where} accepted the connection but did not answer within ${timeoutMs}ms`,
|
|
146
|
+
endpoint,
|
|
147
|
+
startedAt,
|
|
148
|
+
));
|
|
149
|
+
}, timeoutMs);
|
|
150
|
+
connectTimer.unref?.();
|
|
151
|
+
|
|
152
|
+
// Armed only after the success reply, so it measures the thing that broke:
|
|
153
|
+
// the proxy said "connected" and then delivered nothing.
|
|
154
|
+
const armDataTimer = () => {
|
|
155
|
+
dataTimer = setTimeout(() => {
|
|
156
|
+
finish(fail(
|
|
157
|
+
'no-data',
|
|
158
|
+
`proxy at ${where} completed the SOCKS handshake to ${targetHost}:${targetPort} `
|
|
159
|
+
+ `but returned no data within ${dataTimeoutMs}ms `
|
|
160
|
+
+ '(the tunnel is not forwarding answers — check that the proxy process is running the current script and restart it)',
|
|
161
|
+
endpoint,
|
|
162
|
+
startedAt,
|
|
163
|
+
));
|
|
164
|
+
}, dataTimeoutMs);
|
|
165
|
+
dataTimer.unref?.();
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
socket.on('connect', () => {
|
|
169
|
+
socket.write(Buffer.from([0x05, 0x01, 0x00])); // SOCKS5, one method: no auth
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
socket.on('data', (chunk: Buffer) => {
|
|
173
|
+
if (settled) return;
|
|
174
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
175
|
+
|
|
176
|
+
if (stage === 'greet') {
|
|
177
|
+
if (buffer.length < 2) return;
|
|
178
|
+
if (buffer[0] !== 0x05 || buffer[1] !== 0x00) {
|
|
179
|
+
finish(fail(
|
|
180
|
+
'protocol-error',
|
|
181
|
+
`proxy at ${where} answered the SOCKS greeting with [${[...buffer.subarray(0, 2)]}] instead of [5,0]`,
|
|
182
|
+
endpoint,
|
|
183
|
+
startedAt,
|
|
184
|
+
));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
buffer = buffer.subarray(2);
|
|
188
|
+
const hostBytes = Buffer.from(targetHost, 'utf8');
|
|
189
|
+
socket.write(Buffer.concat([
|
|
190
|
+
Buffer.from([0x05, 0x01, 0x00, 0x03, hostBytes.length]),
|
|
191
|
+
hostBytes,
|
|
192
|
+
Buffer.from([(targetPort >> 8) & 0xff, targetPort & 0xff]),
|
|
193
|
+
]));
|
|
194
|
+
stage = 'connect';
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (stage === 'connect') {
|
|
199
|
+
if (buffer.length < 4) return;
|
|
200
|
+
if (buffer[0] !== 0x05) {
|
|
201
|
+
finish(fail('protocol-error', `proxy at ${where} answered the SOCKS request malformed`, endpoint, startedAt));
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const reply = buffer[1];
|
|
205
|
+
if (reply !== 0x00) {
|
|
206
|
+
const meaning = reply === 0x02
|
|
207
|
+
? 'refused by ruleset'
|
|
208
|
+
: reply === 0x03 ? 'network unreachable'
|
|
209
|
+
: reply === 0x04 ? 'host unreachable'
|
|
210
|
+
: reply === 0x05 ? 'connection refused by the target' : `SOCKS error ${reply}`;
|
|
211
|
+
finish(fail(
|
|
212
|
+
'connect-rejected',
|
|
213
|
+
`proxy at ${where} refused CONNECT to ${targetHost}:${targetPort} (${meaning})`,
|
|
214
|
+
endpoint,
|
|
215
|
+
startedAt,
|
|
216
|
+
));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
// Consume the bound-address field so leftover bytes cannot be mistaken
|
|
220
|
+
// for the response body of the request below.
|
|
221
|
+
const atyp = buffer[3];
|
|
222
|
+
let addrLen: number;
|
|
223
|
+
if (atyp === 0x01) {
|
|
224
|
+
addrLen = 4;
|
|
225
|
+
} else if (atyp === 0x04) {
|
|
226
|
+
addrLen = 16;
|
|
227
|
+
} else if (atyp === 0x03) {
|
|
228
|
+
if (buffer.length < 5) return; // the domain-length byte is not in yet
|
|
229
|
+
addrLen = 1 + (buffer[4] ?? 0);
|
|
230
|
+
} else {
|
|
231
|
+
finish(fail('protocol-error', `proxy at ${where} answered CONNECT with unknown address type ${atyp}`, endpoint, startedAt));
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
const replyLen = 4 + addrLen + 2;
|
|
235
|
+
if (buffer.length < replyLen) return;
|
|
236
|
+
buffer = buffer.subarray(replyLen);
|
|
237
|
+
// The handshake is over: the connect deadline must not keep ticking while
|
|
238
|
+
// we wait for the response, or a short connect budget would masquerade as
|
|
239
|
+
// "no data". The data deadline takes over.
|
|
240
|
+
clearTimeout(connectTimer);
|
|
241
|
+
socket.write(
|
|
242
|
+
`GET / HTTP/1.0\r\nHost: ${targetHost}\r\nConnection: close\r\n\r\n`,
|
|
243
|
+
);
|
|
244
|
+
stage = 'data';
|
|
245
|
+
armDataTimer();
|
|
246
|
+
// A pipelined byte that arrived with the reply counts as data.
|
|
247
|
+
if (buffer.length > 0) {
|
|
248
|
+
finish({
|
|
249
|
+
healthy: true,
|
|
250
|
+
code: 'ok',
|
|
251
|
+
reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
|
|
252
|
+
endpoint,
|
|
253
|
+
latencyMs: Date.now() - startedAt,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
finish({
|
|
260
|
+
healthy: true,
|
|
261
|
+
code: 'ok',
|
|
262
|
+
reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
|
|
263
|
+
endpoint,
|
|
264
|
+
latencyMs: Date.now() - startedAt,
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
socket.on('error', (err: NodeJS.ErrnoException) => {
|
|
269
|
+
const detail = err.code === 'ECONNREFUSED'
|
|
270
|
+
? 'nothing is listening there — is the proxy service running?'
|
|
271
|
+
: err.message;
|
|
272
|
+
finish(fail('unreachable', `proxy at ${where} is unusable: ${detail}`, endpoint, startedAt));
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
socket.on('close', () => {
|
|
276
|
+
finish(fail(
|
|
277
|
+
'no-data',
|
|
278
|
+
`proxy at ${where} closed the tunnel before returning data`,
|
|
279
|
+
endpoint,
|
|
280
|
+
startedAt,
|
|
281
|
+
));
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* A one-line diagnosis to append to a run-level search failure, or null when the
|
|
288
|
+
* proxy is healthy/not configured. Kept separate from the probe used by the
|
|
289
|
+
* health registry: this one is bounded tighter, because it runs while the user
|
|
290
|
+
* is already waiting for an error.
|
|
291
|
+
*/
|
|
292
|
+
export interface ProxyDiagnosisOptions {
|
|
293
|
+
/** Per-probe connect deadline. Default 3s. */
|
|
294
|
+
readonly timeoutMs?: number;
|
|
295
|
+
/** Per-probe first-byte deadline. Default 3s (4s on the second sample). */
|
|
296
|
+
readonly dataTimeoutMs?: number;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export async function describeProxyIfBroken(
|
|
300
|
+
signal?: AbortSignal,
|
|
301
|
+
options: ProxyDiagnosisOptions = {},
|
|
302
|
+
): Promise<string | null> {
|
|
303
|
+
const endpoint = getSocksProxyEndpoint();
|
|
304
|
+
if (!endpoint) return null;
|
|
305
|
+
const opts = {
|
|
306
|
+
timeoutMs: options.timeoutMs ?? 3_000,
|
|
307
|
+
dataTimeoutMs: options.dataTimeoutMs ?? 3_000,
|
|
308
|
+
signal,
|
|
309
|
+
} as const;
|
|
310
|
+
|
|
311
|
+
// TWO attempts against DuckDuckGo. This verdict STOPS a run, so it must not rest
|
|
312
|
+
// on one sample: a single refused connect during a proxy restart, or one
|
|
313
|
+
// oversized response, would abort work the next probe would have cleared. A
|
|
314
|
+
// genuinely dead or one-way tunnel fails both attempts.
|
|
315
|
+
let last = await probeSocksProxyForwarding(endpoint, opts);
|
|
316
|
+
if (last.code === 'aborted') return null;
|
|
317
|
+
if (!last.healthy) {
|
|
318
|
+
last = await probeSocksProxyForwarding(endpoint, {
|
|
319
|
+
...opts,
|
|
320
|
+
dataTimeoutMs: (options.dataTimeoutMs ?? 4_000),
|
|
321
|
+
});
|
|
322
|
+
if (last.code === 'aborted') return null;
|
|
323
|
+
}
|
|
324
|
+
if (last.healthy) return null;
|
|
325
|
+
|
|
326
|
+
// DDG failed twice. Before blaming the proxy, ask it for a neutral host: that
|
|
327
|
+
// separates "the tunnel is dead" from "the tunnel works but DDG is blocked or
|
|
328
|
+
// its pins are dead". Both stop a run, but only one is fixed by restarting the
|
|
329
|
+
// proxy, and the message should say which.
|
|
330
|
+
const neutral = await probeSocksProxyForwarding(endpoint, {
|
|
331
|
+
...opts,
|
|
332
|
+
targetHost: NEUTRAL_TARGET_HOST,
|
|
333
|
+
targetPort: NEUTRAL_TARGET_PORT,
|
|
334
|
+
});
|
|
335
|
+
if (neutral.code === 'aborted') return null;
|
|
336
|
+
if (neutral.healthy) {
|
|
337
|
+
return 'SOCKS proxy check: the proxy forwards traffic to example.com, but DuckDuckGo is '
|
|
338
|
+
+ `unreachable through it (${last.reason}). The tunnel works; the pinned DuckDuckGo front `
|
|
339
|
+
+ 'doors are not answering. Update DDG_PIN_IPS in the proxy service or remove ~/.pi/research/proxy.json.';
|
|
340
|
+
}
|
|
341
|
+
return `SOCKS proxy check: ${last.reason}. The proxy did not forward traffic to example.com either, so the tunnel itself is broken.`;
|
|
342
|
+
}
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { platform } from 'node:os';
|
|
12
|
+
import type { Browser, BrowserContext } from 'playwright-core';
|
|
12
13
|
import { loadSocksProxyPrefs } from './proxy-prefs.ts';
|
|
13
14
|
import { setupMocking } from './thread-worker-messaging.ts';
|
|
14
15
|
import { redactSecrets } from '../../utils/log-utils.ts';
|
|
@@ -25,7 +26,7 @@ import { resolveHeadlessMode, BROWSER_LAUNCH_TIMEOUT_MS, CONTEXT_CREATION_TIMEOU
|
|
|
25
26
|
// SAME setting to know that a response's serverAddr() is the proxy hop rather
|
|
26
27
|
// than the origin (see isProxyHopAddress there).
|
|
27
28
|
|
|
28
|
-
let browser:
|
|
29
|
+
let browser: Browser | BrowserContext | null = null;
|
|
29
30
|
let initPromise: Promise<void> | null = null;
|
|
30
31
|
let workerId: string = '';
|
|
31
32
|
|
|
@@ -49,7 +50,7 @@ let resetPending = false;
|
|
|
49
50
|
// immediate path (doResetBrowser() + a fresh initBrowser() relaunch) while
|
|
50
51
|
// this flag is still pending — see taskFinished() below for why the flag
|
|
51
52
|
// alone isn't enough to know whether it's still safe to apply.
|
|
52
|
-
let resetPendingForBrowser:
|
|
53
|
+
let resetPendingForBrowser: Browser | BrowserContext | null = null;
|
|
53
54
|
|
|
54
55
|
/**
|
|
55
56
|
* Set the worker ID for logging purposes
|
|
@@ -89,7 +90,9 @@ export function taskFinished(): void {
|
|
|
89
90
|
*/
|
|
90
91
|
const isBrowserConnected = () => {
|
|
91
92
|
try {
|
|
92
|
-
|
|
93
|
+
// `isConnected` is a Browser-only member; the `in` check narrows the
|
|
94
|
+
// Browser | BrowserContext union to Browser.
|
|
95
|
+
return !!(browser && 'isConnected' in browser && browser.isConnected());
|
|
93
96
|
} catch {
|
|
94
97
|
logToDebugFile('DEBUG', '[ThreadWorker] browser.isConnected check threw, treating as disconnected');
|
|
95
98
|
return false;
|
|
@@ -101,7 +104,7 @@ const isBrowserConnected = () => {
|
|
|
101
104
|
* This is the only logging mechanism available to worker processes —
|
|
102
105
|
* the main-process logger is not accessible from isolated worker threads.
|
|
103
106
|
*/
|
|
104
|
-
function logToDebugFile(level: string, ...args:
|
|
107
|
+
function logToDebugFile(level: string, ...args: unknown[]): void {
|
|
105
108
|
const logFile = process.env['PI_RESEARCH_LOG_FILE'];
|
|
106
109
|
if (!logFile) return;
|
|
107
110
|
// Match the main-process logger: WARN/ERROR are always recorded (crash diagnostics);
|
|
@@ -183,7 +186,7 @@ export async function initBrowser(): Promise<void> {
|
|
|
183
186
|
// Always re-verify a REAL headless run after touching any of this: the
|
|
184
187
|
// unit and integration suites mock the browser, so a Juggler mismatch
|
|
185
188
|
// reaches production with a fully green suite.
|
|
186
|
-
let CamoufoxModule:
|
|
189
|
+
let CamoufoxModule: typeof import('camoufox');
|
|
187
190
|
try {
|
|
188
191
|
CamoufoxModule = await import('camoufox');
|
|
189
192
|
} catch (e: unknown) {
|
|
@@ -278,7 +281,7 @@ export async function initBrowser(): Promise<void> {
|
|
|
278
281
|
// Firefox with no owner, surviving the orphan sweep (its parent worker is
|
|
279
282
|
// alive) until the pool shuts down. Adopt and close it, exactly as
|
|
280
283
|
// createPageSafe already does for an orphaned page.
|
|
281
|
-
launchPromise.then((b:
|
|
284
|
+
launchPromise.then((b: Browser | BrowserContext) => {
|
|
282
285
|
if (!raceLost) return;
|
|
283
286
|
logToDebugFile('WARN', `[Worker-${workerId}] Browser launch completed after its deadline; closing the orphaned instance.`);
|
|
284
287
|
try { b?.close?.(); } catch { /* already gone */ }
|
|
@@ -338,7 +341,7 @@ export async function initBrowser(): Promise<void> {
|
|
|
338
341
|
|
|
339
342
|
// camoufox headless: "virtual" spawns Xvfb on Linux when no DISPLAY is set.
|
|
340
343
|
// CannotFindXvfb is thrown when `which Xvfb` fails (xvfb not installed).
|
|
341
|
-
const errName = e instanceof Error ? (e as
|
|
344
|
+
const errName = e instanceof Error ? (e as { constructor?: { name?: string } }).constructor?.name ?? '' : '';
|
|
342
345
|
if (errName === 'CannotFindXvfb' || errName === 'CannotExecuteXvfb' || msg.includes('Xvfb') || msg.includes('virtual display')) {
|
|
343
346
|
throw new Error(
|
|
344
347
|
'[Worker] No display server found on Linux. Install Xvfb for headless use (TTY/Wayland): sudo apt install xvfb',
|
|
@@ -376,20 +379,20 @@ export async function initBrowser(): Promise<void> {
|
|
|
376
379
|
* context that finishes creating AFTER that timeout is adopted and closed
|
|
377
380
|
* rather than left to leak.
|
|
378
381
|
*/
|
|
379
|
-
export async function acquireTaskContext(): Promise<
|
|
382
|
+
export async function acquireTaskContext(): Promise<BrowserContext> {
|
|
380
383
|
// acceptDownloads is explicit, not defaulted: executeScrapeTask recovers PDFs that a
|
|
381
384
|
// server sends as an attachment by reading the resulting Download, and that object
|
|
382
385
|
// only exists when downloads are accepted.
|
|
383
|
-
const contextPromise = browser.newContext({ acceptDownloads: true });
|
|
386
|
+
const contextPromise = (browser as Browser).newContext({ acceptDownloads: true });
|
|
384
387
|
contextPromise.catch((err: Error) => logToDebugFile('DEBUG', `[ThreadWorker] Background browser context rejection: ${err.message}`));
|
|
385
388
|
let contextTimeoutId: NodeJS.Timeout | undefined;
|
|
386
389
|
let contextRaceLost = false;
|
|
387
|
-
contextPromise.then((c:
|
|
390
|
+
contextPromise.then((c: BrowserContext) => {
|
|
388
391
|
if (!contextRaceLost) return;
|
|
389
392
|
logToDebugFile('WARN', `[Worker-${workerId}] Browser context creation completed after its deadline; closing the orphaned context.`);
|
|
390
393
|
try { c?.close?.(); } catch { /* already gone */ }
|
|
391
394
|
}).catch(() => { /* rejection already logged above */ });
|
|
392
|
-
let newContext:
|
|
395
|
+
let newContext: BrowserContext;
|
|
393
396
|
try {
|
|
394
397
|
newContext = await Promise.race([
|
|
395
398
|
contextPromise,
|
|
@@ -10,6 +10,9 @@ import cluster from 'node:cluster';
|
|
|
10
10
|
import * as fs from 'node:fs/promises';
|
|
11
11
|
import { redactSecrets } from '../../utils/log-utils.ts';
|
|
12
12
|
|
|
13
|
+
/** cluster.Worker plus the module's own guard marker, set on guarded workers. */
|
|
14
|
+
type GuardedWorker = cluster.Worker & { __piIpcGuarded?: boolean };
|
|
15
|
+
|
|
13
16
|
let workerId: string = '';
|
|
14
17
|
|
|
15
18
|
/**
|
|
@@ -35,7 +38,7 @@ export function setupIpcErrorHandler(): void {
|
|
|
35
38
|
if (!cluster.isWorker || !cluster.worker) {
|
|
36
39
|
return;
|
|
37
40
|
}
|
|
38
|
-
cluster.worker.on('error', (err:
|
|
41
|
+
cluster.worker.on('error', (err: unknown) => {
|
|
39
42
|
if (isBenignClusterIpcError(err)) {
|
|
40
43
|
return;
|
|
41
44
|
}
|
|
@@ -54,10 +57,11 @@ export function setupIpcErrorHandler(): void {
|
|
|
54
57
|
*/
|
|
55
58
|
const BENIGN_IPC_CODES = new Set(['EPIPE', 'ERR_IPC_CHANNEL_CLOSED', 'ECONNRESET']);
|
|
56
59
|
|
|
57
|
-
export function isBenignClusterIpcError(err:
|
|
60
|
+
export function isBenignClusterIpcError(err: unknown): boolean {
|
|
58
61
|
if (!err) return false;
|
|
59
|
-
|
|
60
|
-
|
|
62
|
+
const e = err as { code?: string; message?: string };
|
|
63
|
+
if (typeof e.code === 'string' && BENIGN_IPC_CODES.has(e.code)) return true;
|
|
64
|
+
const msg = String(e.message || err);
|
|
61
65
|
return /\b(EPIPE|ECONNRESET)\b/.test(msg) || /channel closed/i.test(msg);
|
|
62
66
|
}
|
|
63
67
|
|
|
@@ -94,11 +98,11 @@ export function setupMasterIpcErrorHandler(): void {
|
|
|
94
98
|
// cluster emits 'fork' for every worker poolifier creates, including the
|
|
95
99
|
// respawns it triggers via startMinimumNumberOfWorkers() after an unexpected
|
|
96
100
|
// exit — so this catches the churn-driven workers, not just the initial set.
|
|
97
|
-
cluster.on('fork', (worker) => guardClusterWorker(worker));
|
|
101
|
+
cluster.on('fork', (worker) => guardClusterWorker(worker as GuardedWorker));
|
|
98
102
|
|
|
99
103
|
// Cover any workers already forked before this handler was installed.
|
|
100
104
|
for (const id of Object.keys(cluster.workers ?? {})) {
|
|
101
|
-
const w = (cluster.workers
|
|
105
|
+
const w = (cluster.workers ?? {})[id] as GuardedWorker | undefined;
|
|
102
106
|
if (w) guardClusterWorker(w);
|
|
103
107
|
}
|
|
104
108
|
|
|
@@ -137,14 +141,15 @@ export function guardWorkerEmitReemit(): void {
|
|
|
137
141
|
const origEmit = Worker.prototype.emit;
|
|
138
142
|
if (typeof origEmit !== 'function') return;
|
|
139
143
|
workerEmitOriginal = origEmit;
|
|
140
|
-
Worker.prototype.emit = function (this:
|
|
144
|
+
Worker.prototype.emit = function (this: cluster.Worker, event: string | symbol, ...args: unknown[]) {
|
|
141
145
|
if (event === 'error' && typeof this.listenerCount === 'function' && this.listenerCount('error') === 0) {
|
|
142
|
-
this.on('error', (err:
|
|
146
|
+
this.on('error', (err: unknown) => {
|
|
147
|
+
const e = err as { code?: string; message?: string; stack?: string } | undefined;
|
|
143
148
|
if (isBenignClusterIpcError(err)) {
|
|
144
|
-
logToDebugFile('DEBUG', `[Master] Last-resort guard swallowed listener-less IPC error: ${
|
|
149
|
+
logToDebugFile('DEBUG', `[Master] Last-resort guard swallowed listener-less IPC error: ${e?.code || e?.message}`);
|
|
145
150
|
return;
|
|
146
151
|
}
|
|
147
|
-
logToDebugFile('WARN', `[Master] Last-resort guard handled listener-less worker error: ${
|
|
152
|
+
logToDebugFile('WARN', `[Master] Last-resort guard handled listener-less worker error: ${e?.stack || e?.message || err}`);
|
|
148
153
|
});
|
|
149
154
|
}
|
|
150
155
|
return origEmit.apply(this, [event, ...args]);
|
|
@@ -161,19 +166,20 @@ export function __resetWorkerEmitGuardForTests(): void {
|
|
|
161
166
|
workerEmitGuardPatched = false;
|
|
162
167
|
}
|
|
163
168
|
|
|
164
|
-
function guardClusterWorker(worker:
|
|
169
|
+
function guardClusterWorker(worker: GuardedWorker): void {
|
|
165
170
|
if (!worker || worker.__piIpcGuarded) return;
|
|
166
171
|
worker.__piIpcGuarded = true;
|
|
167
172
|
|
|
168
|
-
const guard = (err:
|
|
173
|
+
const guard = (err: unknown) => {
|
|
174
|
+
const e = err as { code?: string; message?: string; stack?: string } | undefined;
|
|
169
175
|
if (isBenignClusterIpcError(err)) {
|
|
170
|
-
logToDebugFile('DEBUG', `[Master] Swallowed benign worker IPC error: ${
|
|
176
|
+
logToDebugFile('DEBUG', `[Master] Swallowed benign worker IPC error: ${e?.code || e?.message}`);
|
|
171
177
|
return;
|
|
172
178
|
}
|
|
173
179
|
// Non-benign worker errors are independently handled by poolifier's own
|
|
174
180
|
// errorHandler (which counts them and triggers pool recovery). Re-throwing
|
|
175
181
|
// here would itself become an uncaughtException, so just record it.
|
|
176
|
-
logToDebugFile('WARN', `[Master] Worker error (non-IPC): ${
|
|
182
|
+
logToDebugFile('WARN', `[Master] Worker error (non-IPC): ${e?.stack || e?.message || err}`);
|
|
177
183
|
};
|
|
178
184
|
|
|
179
185
|
worker.on('error', guard);
|
|
@@ -375,7 +381,7 @@ export function cleanupOrphanProtection(): void {
|
|
|
375
381
|
/**
|
|
376
382
|
* Log to debug file
|
|
377
383
|
*/
|
|
378
|
-
function logToDebugFile(level: string, ...args:
|
|
384
|
+
function logToDebugFile(level: string, ...args: unknown[]): void {
|
|
379
385
|
const logFile = process.env['PI_RESEARCH_LOG_FILE'];
|
|
380
386
|
if (!logFile) return;
|
|
381
387
|
// Match the main-process logger: WARN/ERROR are always recorded (crash diagnostics);
|