@lincoln504/pi-research 1.7.22 → 1.7.24
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 +402 -70
- package/dist/thread-worker.mjs +8 -6
- package/docs/CHANGELOG.md +139 -0
- package/docs/CONFIGURATION.md +4 -0
- package/docs/THIRD-PARTY-NOTICES.md +29 -13
- package/docs/TROUBLESHOOTING.md +92 -0
- package/package.json +10 -9
- package/scripts/ddg-socks-proxy.mjs +133 -20
- package/scripts/lib/npm-cmd.cjs +66 -0
- package/scripts/lib/private-addresses.mjs +19 -5
- package/src/core/planning-service.ts +7 -1
- package/src/healthcheck/index.ts +62 -1
- package/src/infrastructure/browser/proxy-health.ts +342 -0
- package/src/infrastructure/browser/proxy-prefs.ts +18 -7
- package/src/infrastructure/browser/thread-worker-messaging.ts +2 -2
- package/src/infrastructure/browser/thread-worker.mjs +8 -6
- package/src/knowledge/embedder-utils.ts +1 -1
- package/src/knowledge/sql-utils.ts +15 -0
- package/src/knowledge/store-operations.ts +3 -2
- package/src/knowledge/store.ts +15 -14
- package/src/orchestration/deep-research-orchestrator.ts +21 -0
- package/src/orchestration/researcher-executor.ts +28 -1
- package/src/tools/read-guard.ts +23 -4
- package/src/utils/provider-errors.ts +61 -9
- package/src/web-research/browser-search.ts +13 -1
- package/src/web-research/retry-utils.ts +30 -2
|
@@ -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
|
+
}
|
|
@@ -51,10 +51,17 @@ export function getSocksProxyEndpoint(): SocksProxyEndpoint | null {
|
|
|
51
51
|
cached = null;
|
|
52
52
|
return cached;
|
|
53
53
|
}
|
|
54
|
-
const cfg = JSON.parse(readFileSync(file, 'utf8')) as { host?:
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
const cfg = JSON.parse(readFileSync(file, 'utf8')) as { host?: unknown; port?: unknown };
|
|
55
|
+
// Type-check the values: a hand-edited file with a numeric host or an
|
|
56
|
+
// out-of-range port must mean "no proxy", not a browser launched with a
|
|
57
|
+
// nonsense endpoint.
|
|
58
|
+
const host = cfg.host === undefined ? '127.0.0.1' : typeof cfg.host === 'string' ? cfg.host.trim() : '';
|
|
59
|
+
const port = cfg.port === undefined ? 1080 : Number.isInteger(cfg.port) ? (cfg.port as number) : -1;
|
|
60
|
+
if (host === '' || port < 1 || port > 65535) {
|
|
61
|
+
cached = null;
|
|
62
|
+
return cached;
|
|
63
|
+
}
|
|
64
|
+
cached = { host, port };
|
|
58
65
|
return cached;
|
|
59
66
|
} catch {
|
|
60
67
|
cached = null;
|
|
@@ -103,11 +110,15 @@ export function resetSocksProxyCache(): void {
|
|
|
103
110
|
* The check is deliberately gated on a configured proxy: with no proxy, Firefox
|
|
104
111
|
* reports the true remote address, and an unspecified address there is anomalous
|
|
105
112
|
* enough to keep blocking.
|
|
113
|
+
*
|
|
114
|
+
* Only the unspecified addresses are exempt, never the proxy host itself:
|
|
115
|
+
* with the proxy on 127.0.0.1 (the normal configuration), an origin address of
|
|
116
|
+
* 127.0.0.1 is indistinguishable from a genuine loopback origin, and the
|
|
117
|
+
* conservative call is to poison the scrape. Measured with camoufox 0.5.8 the
|
|
118
|
+
* hop reports 0.0.0.0, which is covered above.
|
|
106
119
|
*/
|
|
107
120
|
export function isProxyHopAddress(ip: string, proxy: SocksProxyEndpoint | null = getSocksProxyEndpoint()): boolean {
|
|
108
121
|
if (!proxy) return false;
|
|
109
122
|
const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, '');
|
|
110
|
-
|
|
111
|
-
const proxyHost = proxy.host.trim().toLowerCase().replace(/^\[|\]$/g, '');
|
|
112
|
-
return addr === proxyHost;
|
|
123
|
+
return addr === '' || addr === '0.0.0.0' || addr === '::' || addr === '::0';
|
|
113
124
|
}
|
|
@@ -267,7 +267,7 @@ export async function setupMocking(context: any): Promise<void> {
|
|
|
267
267
|
async function extractSearchResults(page: any): Promise<any[]> {
|
|
268
268
|
return await page.evaluate(() => {
|
|
269
269
|
const found: any[] = [];
|
|
270
|
-
//
|
|
270
|
+
// document is available in browser context (callback runs in the page)
|
|
271
271
|
// eslint-disable-next-line no-undef
|
|
272
272
|
const links = Array.from(document.querySelectorAll('a.result-link, a.result__a'));
|
|
273
273
|
links.forEach((link: any) => {
|
|
@@ -985,7 +985,7 @@ export async function executeScrapeTask(
|
|
|
985
985
|
try {
|
|
986
986
|
await page.waitForFunction(
|
|
987
987
|
() => {
|
|
988
|
-
//
|
|
988
|
+
// document is available in browser context (callback runs in the page)
|
|
989
989
|
// eslint-disable-next-line no-undef
|
|
990
990
|
const body = document.body.innerHTML;
|
|
991
991
|
return !body.includes('_cf_chl_') &&
|
|
@@ -2123,9 +2123,13 @@ function getSocksProxyEndpoint() {
|
|
|
2123
2123
|
return cached;
|
|
2124
2124
|
}
|
|
2125
2125
|
const cfg = JSON.parse(readFileSync(file, "utf8"));
|
|
2126
|
-
const host = cfg.host
|
|
2127
|
-
const port = cfg.port
|
|
2128
|
-
|
|
2126
|
+
const host = cfg.host === void 0 ? "127.0.0.1" : typeof cfg.host === "string" ? cfg.host.trim() : "";
|
|
2127
|
+
const port = cfg.port === void 0 ? 1080 : Number.isInteger(cfg.port) ? cfg.port : -1;
|
|
2128
|
+
if (host === "" || port < 1 || port > 65535) {
|
|
2129
|
+
cached = null;
|
|
2130
|
+
return cached;
|
|
2131
|
+
}
|
|
2132
|
+
cached = { host, port };
|
|
2129
2133
|
return cached;
|
|
2130
2134
|
} catch {
|
|
2131
2135
|
cached = null;
|
|
@@ -2147,9 +2151,7 @@ function loadSocksProxyPrefs() {
|
|
|
2147
2151
|
function isProxyHopAddress(ip, proxy = getSocksProxyEndpoint()) {
|
|
2148
2152
|
if (!proxy) return false;
|
|
2149
2153
|
const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, "");
|
|
2150
|
-
|
|
2151
|
-
const proxyHost = proxy.host.trim().toLowerCase().replace(/^\[|\]$/g, "");
|
|
2152
|
-
return addr === proxyHost;
|
|
2154
|
+
return addr === "" || addr === "0.0.0.0" || addr === "::" || addr === "::0";
|
|
2153
2155
|
}
|
|
2154
2156
|
|
|
2155
2157
|
// src/infrastructure/browser/thread-worker-messaging.ts
|
|
@@ -269,7 +269,7 @@ export async function initializeDawnWebGPU(): Promise<boolean> {
|
|
|
269
269
|
// reason; the adapter probe below is the other native entry point and was
|
|
270
270
|
// missing it, which is why a plain `knowledge` run still printed them.
|
|
271
271
|
const adapter = await logger.runCapturingStderr(async () => {
|
|
272
|
-
//
|
|
272
|
+
// webgpu is an optional dependency (types resolve because it is installed for dev)
|
|
273
273
|
const { create, globals } = await import('webgpu');
|
|
274
274
|
Object.assign(globalThis, globals);
|
|
275
275
|
// Use Object.defineProperty — Node.js defines navigator as a configurable getter
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL string literal for the knowledge store's DataFusion queries.
|
|
3
|
+
*
|
|
4
|
+
* The store builds LanceDB/DataFusion SQL by string interpolation, and the
|
|
5
|
+
* interpolated values are attacker-influenced (stored URLs, workspace paths,
|
|
6
|
+
* ingestion types). Every interpolated string MUST go through here so the
|
|
7
|
+
* escaping rule is written once and cannot drift across the call sites.
|
|
8
|
+
*
|
|
9
|
+
* DataFusion's string-literal grammar escapes a single quote by doubling it
|
|
10
|
+
* (standard SQL `''`); that is the only escape the engine applies on read-back,
|
|
11
|
+
* which is why doubling is the complete rule for this dialect.
|
|
12
|
+
*/
|
|
13
|
+
export function sqlString(value: string): string {
|
|
14
|
+
return `'${value.replace(/'/g, "''")}'`;
|
|
15
|
+
}
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// ./lancedb-loader.ts for why that matters.
|
|
11
11
|
import type * as lancedb from '@lancedb/lancedb';
|
|
12
12
|
import { logger } from '../logger.ts';
|
|
13
|
+
import { sqlString } from './sql-utils.ts';
|
|
13
14
|
import { metrics } from '../utils/metrics.ts';
|
|
14
15
|
import { StoreDocument } from '../core/interfaces/knowledge-interfaces.ts';
|
|
15
16
|
|
|
@@ -376,9 +377,9 @@ export async function findDocumentsByUrl(
|
|
|
376
377
|
const startTime = Date.now();
|
|
377
378
|
|
|
378
379
|
// Escape single quotes in URL to prevent SQL injection
|
|
379
|
-
const escapedUrl = url
|
|
380
|
+
const escapedUrl = sqlString(url);
|
|
380
381
|
|
|
381
|
-
let filter = `url =
|
|
382
|
+
let filter = `url = ${escapedUrl}`;
|
|
382
383
|
if (scopeFilter) {
|
|
383
384
|
filter = `(${filter}) AND (${scopeFilter})`;
|
|
384
385
|
}
|
package/src/knowledge/store.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
// hoisted into the CLI bundle and loaded at startup. See ./lancedb-loader.ts.
|
|
10
10
|
import type * as lancedb from '@lancedb/lancedb';
|
|
11
11
|
import { getLancedb } from './lancedb-loader.ts';
|
|
12
|
+
import { sqlString } from './sql-utils.ts';
|
|
12
13
|
import { CircuitBreaker } from '../utils/circuit-breaker.ts';
|
|
13
14
|
import { logger } from '../logger.ts';
|
|
14
15
|
import {
|
|
@@ -158,11 +159,11 @@ export class KnowledgeStore implements IKnowledgeStore {
|
|
|
158
159
|
}
|
|
159
160
|
|
|
160
161
|
private getScopeFilter(): string {
|
|
161
|
-
const ws = this.getWorkspace()
|
|
162
|
+
const ws = sqlString(this.getWorkspace());
|
|
162
163
|
|
|
163
164
|
switch (this.options.knowledgeMode) {
|
|
164
165
|
case 'project':
|
|
165
|
-
return `workspace =
|
|
166
|
+
return `workspace = ${ws}`;
|
|
166
167
|
case 'global':
|
|
167
168
|
return 'is_global = true';
|
|
168
169
|
default: // 'none'
|
|
@@ -992,8 +993,8 @@ export class KnowledgeStore implements IKnowledgeStore {
|
|
|
992
993
|
const table = await this.getFreshTable();
|
|
993
994
|
const startTime = Date.now();
|
|
994
995
|
try {
|
|
995
|
-
const escapedUrl = url
|
|
996
|
-
await table.delete(`url =
|
|
996
|
+
const escapedUrl = sqlString(url);
|
|
997
|
+
await table.delete(`url = ${escapedUrl} AND (${scopeFilter})`);
|
|
997
998
|
const duration = Date.now() - startTime;
|
|
998
999
|
metrics.observe('knowledge_store_delete_duration_ms', duration);
|
|
999
1000
|
metrics.increment('knowledge_store_delete_total', 1, { operation: 'by_url', status: 'success' });
|
|
@@ -1048,13 +1049,13 @@ export class KnowledgeStore implements IKnowledgeStore {
|
|
|
1048
1049
|
const table = await this.getFreshTable();
|
|
1049
1050
|
const startTime = Date.now();
|
|
1050
1051
|
try {
|
|
1051
|
-
const escapedUrl = url
|
|
1052
|
-
const escapedType = ingestionType
|
|
1052
|
+
const escapedUrl = sqlString(url);
|
|
1053
|
+
const escapedType = sqlString(ingestionType);
|
|
1053
1054
|
// Integer-coerced so the predicate can never carry anything but digits.
|
|
1054
1055
|
const ageClause = Number.isFinite(olderThan as number)
|
|
1055
1056
|
? ` AND timestamp < ${Math.floor(olderThan as number)}`
|
|
1056
1057
|
: '';
|
|
1057
|
-
await table.delete(`url =
|
|
1058
|
+
await table.delete(`url = ${escapedUrl} AND ingestion_type = ${escapedType} AND (${scopeFilter})${ageClause}`);
|
|
1058
1059
|
const duration = Date.now() - startTime;
|
|
1059
1060
|
metrics.observe('knowledge_store_delete_duration_ms', duration, { operation: 'by_url_and_type' });
|
|
1060
1061
|
metrics.increment('knowledge_store_delete_total', 1, { operation: 'by_url_and_type', status: 'success' });
|
|
@@ -1096,13 +1097,13 @@ export class KnowledgeStore implements IKnowledgeStore {
|
|
|
1096
1097
|
while (retryCount <= MAX_RETRIES) {
|
|
1097
1098
|
const table = await this.getFreshTable();
|
|
1098
1099
|
try {
|
|
1099
|
-
const escapedUrl = url
|
|
1100
|
-
const escapedType = ingestionType
|
|
1100
|
+
const escapedUrl = sqlString(url);
|
|
1101
|
+
const escapedType = sqlString(ingestionType);
|
|
1101
1102
|
// valuesSql with integer-coerced literals: timestamp is an Int64 column,
|
|
1102
1103
|
// and both inputs are integer-coerced so the SQL can never carry
|
|
1103
1104
|
// anything but digits.
|
|
1104
1105
|
await table.update({
|
|
1105
|
-
where: `url =
|
|
1106
|
+
where: `url = ${escapedUrl} AND ingestion_type = ${escapedType} AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
|
|
1106
1107
|
valuesSql: { timestamp: String(Math.floor(newTs)) },
|
|
1107
1108
|
});
|
|
1108
1109
|
logger.log(`[store] Refreshed timestamp for unchanged ${ingestionType} chunks of ${url}`);
|
|
@@ -1202,13 +1203,13 @@ export class KnowledgeStore implements IKnowledgeStore {
|
|
|
1202
1203
|
const scopeFilter = this.getScopeFilter();
|
|
1203
1204
|
|
|
1204
1205
|
const startTime = Date.now();
|
|
1205
|
-
const escapedUrl = url
|
|
1206
|
+
const escapedUrl = sqlString(url);
|
|
1206
1207
|
|
|
1207
1208
|
// limit > 1 deliberately: after a failed prune two generations of this URL can
|
|
1208
1209
|
// coexist, and LanceDB's fragment-scan order typically returns the OLDEST row
|
|
1209
1210
|
// first — limit(1) would serve the superseded content (and feed its older
|
|
1210
1211
|
// timestamp to the serve-age gate) until the next successful ingest.
|
|
1211
|
-
const whereClause = `url =
|
|
1212
|
+
const whereClause = `url = ${escapedUrl} AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
|
|
1212
1213
|
let results = await table
|
|
1213
1214
|
.query()
|
|
1214
1215
|
.where(whereClause)
|
|
@@ -1622,10 +1623,10 @@ export class KnowledgeStore implements IKnowledgeStore {
|
|
|
1622
1623
|
try {
|
|
1623
1624
|
const table = await this.getFreshTable();
|
|
1624
1625
|
const ws = normalizeWorkspacePath(workspace || this.getWorkspace());
|
|
1625
|
-
const escaped = ws
|
|
1626
|
+
const escaped = sqlString(ws);
|
|
1626
1627
|
|
|
1627
1628
|
const [local, global] = await Promise.all([
|
|
1628
|
-
table.countRows(`workspace =
|
|
1629
|
+
table.countRows(`workspace = ${escaped}`),
|
|
1629
1630
|
table.countRows(`is_global = true`)
|
|
1630
1631
|
]);
|
|
1631
1632
|
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import type { ExtensionContext, AgentToolResult } from '@earendil-works/pi-coding-agent';
|
|
8
8
|
import { type Model } from '@earendil-works/pi-ai';
|
|
9
9
|
import { logger } from '../logger.ts';
|
|
10
|
+
import { describeProxyIfBroken } from '../infrastructure/browser/proxy-health.ts';
|
|
10
11
|
import { metrics } from '../utils/metrics.ts';
|
|
11
12
|
import { getSteeringMessages, consumeQueuedMessages, getActiveSteeringMessages, getFailedResearchers, getResearcherFailureReasons, shouldStopResearch, createResearchStopError, hasOnlyCapacityFailures } from './session-state.ts';
|
|
12
13
|
import { MAX_EXTRA_ROUNDS_WITH_STEERING, MIN_SYNTHESIS_PROSE_CHARS, SYNTHESIS_FALLBACK_NOTICE, resolveExcludedTools } from '../constants.ts';
|
|
@@ -150,6 +151,26 @@ export class DeepResearchOrchestrator {
|
|
|
150
151
|
// which already passes ctx).
|
|
151
152
|
await orchestrationService.cleanupResearchServices(undefined, researchId, ctx, this.config);
|
|
152
153
|
|
|
154
|
+
// A configured-but-broken SOCKS proxy fails EVERY browser request. Only the
|
|
155
|
+
// UI health gate and the quick orchestrator run a pre-flight check; a deep
|
|
156
|
+
// run has no such gate, so without this the whole search burst is spent
|
|
157
|
+
// first (36 queries, ~7 minutes on 2026-10-30) and then dies with the
|
|
158
|
+
// generic "Search completely failed". One probe costs seconds.
|
|
159
|
+
//
|
|
160
|
+
// Bounded generously (3s connect + 3-4s data, then a neutral-host check): the
|
|
161
|
+
// point is to catch a dead or one-way tunnel, not to convict a proxy that is
|
|
162
|
+
// merely slow on a loaded box.
|
|
163
|
+
// The run signal is passed through so Esc during a dead proxy's probe sequence
|
|
164
|
+
// cancels immediately instead of waiting out both attempts.
|
|
165
|
+
const proxyDiagnosis = await describeProxyIfBroken(signal);
|
|
166
|
+
if (signal?.aborted) return '';
|
|
167
|
+
if (proxyDiagnosis) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`Research cannot start: ${proxyDiagnosis} ` +
|
|
170
|
+
'Repair or remove ~/.pi/research/proxy.json (docs/TROUBLESHOOTING.md), then rerun.',
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
153
174
|
logger.log(`[DeepOrchestrator] Starting multi-round research (complexity ${complexity}) for: "${query}" (Run: ${researchId})`);
|
|
154
175
|
metrics.increment('research_sessions_total', 1, { mode: 'deep', complexity: String(complexity) });
|
|
155
176
|
|
|
@@ -24,7 +24,7 @@ import { isAbortSentinel, boundSessionAbort } from './abort-utils.ts';
|
|
|
24
24
|
import type { RunResearcherOptions } from './orchestration-types.ts';
|
|
25
25
|
import { search } from '../web-research/search.ts';
|
|
26
26
|
import { RESEARCHER_DIGEST_SECTION } from '../utils/coverage-digest.ts';
|
|
27
|
-
import { isRateLimitError, isSpentAccountError, parseRetryAfterMs, rateLimitBackoffMs } from '../utils/provider-errors.ts';
|
|
27
|
+
import { isRateLimitError, isSpentAccountError, parseRetryAfterMs, rateLimitBackoffMs, RATE_LIMIT_TOTAL_WAIT_MAX_MS } from '../utils/provider-errors.ts';
|
|
28
28
|
|
|
29
29
|
/**
|
|
30
30
|
* Failures a retry cannot fix, because the next attempt sends the same request to
|
|
@@ -233,6 +233,11 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
|
|
|
233
233
|
// rate limit: the next backoff uses the provider's Retry-After (or the long
|
|
234
234
|
// rate-limit step) instead of the small exponential 1-2s step.
|
|
235
235
|
let inFlightBackoffMs: number | null = null;
|
|
236
|
+
// Provider-capacity waits already spent by THIS researcher. Bounds the case the
|
|
237
|
+
// rate-limit path made possible: a provider stating a long window on every
|
|
238
|
+
// attempt ("requested 120s retry delay"), which would otherwise spend most of a
|
|
239
|
+
// run's budget sleeping inside one researcher.
|
|
240
|
+
let capacityWaitSpentMs = 0;
|
|
236
241
|
|
|
237
242
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
238
243
|
// Launch boundary: never build a session for a run that is already cancelled
|
|
@@ -638,6 +643,28 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
|
|
|
638
643
|
metrics.increment('researcher_rate_limit_backoff_total', 1, { mode: 'deep', complexity: String(complexity) });
|
|
639
644
|
logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
|
|
640
645
|
}
|
|
646
|
+
|
|
647
|
+
// Bound total capacity waiting, and FAIL WITH A TIME when the bound is the
|
|
648
|
+
// reason. `break` (not throw) so the loop's own lastError wins and every
|
|
649
|
+
// caller keeps its existing failure classification. Issue #22: eight runs
|
|
650
|
+
// died on 3 x 1s/2s retries against a provider that had asked for 120s.
|
|
651
|
+
if (inFlightBackoffMs !== null) {
|
|
652
|
+
const remainingBudgetMs = RATE_LIMIT_TOTAL_WAIT_MAX_MS - capacityWaitSpentMs;
|
|
653
|
+
if (inFlightBackoffMs > remainingBudgetMs) {
|
|
654
|
+
const windowSeconds = Math.ceil(inFlightBackoffMs / 1000);
|
|
655
|
+
const retryAt = new Date(Date.now() + inFlightBackoffMs).toISOString().slice(11, 19);
|
|
656
|
+
lastError = new Error(
|
|
657
|
+
`Provider capacity: it asked for a ${windowSeconds}s cool-off, but this researcher ` +
|
|
658
|
+
`has only ${Math.max(0, Math.round(remainingBudgetMs / 1000))}s of its ` +
|
|
659
|
+
`${Math.round(RATE_LIMIT_TOTAL_WAIT_MAX_MS / 1000)}s capacity-wait budget left. ` +
|
|
660
|
+
`Rerun after ${retryAt}Z. Cause: ${errMsg}`,
|
|
661
|
+
);
|
|
662
|
+
logger.error(`[ResearcherExecutor] Researcher ${id} stopping instead of waiting ${inFlightBackoffMs}ms (capacity budget exhausted); rerun after ${retryAt}Z`);
|
|
663
|
+
metrics.increment('researcher_capacity_budget_exhausted_total', 1, { mode: 'deep', complexity: String(complexity) });
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
capacityWaitSpentMs += inFlightBackoffMs;
|
|
667
|
+
}
|
|
641
668
|
}
|
|
642
669
|
|
|
643
670
|
if (attempt < maxAttempts) {
|