@lincoln504/pi-research 1.7.23 → 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 +347 -36
- package/docs/CHANGELOG.md +110 -0
- package/docs/CONFIGURATION.md +3 -3
- package/docs/TROUBLESHOOTING.md +92 -0
- package/package.json +1 -1
- package/scripts/ddg-socks-proxy.mjs +105 -15
- 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/orchestration/deep-research-orchestrator.ts +21 -0
- package/src/orchestration/researcher-executor.ts +28 -1
- package/src/utils/provider-errors.ts +61 -9
- package/src/web-research/browser-search.ts +13 -1
- package/src/web-research/retry-utils.ts +29 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
name: pi-research
|
|
3
3
|
description: "Multi-agent web research for any coding agent. Use for anything requiring current information from the internet — news, trends, product/service/company facts, statistics, people, places, events, APIs, library behavior, or 'what is X / how does X work' questions. Also use to search a local knowledge store of previously researched findings before doing live research. Powered by the pi-research engine (search, stealth scraping, security databases, Stack Exchange). Not for reading local files, running project commands, or analyzing this repository's own source."
|
|
4
4
|
license: MIT
|
|
5
|
-
metadata: { "author": "Lincoln Deen", "version": "1.7.
|
|
5
|
+
metadata: { "author": "Lincoln Deen", "version": "1.7.24", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
|
|
6
6
|
allowed-tools: Bash(node:*)
|
|
7
7
|
---
|
|
8
8
|
|
package/dist/cli.mjs
CHANGED
|
@@ -3039,11 +3039,11 @@ function createConfig(env, processEnv) {
|
|
|
3039
3039
|
}
|
|
3040
3040
|
function getConfig(cwd = process.cwd(), iface) {
|
|
3041
3041
|
const cacheKey = `${normalizeWorkspacePath(cwd)}:${iface ?? ""}`;
|
|
3042
|
-
const
|
|
3043
|
-
if (
|
|
3044
|
-
return
|
|
3042
|
+
const cached2 = configCache.get(cacheKey);
|
|
3043
|
+
if (cached2 && configFingerprints.get(cacheKey) === configSourcesFingerprint(cwd, iface)) {
|
|
3044
|
+
return cached2;
|
|
3045
3045
|
}
|
|
3046
|
-
if (
|
|
3046
|
+
if (cached2) {
|
|
3047
3047
|
logger.info(`[config] Configuration files changed on disk; reloading for ${cwd} (cached values were from process start)`);
|
|
3048
3048
|
}
|
|
3049
3049
|
const fingerprint = configSourcesFingerprint(cwd, iface);
|
|
@@ -4209,6 +4209,7 @@ async function retryWithBackoff(fn, options = {}) {
|
|
|
4209
4209
|
const startTime = Date.now();
|
|
4210
4210
|
let lastError = null;
|
|
4211
4211
|
let attempt = 0;
|
|
4212
|
+
let totalDelayMs = 0;
|
|
4212
4213
|
metrics.increment("retry_attempts_total", 1, { label: opts.label });
|
|
4213
4214
|
while (attempt <= opts.maxRetries) {
|
|
4214
4215
|
try {
|
|
@@ -4234,6 +4235,15 @@ async function retryWithBackoff(fn, options = {}) {
|
|
|
4234
4235
|
const jitter = Math.random() * 0.5 * baseDelay;
|
|
4235
4236
|
const override = opts.delayFor?.(attempt + 2, lastError);
|
|
4236
4237
|
const delay2 = override != null && Number.isFinite(override) && override > 0 ? Math.round(override) : Math.min(baseDelay + jitter, opts.maxDelay);
|
|
4238
|
+
if (opts.maxTotalDelayMs !== void 0 && totalDelayMs + delay2 > opts.maxTotalDelayMs) {
|
|
4239
|
+
const retryAt = new Date(Date.now() + delay2).toISOString().slice(11, 19);
|
|
4240
|
+
metrics.increment("retry_total_delay_exhausted_total", 1, { label: opts.label });
|
|
4241
|
+
throw new Error(
|
|
4242
|
+
`Provider capacity: ${opts.label} asked for a ${Math.round(delay2 / 1e3)}s wait, but only ${Math.max(0, Math.round((opts.maxTotalDelayMs - totalDelayMs) / 1e3))}s of its ${Math.round(opts.maxTotalDelayMs / 1e3)}s total-wait budget is left. Rerun after ${retryAt}Z. Cause: ${lastError.message}`,
|
|
4243
|
+
{ cause: error }
|
|
4244
|
+
);
|
|
4245
|
+
}
|
|
4246
|
+
totalDelayMs += delay2;
|
|
4237
4247
|
metrics.increment("retry_backoff_total", 1, { attempt: String(attempt), label: opts.label });
|
|
4238
4248
|
metrics.observe("retry_backoff_delay_ms", delay2, { attempt: String(attempt), label: opts.label });
|
|
4239
4249
|
logger.warn(`[Retry] ${opts.label} failed (attempt ${attempt + 1}/${opts.maxRetries + 1}), retrying in ${Math.round(delay2)}ms: ${lastError.message}`);
|
|
@@ -4924,10 +4934,10 @@ async function resolveEmbeddingDevice(requested, model, timeoutMs) {
|
|
|
4924
4934
|
if (requested === "cpu") return "cpu";
|
|
4925
4935
|
if (requested === "webgpu") return "webgpu";
|
|
4926
4936
|
const signature = hostSignature(model);
|
|
4927
|
-
const
|
|
4928
|
-
if (
|
|
4929
|
-
logger.info(`[embedder] WebGPU viability (cached verdict): ${
|
|
4930
|
-
return
|
|
4937
|
+
const cached2 = await readVerdict(signature);
|
|
4938
|
+
if (cached2 !== null) {
|
|
4939
|
+
logger.info(`[embedder] WebGPU viability (cached verdict): ${cached2 ? "viable -> webgpu" : "not viable -> cpu"}`);
|
|
4940
|
+
return cached2 ? "webgpu" : "cpu";
|
|
4931
4941
|
}
|
|
4932
4942
|
if (!await isModelCached(model)) {
|
|
4933
4943
|
logger.info("[embedder] Embedding model not cached yet \u2014 using CPU for now; WebGPU will be probed once the model is present.");
|
|
@@ -5144,17 +5154,17 @@ var init_embedder = __esm({
|
|
|
5144
5154
|
this.device = "cpu";
|
|
5145
5155
|
}
|
|
5146
5156
|
}
|
|
5147
|
-
const
|
|
5157
|
+
const cached2 = await isModelCached(this.model);
|
|
5148
5158
|
logger.info(
|
|
5149
|
-
`[embedder] Loading model: ${this.model} (${
|
|
5159
|
+
`[embedder] Loading model: ${this.model} (${cached2 ? "from local cache" : "downloading from HuggingFace"})...`
|
|
5150
5160
|
);
|
|
5151
5161
|
const env = await getHFEnv();
|
|
5152
5162
|
const prevAllowRemote = env.allowRemoteModels;
|
|
5153
|
-
if (
|
|
5163
|
+
if (cached2) {
|
|
5154
5164
|
env.allowRemoteModels = false;
|
|
5155
5165
|
}
|
|
5156
5166
|
try {
|
|
5157
|
-
const timeoutMs =
|
|
5167
|
+
const timeoutMs = cached2 ? 3e4 : this.initializationTimeoutMs;
|
|
5158
5168
|
const { pipeline: loadedPipeline } = await loadPipelineWithTimeout(this.model, this.device, timeoutMs, this.useCache);
|
|
5159
5169
|
this.pipeline = loadedPipeline;
|
|
5160
5170
|
logger.info(`[embedder] Pipeline loaded (device: ${this.device})`);
|
|
@@ -5175,7 +5185,7 @@ var init_embedder = __esm({
|
|
|
5175
5185
|
this.pipeline = result.pipeline ?? null;
|
|
5176
5186
|
this.device = "cpu";
|
|
5177
5187
|
this.gpuLockHeld = false;
|
|
5178
|
-
} else if (
|
|
5188
|
+
} else if (cached2 && isCorruptModelError(loadErr)) {
|
|
5179
5189
|
const errMsg = loadErr instanceof Error ? loadErr.message : String(loadErr);
|
|
5180
5190
|
logger.warn(`[embedder] Corrupt model cache detected on load (${errMsg}); purging and re-downloading once`);
|
|
5181
5191
|
await purgeModelCache(this.model);
|
|
@@ -6780,8 +6790,8 @@ var init_file_lock_service = __esm({
|
|
|
6780
6790
|
async _resolveOwnerAlive(pid, startTime, memo) {
|
|
6781
6791
|
if (!memo) return this._isOwnerAlive(pid, startTime);
|
|
6782
6792
|
const key = `${pid ?? "null"}:${startTime ?? "null"}`;
|
|
6783
|
-
const
|
|
6784
|
-
if (
|
|
6793
|
+
const cached2 = memo.get(key);
|
|
6794
|
+
if (cached2 !== void 0) return cached2;
|
|
6785
6795
|
const alive = await this._isOwnerAlive(pid, startTime);
|
|
6786
6796
|
memo.set(key, alive);
|
|
6787
6797
|
return alive;
|
|
@@ -11347,24 +11357,26 @@ function isSpentAccountError(error) {
|
|
|
11347
11357
|
function isRateLimitError(error) {
|
|
11348
11358
|
if (isSpentAccountError(error)) return false;
|
|
11349
11359
|
const msg2 = (error instanceof Error ? error.message : String(error)).toLowerCase();
|
|
11350
|
-
return /\b429\b/.test(msg2) || msg2.includes("rate limit") || msg2.includes("rate-limit") || msg2.includes("rate limited") || msg2.includes("too many requests") || msg2.includes("engine_overloaded") || msg2.includes("provider_overloaded");
|
|
11360
|
+
return /\b429\b/.test(msg2) || /\b(?:http|status|code|error|response|returned)\W{0,4}50[0234]\b/i.test(msg2) || /\b50[0234]\b\W{0,4}(?:provider|service|unavailable|bad|gateway|internal|error|timeout)/i.test(msg2) || msg2.includes("service unavailable") || msg2.includes("bad gateway") || msg2.includes("gateway timeout") || msg2.includes("rate limit") || msg2.includes("rate-limit") || msg2.includes("rate limited") || msg2.includes("too many requests") || msg2.includes("retry delay") || msg2.includes("retry-after") || msg2.includes("engine_overloaded") || msg2.includes("provider_overloaded");
|
|
11351
11361
|
}
|
|
11352
11362
|
function isCapacityFailureReason(reason) {
|
|
11353
11363
|
return reason !== void 0 && reason !== "" && isRateLimitError(reason);
|
|
11354
11364
|
}
|
|
11355
11365
|
function parseRetryAfterMs(error) {
|
|
11356
11366
|
const message = error instanceof Error ? error.message : String(error);
|
|
11357
|
-
const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
|
|
11367
|
+
const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message) || /requested\s+(\d{1,4})\s*s(?:ec(?:onds?)?)?\s+retry\s+delay/i.exec(message) || /retry\s+after\s+(\d{1,4})\s*s/i.exec(message);
|
|
11358
11368
|
if (!m) return null;
|
|
11359
11369
|
const seconds = Number(m[1]);
|
|
11360
11370
|
if (!Number.isFinite(seconds) || seconds <= 0) return null;
|
|
11361
|
-
return Math.min(Math.max(seconds, 5),
|
|
11371
|
+
return Math.min(Math.max(seconds, 5), STATED_RETRY_AFTER_MAX_MS / 1e3) * 1e3;
|
|
11362
11372
|
}
|
|
11363
11373
|
var RATE_LIMIT_BACKOFF_BASE_MS = 15e3;
|
|
11364
11374
|
var RATE_LIMIT_BACKOFF_MAX_MS = 6e4;
|
|
11375
|
+
var STATED_RETRY_AFTER_MAX_MS = 18e4;
|
|
11376
|
+
var RATE_LIMIT_TOTAL_WAIT_MAX_MS = 24e4;
|
|
11365
11377
|
function rateLimitBackoffMs(attempt, retryAfterMs, random = Math.random) {
|
|
11366
11378
|
if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
|
|
11367
|
-
return
|
|
11379
|
+
return Math.min(Math.max(Math.round(retryAfterMs), 1e3), STATED_RETRY_AFTER_MAX_MS);
|
|
11368
11380
|
}
|
|
11369
11381
|
const exponent = Math.max(0, attempt - 2);
|
|
11370
11382
|
const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
|
|
@@ -12305,7 +12317,10 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
|
|
|
12305
12317
|
label: "coordinator-generatePlan",
|
|
12306
12318
|
signal,
|
|
12307
12319
|
isTransientError: (err) => isRetriableLlmError(err, signal),
|
|
12308
|
-
delayFor: rateLimitDelayFor
|
|
12320
|
+
delayFor: rateLimitDelayFor,
|
|
12321
|
+
// Bound the TOTAL wait for THIS call: a provider that keeps asking for
|
|
12322
|
+
// a long window must not spend the run's whole budget sleeping here.
|
|
12323
|
+
maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS
|
|
12309
12324
|
}
|
|
12310
12325
|
);
|
|
12311
12326
|
recordLlmUsage(model, response.usage, { component: "coordinator", complexity, observer });
|
|
@@ -12720,7 +12735,10 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
|
|
|
12720
12735
|
label,
|
|
12721
12736
|
signal,
|
|
12722
12737
|
isTransientError: (err) => isRetriableLlmError(err, signal),
|
|
12723
|
-
delayFor: rateLimitDelayFor
|
|
12738
|
+
delayFor: rateLimitDelayFor,
|
|
12739
|
+
// Bound the TOTAL wait for THIS call: a provider that keeps asking for
|
|
12740
|
+
// a long window must not spend the run's whole budget sleeping here.
|
|
12741
|
+
maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS
|
|
12724
12742
|
}
|
|
12725
12743
|
);
|
|
12726
12744
|
recordLlmUsage(model, response.usage, { component: args.component, complexity, observer });
|
|
@@ -18316,8 +18334,8 @@ async function isRegisteredLeaderAliveUncached(container) {
|
|
|
18316
18334
|
const info = await stateManager.getBrowserServer();
|
|
18317
18335
|
if (!info) return false;
|
|
18318
18336
|
const schedulerService = await getService(ServiceNames.SCHEDULER, void 0, container);
|
|
18319
|
-
const
|
|
18320
|
-
if (
|
|
18337
|
+
const cached2 = schedulerService.getSchedulerInstance();
|
|
18338
|
+
if (cached2 instanceof BrowserClient && cached2.targetPort !== info.port) return false;
|
|
18321
18339
|
return await stateManager.isPidAlive(info.pid, info.schedulerId);
|
|
18322
18340
|
} catch {
|
|
18323
18341
|
return false;
|
|
@@ -18487,6 +18505,246 @@ async function runWorkerSearch(query, config, signal, retries = 1, sessionId, co
|
|
|
18487
18505
|
}
|
|
18488
18506
|
}
|
|
18489
18507
|
|
|
18508
|
+
// src/infrastructure/browser/proxy-health.ts
|
|
18509
|
+
import net3 from "node:net";
|
|
18510
|
+
|
|
18511
|
+
// src/infrastructure/browser/proxy-prefs.ts
|
|
18512
|
+
import { existsSync as existsSync12, readFileSync as readFileSync7 } from "node:fs";
|
|
18513
|
+
import { homedir as homedir6 } from "node:os";
|
|
18514
|
+
function proxyConfigPath() {
|
|
18515
|
+
return process.env["PI_RESEARCH_PROXY_JSON"] || `${homedir6()}/.pi/research/proxy.json`;
|
|
18516
|
+
}
|
|
18517
|
+
var cached;
|
|
18518
|
+
var cachedAt = 0;
|
|
18519
|
+
var CACHE_TTL_MS = 1e4;
|
|
18520
|
+
function getSocksProxyEndpoint() {
|
|
18521
|
+
const now = Date.now();
|
|
18522
|
+
if (cached !== void 0 && now - cachedAt < CACHE_TTL_MS) return cached;
|
|
18523
|
+
cachedAt = now;
|
|
18524
|
+
try {
|
|
18525
|
+
const file = proxyConfigPath();
|
|
18526
|
+
if (!existsSync12(file)) {
|
|
18527
|
+
cached = null;
|
|
18528
|
+
return cached;
|
|
18529
|
+
}
|
|
18530
|
+
const cfg = JSON.parse(readFileSync7(file, "utf8"));
|
|
18531
|
+
const host = cfg.host === void 0 ? "127.0.0.1" : typeof cfg.host === "string" ? cfg.host.trim() : "";
|
|
18532
|
+
const port = cfg.port === void 0 ? 1080 : Number.isInteger(cfg.port) ? cfg.port : -1;
|
|
18533
|
+
if (host === "" || port < 1 || port > 65535) {
|
|
18534
|
+
cached = null;
|
|
18535
|
+
return cached;
|
|
18536
|
+
}
|
|
18537
|
+
cached = { host, port };
|
|
18538
|
+
return cached;
|
|
18539
|
+
} catch {
|
|
18540
|
+
cached = null;
|
|
18541
|
+
return cached;
|
|
18542
|
+
}
|
|
18543
|
+
}
|
|
18544
|
+
|
|
18545
|
+
// src/infrastructure/browser/proxy-health.ts
|
|
18546
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
18547
|
+
var DEFAULT_DATA_TIMEOUT_MS = 8e3;
|
|
18548
|
+
var DEFAULT_TARGET_HOST = "lite.duckduckgo.com";
|
|
18549
|
+
var DEFAULT_TARGET_PORT = 80;
|
|
18550
|
+
var NEUTRAL_TARGET_HOST = "example.com";
|
|
18551
|
+
var NEUTRAL_TARGET_PORT = 80;
|
|
18552
|
+
function fail(code, reason, endpoint, startedAt) {
|
|
18553
|
+
return { healthy: false, code, reason, endpoint, latencyMs: Date.now() - startedAt };
|
|
18554
|
+
}
|
|
18555
|
+
function probeSocksProxyForwarding(endpoint = getSocksProxyEndpoint(), options = {}) {
|
|
18556
|
+
const startedAt = Date.now();
|
|
18557
|
+
if (!endpoint) {
|
|
18558
|
+
return Promise.resolve({
|
|
18559
|
+
healthy: true,
|
|
18560
|
+
code: "not-configured",
|
|
18561
|
+
reason: "no SOCKS proxy configured (browser connects directly)",
|
|
18562
|
+
endpoint: null,
|
|
18563
|
+
latencyMs: 0
|
|
18564
|
+
});
|
|
18565
|
+
}
|
|
18566
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
18567
|
+
const dataTimeoutMs = options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS;
|
|
18568
|
+
const targetHost = options.targetHost ?? DEFAULT_TARGET_HOST;
|
|
18569
|
+
const targetPort = options.targetPort ?? DEFAULT_TARGET_PORT;
|
|
18570
|
+
const where = `${endpoint.host}:${endpoint.port}`;
|
|
18571
|
+
return new Promise((resolve9) => {
|
|
18572
|
+
const socket = net3.connect({ host: endpoint.host, port: endpoint.port });
|
|
18573
|
+
let stage = "greet";
|
|
18574
|
+
let settled = false;
|
|
18575
|
+
let buffer = Buffer.alloc(0);
|
|
18576
|
+
let connectTimer;
|
|
18577
|
+
let dataTimer;
|
|
18578
|
+
const onAbort = () => {
|
|
18579
|
+
finish(fail("aborted", "proxy probe cancelled by the caller", endpoint, startedAt));
|
|
18580
|
+
};
|
|
18581
|
+
const finish = (result) => {
|
|
18582
|
+
if (settled) return;
|
|
18583
|
+
settled = true;
|
|
18584
|
+
clearTimeout(connectTimer);
|
|
18585
|
+
clearTimeout(dataTimer);
|
|
18586
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
18587
|
+
socket.destroy();
|
|
18588
|
+
resolve9(result);
|
|
18589
|
+
};
|
|
18590
|
+
if (options.signal?.aborted) {
|
|
18591
|
+
onAbort();
|
|
18592
|
+
return;
|
|
18593
|
+
}
|
|
18594
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
18595
|
+
connectTimer = setTimeout(() => {
|
|
18596
|
+
finish(fail(
|
|
18597
|
+
stage === "greet" ? "unreachable" : "no-data",
|
|
18598
|
+
stage === "greet" ? `proxy at ${where} did not accept a TCP connection within ${timeoutMs}ms` : `proxy at ${where} accepted the connection but did not answer within ${timeoutMs}ms`,
|
|
18599
|
+
endpoint,
|
|
18600
|
+
startedAt
|
|
18601
|
+
));
|
|
18602
|
+
}, timeoutMs);
|
|
18603
|
+
connectTimer.unref?.();
|
|
18604
|
+
const armDataTimer = () => {
|
|
18605
|
+
dataTimer = setTimeout(() => {
|
|
18606
|
+
finish(fail(
|
|
18607
|
+
"no-data",
|
|
18608
|
+
`proxy at ${where} completed the SOCKS handshake to ${targetHost}:${targetPort} but returned no data within ${dataTimeoutMs}ms (the tunnel is not forwarding answers \u2014 check that the proxy process is running the current script and restart it)`,
|
|
18609
|
+
endpoint,
|
|
18610
|
+
startedAt
|
|
18611
|
+
));
|
|
18612
|
+
}, dataTimeoutMs);
|
|
18613
|
+
dataTimer.unref?.();
|
|
18614
|
+
};
|
|
18615
|
+
socket.on("connect", () => {
|
|
18616
|
+
socket.write(Buffer.from([5, 1, 0]));
|
|
18617
|
+
});
|
|
18618
|
+
socket.on("data", (chunk) => {
|
|
18619
|
+
if (settled) return;
|
|
18620
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
18621
|
+
if (stage === "greet") {
|
|
18622
|
+
if (buffer.length < 2) return;
|
|
18623
|
+
if (buffer[0] !== 5 || buffer[1] !== 0) {
|
|
18624
|
+
finish(fail(
|
|
18625
|
+
"protocol-error",
|
|
18626
|
+
`proxy at ${where} answered the SOCKS greeting with [${[...buffer.subarray(0, 2)]}] instead of [5,0]`,
|
|
18627
|
+
endpoint,
|
|
18628
|
+
startedAt
|
|
18629
|
+
));
|
|
18630
|
+
return;
|
|
18631
|
+
}
|
|
18632
|
+
buffer = buffer.subarray(2);
|
|
18633
|
+
const hostBytes = Buffer.from(targetHost, "utf8");
|
|
18634
|
+
socket.write(Buffer.concat([
|
|
18635
|
+
Buffer.from([5, 1, 0, 3, hostBytes.length]),
|
|
18636
|
+
hostBytes,
|
|
18637
|
+
Buffer.from([targetPort >> 8 & 255, targetPort & 255])
|
|
18638
|
+
]));
|
|
18639
|
+
stage = "connect";
|
|
18640
|
+
return;
|
|
18641
|
+
}
|
|
18642
|
+
if (stage === "connect") {
|
|
18643
|
+
if (buffer.length < 4) return;
|
|
18644
|
+
if (buffer[0] !== 5) {
|
|
18645
|
+
finish(fail("protocol-error", `proxy at ${where} answered the SOCKS request malformed`, endpoint, startedAt));
|
|
18646
|
+
return;
|
|
18647
|
+
}
|
|
18648
|
+
const reply = buffer[1];
|
|
18649
|
+
if (reply !== 0) {
|
|
18650
|
+
const meaning = reply === 2 ? "refused by ruleset" : reply === 3 ? "network unreachable" : reply === 4 ? "host unreachable" : reply === 5 ? "connection refused by the target" : `SOCKS error ${reply}`;
|
|
18651
|
+
finish(fail(
|
|
18652
|
+
"connect-rejected",
|
|
18653
|
+
`proxy at ${where} refused CONNECT to ${targetHost}:${targetPort} (${meaning})`,
|
|
18654
|
+
endpoint,
|
|
18655
|
+
startedAt
|
|
18656
|
+
));
|
|
18657
|
+
return;
|
|
18658
|
+
}
|
|
18659
|
+
const atyp = buffer[3];
|
|
18660
|
+
let addrLen;
|
|
18661
|
+
if (atyp === 1) {
|
|
18662
|
+
addrLen = 4;
|
|
18663
|
+
} else if (atyp === 4) {
|
|
18664
|
+
addrLen = 16;
|
|
18665
|
+
} else if (atyp === 3) {
|
|
18666
|
+
if (buffer.length < 5) return;
|
|
18667
|
+
addrLen = 1 + (buffer[4] ?? 0);
|
|
18668
|
+
} else {
|
|
18669
|
+
finish(fail("protocol-error", `proxy at ${where} answered CONNECT with unknown address type ${atyp}`, endpoint, startedAt));
|
|
18670
|
+
return;
|
|
18671
|
+
}
|
|
18672
|
+
const replyLen = 4 + addrLen + 2;
|
|
18673
|
+
if (buffer.length < replyLen) return;
|
|
18674
|
+
buffer = buffer.subarray(replyLen);
|
|
18675
|
+
clearTimeout(connectTimer);
|
|
18676
|
+
socket.write(
|
|
18677
|
+
`GET / HTTP/1.0\r
|
|
18678
|
+
Host: ${targetHost}\r
|
|
18679
|
+
Connection: close\r
|
|
18680
|
+
\r
|
|
18681
|
+
`
|
|
18682
|
+
);
|
|
18683
|
+
stage = "data";
|
|
18684
|
+
armDataTimer();
|
|
18685
|
+
if (buffer.length > 0) {
|
|
18686
|
+
finish({
|
|
18687
|
+
healthy: true,
|
|
18688
|
+
code: "ok",
|
|
18689
|
+
reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
|
|
18690
|
+
endpoint,
|
|
18691
|
+
latencyMs: Date.now() - startedAt
|
|
18692
|
+
});
|
|
18693
|
+
}
|
|
18694
|
+
return;
|
|
18695
|
+
}
|
|
18696
|
+
finish({
|
|
18697
|
+
healthy: true,
|
|
18698
|
+
code: "ok",
|
|
18699
|
+
reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
|
|
18700
|
+
endpoint,
|
|
18701
|
+
latencyMs: Date.now() - startedAt
|
|
18702
|
+
});
|
|
18703
|
+
});
|
|
18704
|
+
socket.on("error", (err) => {
|
|
18705
|
+
const detail = err.code === "ECONNREFUSED" ? "nothing is listening there \u2014 is the proxy service running?" : err.message;
|
|
18706
|
+
finish(fail("unreachable", `proxy at ${where} is unusable: ${detail}`, endpoint, startedAt));
|
|
18707
|
+
});
|
|
18708
|
+
socket.on("close", () => {
|
|
18709
|
+
finish(fail(
|
|
18710
|
+
"no-data",
|
|
18711
|
+
`proxy at ${where} closed the tunnel before returning data`,
|
|
18712
|
+
endpoint,
|
|
18713
|
+
startedAt
|
|
18714
|
+
));
|
|
18715
|
+
});
|
|
18716
|
+
});
|
|
18717
|
+
}
|
|
18718
|
+
async function describeProxyIfBroken(signal, options = {}) {
|
|
18719
|
+
const endpoint = getSocksProxyEndpoint();
|
|
18720
|
+
if (!endpoint) return null;
|
|
18721
|
+
const opts = {
|
|
18722
|
+
timeoutMs: options.timeoutMs ?? 3e3,
|
|
18723
|
+
dataTimeoutMs: options.dataTimeoutMs ?? 3e3,
|
|
18724
|
+
signal
|
|
18725
|
+
};
|
|
18726
|
+
let last = await probeSocksProxyForwarding(endpoint, opts);
|
|
18727
|
+
if (last.code === "aborted") return null;
|
|
18728
|
+
if (!last.healthy) {
|
|
18729
|
+
last = await probeSocksProxyForwarding(endpoint, {
|
|
18730
|
+
...opts,
|
|
18731
|
+
dataTimeoutMs: options.dataTimeoutMs ?? 4e3
|
|
18732
|
+
});
|
|
18733
|
+
if (last.code === "aborted") return null;
|
|
18734
|
+
}
|
|
18735
|
+
if (last.healthy) return null;
|
|
18736
|
+
const neutral = await probeSocksProxyForwarding(endpoint, {
|
|
18737
|
+
...opts,
|
|
18738
|
+
targetHost: NEUTRAL_TARGET_HOST,
|
|
18739
|
+
targetPort: NEUTRAL_TARGET_PORT
|
|
18740
|
+
});
|
|
18741
|
+
if (neutral.code === "aborted") return null;
|
|
18742
|
+
if (neutral.healthy) {
|
|
18743
|
+
return `SOCKS proxy check: the proxy forwards traffic to example.com, but DuckDuckGo is unreachable through it (${last.reason}). The tunnel works; the pinned DuckDuckGo front doors are not answering. Update DDG_PIN_IPS in the proxy service or remove ~/.pi/research/proxy.json.`;
|
|
18744
|
+
}
|
|
18745
|
+
return `SOCKS proxy check: ${last.reason}. The proxy did not forward traffic to example.com either, so the tunnel itself is broken.`;
|
|
18746
|
+
}
|
|
18747
|
+
|
|
18490
18748
|
// src/web-research/browser-search.ts
|
|
18491
18749
|
init_logger();
|
|
18492
18750
|
init_safe_unref();
|
|
@@ -18630,8 +18888,9 @@ async function performSearch(queries, config, signal, onProgress, container = ge
|
|
|
18630
18888
|
`Search completely failed: ${reason}, all with a missing native module. This is an incomplete install, not a network problem: the browser launcher's native dependency (impit) ships a prebuilt binding per platform as a separate package, and npm sometimes drops it (npm/cli#4828). Reinstall this package (npm install, or pi install again) to restore it.` + (sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : "")
|
|
18631
18889
|
);
|
|
18632
18890
|
}
|
|
18891
|
+
const proxyDiagnosis = await describeProxyIfBroken(signal);
|
|
18633
18892
|
throw new Error(
|
|
18634
|
-
`Search completely failed: ${reason}. Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under extreme load.` + (sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : "")
|
|
18893
|
+
`Search completely failed: ${reason}. ` + (proxyDiagnosis ? `${proxyDiagnosis} Every browser request is routed through the configured proxy, so no search can succeed until it forwards DuckDuckGo traffic or ~/.pi/research/proxy.json is removed.` : `Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under extreme load.`) + (sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : "")
|
|
18635
18894
|
);
|
|
18636
18895
|
}
|
|
18637
18896
|
const totalDuration = Date.now() - startTime;
|
|
@@ -18836,6 +19095,35 @@ function registerHealthChecks(registry, container = getServiceContainer()) {
|
|
|
18836
19095
|
return { healthy: false, error: `Browser healthcheck failed: ${e instanceof Error ? e.message : String(e)}` };
|
|
18837
19096
|
}
|
|
18838
19097
|
}, { timeoutMs: Math.max(healthTimeoutMs, 15e4, getHealthCheckBudgetMs(config)), critical: true });
|
|
19098
|
+
registry.register("SocksProxy", async () => {
|
|
19099
|
+
const endpoint = getSocksProxyEndpoint();
|
|
19100
|
+
if (!endpoint) {
|
|
19101
|
+
return { healthy: true, diagnostic: { status: "not configured (browser connects directly)" } };
|
|
19102
|
+
}
|
|
19103
|
+
const probe = await probeSocksProxyForwarding(endpoint, { timeoutMs: 4e3, dataTimeoutMs: 5e3 });
|
|
19104
|
+
if (probe.healthy) {
|
|
19105
|
+
return {
|
|
19106
|
+
healthy: true,
|
|
19107
|
+
diagnostic: {
|
|
19108
|
+
status: `forwarding via ${endpoint.host}:${endpoint.port}`,
|
|
19109
|
+
firstByteMs: probe.latencyMs
|
|
19110
|
+
}
|
|
19111
|
+
};
|
|
19112
|
+
}
|
|
19113
|
+
const neutral = await probeSocksProxyForwarding(endpoint, {
|
|
19114
|
+
timeoutMs: 4e3,
|
|
19115
|
+
dataTimeoutMs: 5e3,
|
|
19116
|
+
targetHost: NEUTRAL_TARGET_HOST,
|
|
19117
|
+
targetPort: NEUTRAL_TARGET_PORT
|
|
19118
|
+
});
|
|
19119
|
+
if (neutral.healthy) {
|
|
19120
|
+
return {
|
|
19121
|
+
healthy: false,
|
|
19122
|
+
error: `the proxy forwards traffic to ${NEUTRAL_TARGET_HOST}, but DuckDuckGo is unreachable through it (${probe.reason}). The tunnel works; the pinned front doors do not. Update DDG_PIN_IPS and restart the proxy, or remove ~/.pi/research/proxy.json.`
|
|
19123
|
+
};
|
|
19124
|
+
}
|
|
19125
|
+
return { healthy: false, error: probe.reason };
|
|
19126
|
+
}, { timeoutMs: 25e3, critical: true });
|
|
18839
19127
|
registry.register("KnowledgeStore", async (options) => {
|
|
18840
19128
|
const existing = container.tryGet(ServiceNames.KNOWLEDGE_STORE);
|
|
18841
19129
|
const alreadyInitialized = existing?.lifecycle === "initialized" /* INITIALIZED */;
|
|
@@ -18964,7 +19252,8 @@ function isBusyPoolHealthFailure(health) {
|
|
|
18964
19252
|
const capabilityOk = !capability || capability.healthy !== false;
|
|
18965
19253
|
const unhealthy = components.filter((c) => c.healthy === false);
|
|
18966
19254
|
const isTimeout = (c) => /tim(e|ed)\s*out|timeout/i.test(String(c.error || ""));
|
|
18967
|
-
|
|
19255
|
+
const proxyBroken = unhealthy.some((c) => c.component === "SocksProxy");
|
|
19256
|
+
return capabilityOk && !proxyBroken && unhealthy.length > 0 && unhealthy.every(isTimeout);
|
|
18968
19257
|
}
|
|
18969
19258
|
async function runHealthCheck(options) {
|
|
18970
19259
|
const container = tryGetServiceContainerFromCtx(options?.ctx);
|
|
@@ -18994,7 +19283,7 @@ import { createAgentSession, SessionManager, SettingsManager as SettingsManagerC
|
|
|
18994
19283
|
// src/tools/read-guard.ts
|
|
18995
19284
|
import { constants as constants2 } from "node:fs";
|
|
18996
19285
|
import { access as access3, open as open5, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
|
|
18997
|
-
import { homedir as
|
|
19286
|
+
import { homedir as homedir7 } from "node:os";
|
|
18998
19287
|
import { basename as basename5, dirname as dirname13, relative, isAbsolute as isAbsolute3, parse, sep as sep2 } from "node:path";
|
|
18999
19288
|
var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud", ".terraform"]);
|
|
19000
19289
|
var DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.dockerconfigjson|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)([._-].*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars|key)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
|
|
@@ -19023,7 +19312,7 @@ function isWithin(root, target) {
|
|
|
19023
19312
|
}
|
|
19024
19313
|
async function assertReadAllowed(cwd, absolutePath) {
|
|
19025
19314
|
const root = await resolveReal(cwd);
|
|
19026
|
-
const home = await resolveReal(
|
|
19315
|
+
const home = await resolveReal(homedir7());
|
|
19027
19316
|
if (root === parse(root).root || isWithin(root, home)) {
|
|
19028
19317
|
throw new ReadDeniedError("the working directory is a home or filesystem root, not a project directory");
|
|
19029
19318
|
}
|
|
@@ -19306,7 +19595,7 @@ init_metrics();
|
|
|
19306
19595
|
init_logger();
|
|
19307
19596
|
import * as dns from "node:dns/promises";
|
|
19308
19597
|
import * as dnsCb from "node:dns";
|
|
19309
|
-
import * as
|
|
19598
|
+
import * as net4 from "node:net";
|
|
19310
19599
|
import crypto9 from "node:crypto";
|
|
19311
19600
|
import { NodeHtmlMarkdown } from "node-html-markdown";
|
|
19312
19601
|
function getRandomUserAgent() {
|
|
@@ -19339,7 +19628,7 @@ function validateUrlForSSRFSync(url) {
|
|
|
19339
19628
|
throw new Error("Only HTTP/HTTPS protocols are allowed");
|
|
19340
19629
|
}
|
|
19341
19630
|
if (process.env["PI_RESEARCH_ALLOW_LOOPBACK_SCRAPE"] === "true") {
|
|
19342
|
-
const isLoopback = hostname === "localhost" || hostname.endsWith(".localhost") || /^127\./.test(hostname) || hostname === "::1" ||
|
|
19631
|
+
const isLoopback = hostname === "localhost" || hostname.endsWith(".localhost") || /^127\./.test(hostname) || hostname === "::1" || net4.isIPv6(hostname) && isPrivateIpv6(hostname) && isMappedLoopback(hostname);
|
|
19343
19632
|
if (isLoopback) return true;
|
|
19344
19633
|
}
|
|
19345
19634
|
if (hostname === "localhost" || hostname.endsWith(".localhost")) {
|
|
@@ -19352,7 +19641,7 @@ function validateUrlForSSRFSync(url) {
|
|
|
19352
19641
|
throw new Error("Access to internal networks is not allowed");
|
|
19353
19642
|
}
|
|
19354
19643
|
}
|
|
19355
|
-
const literalKind =
|
|
19644
|
+
const literalKind = net4.isIP(hostname);
|
|
19356
19645
|
if (literalKind === 4 && isPrivateIp(hostname)) {
|
|
19357
19646
|
metrics.increment("scrape_ssrf_blocks_total", 1, { block_type: "ip_literal_v4" });
|
|
19358
19647
|
throw new Error("Access to private/reserved IPv4 address is not allowed");
|
|
@@ -19438,8 +19727,8 @@ async function disposeSsrfSafeFetcher() {
|
|
|
19438
19727
|
const pending = cachedSsrfFetcher;
|
|
19439
19728
|
cachedSsrfFetcher = void 0;
|
|
19440
19729
|
if (pending === void 0) return;
|
|
19441
|
-
const
|
|
19442
|
-
const closable =
|
|
19730
|
+
const cached2 = await pending.catch(() => null);
|
|
19731
|
+
const closable = cached2?.dispatcher;
|
|
19443
19732
|
if (!closable?.close) return;
|
|
19444
19733
|
try {
|
|
19445
19734
|
await closable.close();
|
|
@@ -19654,7 +19943,7 @@ init_service_registry();
|
|
|
19654
19943
|
init_logger();
|
|
19655
19944
|
init_metrics();
|
|
19656
19945
|
init_error_tracker();
|
|
19657
|
-
import { existsSync as
|
|
19946
|
+
import { existsSync as existsSync13 } from "node:fs";
|
|
19658
19947
|
import { dirname as dirname14, join as join21 } from "node:path";
|
|
19659
19948
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
19660
19949
|
import { Worker } from "node:worker_threads";
|
|
@@ -19727,7 +20016,7 @@ var pendingRequests = /* @__PURE__ */ new Map();
|
|
|
19727
20016
|
var warnedWorkerUnavailable = false;
|
|
19728
20017
|
function resolveWorkerPath() {
|
|
19729
20018
|
const candidate = join21(MODULE_DIR, WORKER_FILENAME);
|
|
19730
|
-
return
|
|
20019
|
+
return existsSync13(candidate) ? candidate : null;
|
|
19731
20020
|
}
|
|
19732
20021
|
function pdfWorkerEnabled() {
|
|
19733
20022
|
if (process.env["PI_RESEARCH_PDF_WORKER"] === "off") return false;
|
|
@@ -24775,6 +25064,7 @@ ${effectiveInitialLinks.map((l) => `- ${l}`).join("\n")}`;
|
|
|
24775
25064
|
const deliveredSteeringIds = /* @__PURE__ */ new Set();
|
|
24776
25065
|
const researcherSystemPrompt = injectCurrentDate(researcherPromptTemplate, "researcher").replace("{{extra_tool_guidelines}}", "").replaceAll("{{max_scrape_urls}}", String(config.MAX_SCRAPE_URLS)).replace("{{digest_section}}", () => RESEARCHER_DIGEST_SECTION).trim();
|
|
24777
25066
|
let inFlightBackoffMs = null;
|
|
25067
|
+
let capacityWaitSpentMs = 0;
|
|
24778
25068
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
24779
25069
|
if (signal?.aborted) throw new Error("Aborted");
|
|
24780
25070
|
if (stopRequested()) {
|
|
@@ -25036,6 +25326,20 @@ ${responseText}`);
|
|
|
25036
25326
|
metrics.increment("researcher_rate_limit_backoff_total", 1, { mode: "deep", complexity: String(complexity) });
|
|
25037
25327
|
logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
|
|
25038
25328
|
}
|
|
25329
|
+
if (inFlightBackoffMs !== null) {
|
|
25330
|
+
const remainingBudgetMs = RATE_LIMIT_TOTAL_WAIT_MAX_MS - capacityWaitSpentMs;
|
|
25331
|
+
if (inFlightBackoffMs > remainingBudgetMs) {
|
|
25332
|
+
const windowSeconds = Math.ceil(inFlightBackoffMs / 1e3);
|
|
25333
|
+
const retryAt = new Date(Date.now() + inFlightBackoffMs).toISOString().slice(11, 19);
|
|
25334
|
+
lastError = new Error(
|
|
25335
|
+
`Provider capacity: it asked for a ${windowSeconds}s cool-off, but this researcher has only ${Math.max(0, Math.round(remainingBudgetMs / 1e3))}s of its ${Math.round(RATE_LIMIT_TOTAL_WAIT_MAX_MS / 1e3)}s capacity-wait budget left. Rerun after ${retryAt}Z. Cause: ${errMsg}`
|
|
25336
|
+
);
|
|
25337
|
+
logger.error(`[ResearcherExecutor] Researcher ${id} stopping instead of waiting ${inFlightBackoffMs}ms (capacity budget exhausted); rerun after ${retryAt}Z`);
|
|
25338
|
+
metrics.increment("researcher_capacity_budget_exhausted_total", 1, { mode: "deep", complexity: String(complexity) });
|
|
25339
|
+
break;
|
|
25340
|
+
}
|
|
25341
|
+
capacityWaitSpentMs += inFlightBackoffMs;
|
|
25342
|
+
}
|
|
25039
25343
|
}
|
|
25040
25344
|
if (attempt < maxAttempts) {
|
|
25041
25345
|
logger.warn(`[ResearcherExecutor] Researcher ${id} attempt ${attempt} failed: ${errMsg}; will retry`);
|
|
@@ -25702,6 +26006,13 @@ var DeepResearchOrchestrator = class {
|
|
|
25702
26006
|
const orchestrationService = await this.getOrchestrationService();
|
|
25703
26007
|
const planningService = await this.getPlanningService();
|
|
25704
26008
|
await orchestrationService.cleanupResearchServices(void 0, researchId, ctx, this.config);
|
|
26009
|
+
const proxyDiagnosis = await describeProxyIfBroken(signal);
|
|
26010
|
+
if (signal?.aborted) return "";
|
|
26011
|
+
if (proxyDiagnosis) {
|
|
26012
|
+
throw new Error(
|
|
26013
|
+
`Research cannot start: ${proxyDiagnosis} Repair or remove ~/.pi/research/proxy.json (docs/TROUBLESHOOTING.md), then rerun.`
|
|
26014
|
+
);
|
|
26015
|
+
}
|
|
25705
26016
|
logger.log(`[DeepOrchestrator] Starting multi-round research (complexity ${complexity}) for: "${query}" (Run: ${researchId})`);
|
|
25706
26017
|
metrics.increment("research_sessions_total", 1, { mode: "deep", complexity: String(complexity) });
|
|
25707
26018
|
observer?.onStart?.(query, complexity);
|
|
@@ -27804,7 +28115,7 @@ init_url_utils();
|
|
|
27804
28115
|
init_logger();
|
|
27805
28116
|
init_constants();
|
|
27806
28117
|
import { promises as fs16 } from "node:fs";
|
|
27807
|
-
import { homedir as
|
|
28118
|
+
import { homedir as homedir8, tmpdir as tmpdir4, platform as platform4 } from "node:os";
|
|
27808
28119
|
import { join as join22, resolve as resolve5, normalize, sep as sep3 } from "node:path";
|
|
27809
28120
|
import { randomBytes as randomBytes6 } from "node:crypto";
|
|
27810
28121
|
var PREFERRED_SUBDIRS = [
|
|
@@ -27847,7 +28158,7 @@ var WIN_SYSTEM_PREFIXES_LC = [
|
|
|
27847
28158
|
];
|
|
27848
28159
|
function isSafeToWriteDirectly(dir) {
|
|
27849
28160
|
const normalized = normalize(resolve5(dir));
|
|
27850
|
-
const home = normalize(resolve5(
|
|
28161
|
+
const home = normalize(resolve5(homedir8()));
|
|
27851
28162
|
if (normalized === home) return false;
|
|
27852
28163
|
if (platform4() === "win32") {
|
|
27853
28164
|
if (/^[a-zA-Z]:\\?$/.test(normalized)) return false;
|