@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
package/src/tools/read-guard.ts
CHANGED
|
@@ -9,16 +9,16 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { constants } from 'node:fs';
|
|
12
|
-
import { access, readFile, realpath } from 'node:fs/promises';
|
|
12
|
+
import { access, open, readFile, realpath } from 'node:fs/promises';
|
|
13
13
|
import { homedir } from 'node:os';
|
|
14
14
|
import { basename, dirname, relative, isAbsolute, parse, sep } from 'node:path';
|
|
15
15
|
import type { ReadOperations } from '@earendil-works/pi-coding-agent';
|
|
16
16
|
|
|
17
17
|
/** Path segments that are never readable, wherever they sit under the project. */
|
|
18
|
-
const DENIED_SEGMENTS = new Set(['.ssh', '.aws', '.gnupg', '.git', '.kube', '.docker', '.azure', '.gcloud']);
|
|
18
|
+
const DENIED_SEGMENTS = new Set(['.ssh', '.aws', '.gnupg', '.git', '.kube', '.docker', '.azure', '.gcloud', '.terraform']);
|
|
19
19
|
|
|
20
20
|
/** Basenames (lower-cased) and patterns that carry credentials. */
|
|
21
|
-
const DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)(
|
|
21
|
+
const 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)$/;
|
|
22
22
|
|
|
23
23
|
/** Env templates are meant to be shared and hold no secrets. */
|
|
24
24
|
const ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
|
|
@@ -89,7 +89,26 @@ export function createGuardedReadOperations(cwd: string): ReadOperations {
|
|
|
89
89
|
readFile: async (p) => {
|
|
90
90
|
// Re-checked at read time: the access() check and the read are separate calls.
|
|
91
91
|
await assertReadAllowed(cwd, p);
|
|
92
|
-
|
|
92
|
+
// The policy check above resolves symlinks, then this open() runs a moment
|
|
93
|
+
// later: a local attacker with write access to the project can swap `p`
|
|
94
|
+
// for a symlink in between (TOCTOU). O_NOFOLLOW makes the open itself
|
|
95
|
+
// refuse a final-component symlink (ELOOP), and the stat on the fd
|
|
96
|
+
// rejects anything that is not a regular file. Reading through the fd
|
|
97
|
+
// (not the path) means the bytes come from the file the fd points at,
|
|
98
|
+
// not whatever the path resolves to at read time. The residual gap is an
|
|
99
|
+
// intermediate path component swapped for a directory symlink, which
|
|
100
|
+
// Node's public API cannot close (no openat-walk); it is documented in
|
|
101
|
+
// SECURITY.md.
|
|
102
|
+
const handle = await open(p, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
103
|
+
try {
|
|
104
|
+
const stat = await handle.stat();
|
|
105
|
+
if (!stat.isFile()) {
|
|
106
|
+
throw new ReadDeniedError('path is not a regular file');
|
|
107
|
+
}
|
|
108
|
+
return await readFile(handle);
|
|
109
|
+
} finally {
|
|
110
|
+
await handle.close();
|
|
111
|
+
}
|
|
93
112
|
},
|
|
94
113
|
};
|
|
95
114
|
}
|
|
@@ -64,10 +64,30 @@ export function isRateLimitError(error: unknown): boolean {
|
|
|
64
64
|
if (isSpentAccountError(error)) return false;
|
|
65
65
|
const msg = (error instanceof Error ? error.message : String(error)).toLowerCase();
|
|
66
66
|
return /\b429\b/.test(msg)
|
|
67
|
+
// A provider that is OVERLOADED says 5xx, and pi passes the status through:
|
|
68
|
+
// "503 Provider returned error"
|
|
69
|
+
// That is as transient as a 429 and must take the same long-wait path. Before
|
|
70
|
+
// this, a 503 fell through to the ordinary 1s/2s curve and killed the run
|
|
71
|
+
// (2026-10-28, eight consecutive runs lost while the search burst had already
|
|
72
|
+
// collected 48-104 results).
|
|
73
|
+
// Anchored to STATUS CONTEXT on purpose. A bare `/\b50[0234]\b/` also matches
|
|
74
|
+
// "took 502ms", "max_tokens=500" and "504 results", and this classifier drives
|
|
75
|
+
// both the retry policy and the run-level stop threshold, so a false positive
|
|
76
|
+
// buys a long wait and stops counting a genuine failure.
|
|
77
|
+
|| /\b(?:http|status|code|error|response|returned)\W{0,4}50[0234]\b/i.test(msg)
|
|
78
|
+
|| /\b50[0234]\b\W{0,4}(?:provider|service|unavailable|bad|gateway|internal|error|timeout)/i.test(msg)
|
|
79
|
+
|| msg.includes('service unavailable')
|
|
80
|
+
|| msg.includes('bad gateway')
|
|
81
|
+
|| msg.includes('gateway timeout')
|
|
67
82
|
|| msg.includes('rate limit')
|
|
68
83
|
|| msg.includes('rate-limit')
|
|
69
84
|
|| msg.includes('rate limited')
|
|
70
85
|
|| msg.includes('too many requests')
|
|
86
|
+
// pi's own client throws this sentence when the provider's Retry-After is
|
|
87
|
+
// longer than pi's cap. It is a capacity signal, not a bug report:
|
|
88
|
+
// "Server requested 120s retry delay (max: 60s). 503 Provider returned error"
|
|
89
|
+
|| msg.includes('retry delay')
|
|
90
|
+
|| msg.includes('retry-after')
|
|
71
91
|
|| msg.includes('engine_overloaded')
|
|
72
92
|
|| msg.includes('provider_overloaded');
|
|
73
93
|
}
|
|
@@ -84,8 +104,10 @@ export function isCapacityFailureReason(reason: string | undefined): boolean {
|
|
|
84
104
|
}
|
|
85
105
|
|
|
86
106
|
/**
|
|
87
|
-
* The `Retry-After` a provider error asked for, in ms, clamped to [5s,
|
|
88
|
-
* the error carries none.
|
|
107
|
+
* The `Retry-After` a provider error asked for, in ms, clamped to [5s, 180s], or null when
|
|
108
|
+
* the error carries none. 60s is only the EXPONENTIAL ceiling: a stated window is the
|
|
109
|
+
* provider telling us when its pool reopens, so it keeps its full length up to
|
|
110
|
+
* STATED_RETRY_AFTER_MAX_MS. Read out of the message because every caller sees a serialized
|
|
89
111
|
* provider error, not the raw Response headers: pi's `after_provider_response` hook
|
|
90
112
|
* (src/index.ts) is the only place with headers, and it does not feed these retry loops.
|
|
91
113
|
*
|
|
@@ -94,11 +116,20 @@ export function isCapacityFailureReason(reason: string | undefined): boolean {
|
|
|
94
116
|
*/
|
|
95
117
|
export function parseRetryAfterMs(error: unknown): number | null {
|
|
96
118
|
const message = error instanceof Error ? error.message : String(error);
|
|
97
|
-
|
|
119
|
+
// Three shapes are in the wild:
|
|
120
|
+
// 1. `retry-after: 30` — a header echoed into the message
|
|
121
|
+
// 2. `retry after 30s` — prose form
|
|
122
|
+
// 3. `Server requested 120s retry delay (max: 60s). 503 ...`
|
|
123
|
+
// — pi's client refusing a window longer than its own cap. The provider's
|
|
124
|
+
// number is the load-bearing one: it is the ONLY statement of when the
|
|
125
|
+
// pool reopens, and the run has just been told to come back in 120s.
|
|
126
|
+
const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message)
|
|
127
|
+
|| /requested\s+(\d{1,4})\s*s(?:ec(?:onds?)?)?\s+retry\s+delay/i.exec(message)
|
|
128
|
+
|| /retry\s+after\s+(\d{1,4})\s*s/i.exec(message);
|
|
98
129
|
if (!m) return null;
|
|
99
130
|
const seconds = Number(m[1]);
|
|
100
131
|
if (!Number.isFinite(seconds) || seconds <= 0) return null;
|
|
101
|
-
return Math.min(Math.max(seconds, 5),
|
|
132
|
+
return Math.min(Math.max(seconds, 5), STATED_RETRY_AFTER_MAX_MS / 1000) * 1000;
|
|
102
133
|
}
|
|
103
134
|
|
|
104
135
|
/**
|
|
@@ -110,12 +141,31 @@ export function parseRetryAfterMs(error: unknown): number | null {
|
|
|
110
141
|
export const RATE_LIMIT_BACKOFF_BASE_MS = 15_000;
|
|
111
142
|
|
|
112
143
|
/**
|
|
113
|
-
* Ceiling for one rate-limit wait.
|
|
114
|
-
*
|
|
115
|
-
* fallback, so three retries cost at
|
|
144
|
+
* Ceiling for one EXPONENTIAL rate-limit wait. A provider's stated `Retry-After`
|
|
145
|
+
* bypasses this bound (parseRetryAfterMs clamps it to STATED_RETRY_AFTER_MAX_MS
|
|
146
|
+
* instead); this only bounds the exponential fallback, so three retries cost at
|
|
147
|
+
* most 15s + 30s + 60s of waiting.
|
|
116
148
|
*/
|
|
117
149
|
export const RATE_LIMIT_BACKOFF_MAX_MS = 60_000;
|
|
118
150
|
|
|
151
|
+
/**
|
|
152
|
+
* Ceiling for a wait the PROVIDER stated, which is a different thing from the
|
|
153
|
+
* exponential ceiling above. A provider that asks for 120s has told us when its
|
|
154
|
+
* pool reopens. Clamping that to 60s does not make the request succeed — it
|
|
155
|
+
* guarantees the next attempt fails too, and burns one of three attempts to learn
|
|
156
|
+
* nothing. 180s still bounds a run: PI_RESEARCH_TIMEOUT_MS defaults to 900s.
|
|
157
|
+
*/
|
|
158
|
+
export const STATED_RETRY_AFTER_MAX_MS = 180_000;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Total time ONE researcher may spend waiting on provider capacity across its
|
|
162
|
+
* attempts. Three stated 120s windows would be six minutes inside a single
|
|
163
|
+
* researcher, which is most of a run's budget spent on one call. Past this bound
|
|
164
|
+
* the loop stops and says WHEN to rerun, instead of sleeping into the run timeout
|
|
165
|
+
* and reporting a failure with no cause.
|
|
166
|
+
*/
|
|
167
|
+
export const RATE_LIMIT_TOTAL_WAIT_MAX_MS = 240_000;
|
|
168
|
+
|
|
119
169
|
/**
|
|
120
170
|
* How long to wait before retry `attempt` (2 = first retry).
|
|
121
171
|
*
|
|
@@ -135,7 +185,9 @@ export function rateLimitBackoffMs(
|
|
|
135
185
|
random: () => number = Math.random,
|
|
136
186
|
): number {
|
|
137
187
|
if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
|
|
138
|
-
|
|
188
|
+
// A stated window keeps its full length up to STATED_RETRY_AFTER_MAX_MS; only
|
|
189
|
+
// the exponential fallback below is bounded by RATE_LIMIT_BACKOFF_MAX_MS.
|
|
190
|
+
return Math.min(Math.max(Math.round(retryAfterMs), 1_000), STATED_RETRY_AFTER_MAX_MS);
|
|
139
191
|
}
|
|
140
192
|
const exponent = Math.max(0, attempt - 2);
|
|
141
193
|
const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
|
|
@@ -143,7 +195,7 @@ export function rateLimitBackoffMs(
|
|
|
143
195
|
return clampRateLimitWait(base + jitter);
|
|
144
196
|
}
|
|
145
197
|
|
|
146
|
-
/** Keep
|
|
198
|
+
/** Keep an EXPONENTIAL wait inside [1s, 60s]. A provider-stated window is NOT clamped here. */
|
|
147
199
|
export function clampRateLimitWait(ms: number): number {
|
|
148
200
|
return Math.min(Math.max(Math.round(ms), 1_000), RATE_LIMIT_BACKOFF_MAX_MS);
|
|
149
201
|
}
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { runWorkerSearch } from '../infrastructure/browser/task-execution-service.ts';
|
|
8
8
|
import { getMaxWorkers, COLD_START_ALLOWANCE_MS } from '../infrastructure/browser/config.ts';
|
|
9
9
|
import { isTaskTimeoutError, isNativeBindingError } from '../infrastructure/browser/browser-error-utils.ts';
|
|
10
|
+
import { describeProxyIfBroken } from '../infrastructure/browser/proxy-health.ts';
|
|
10
11
|
import { logger } from '../logger.ts';
|
|
11
12
|
import { safeUnref } from '../utils/safe-unref.ts';
|
|
12
13
|
import { normalizeUrl } from '../utils/url-utils.ts';
|
|
@@ -339,9 +340,20 @@ export async function performSearch(
|
|
|
339
340
|
);
|
|
340
341
|
}
|
|
341
342
|
|
|
343
|
+
// Name the actual cause when the configured proxy is the cause. Without
|
|
344
|
+
// this the message lists three hypotheses (workers, DuckDuckGo, load) and
|
|
345
|
+
// none of them is "the local SOCKS proxy is a black hole", which is what
|
|
346
|
+
// every one of these failures was between 2026-10-28 and 2026-10-30.
|
|
347
|
+
// Cheap: this branch only runs after a burst has already failed.
|
|
348
|
+
// Pass the run signal: if the caller cancels mid-diagnosis, the two DDG
|
|
349
|
+
// samples plus the neutral check must stop at once, not run to completion.
|
|
350
|
+
const proxyDiagnosis = await describeProxyIfBroken(signal);
|
|
342
351
|
throw new Error(
|
|
343
352
|
`Search completely failed: ${reason}. ` +
|
|
344
|
-
|
|
353
|
+
(proxyDiagnosis
|
|
354
|
+
? `${proxyDiagnosis} Every browser request is routed through the configured proxy, ` +
|
|
355
|
+
`so no search can succeed until it forwards DuckDuckGo traffic or ~/.pi/research/proxy.json is removed.`
|
|
356
|
+
: `Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under extreme load.`) +
|
|
345
357
|
(sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : '')
|
|
346
358
|
);
|
|
347
359
|
}
|
|
@@ -47,6 +47,17 @@ export interface RetryOptions {
|
|
|
47
47
|
* `rateLimitDelayFor` in src/core/planning-service.ts.
|
|
48
48
|
*/
|
|
49
49
|
readonly delayFor?: (nextAttempt: number, error: Error) => number | null;
|
|
50
|
+
/**
|
|
51
|
+
* Hard ceiling on the SUM of the waits this one call may spend.
|
|
52
|
+
*
|
|
53
|
+
* `delayFor` lets a provider-mandated window (up to 180s) bypass `maxDelay`, which
|
|
54
|
+
* is correct per attempt and unbounded across attempts. The planning/router calls
|
|
55
|
+
* retry up to twice, so two stated 180s windows are six minutes inside a 900s run
|
|
56
|
+
* — most of the budget spent sleeping, and no actionable error at the end of it.
|
|
57
|
+
* Past this bound the call throws the provider's own window and the time to
|
|
58
|
+
* rerun instead of sleeping into the caller's timeout.
|
|
59
|
+
*/
|
|
60
|
+
readonly maxTotalDelayMs?: number;
|
|
50
61
|
}
|
|
51
62
|
|
|
52
63
|
/**
|
|
@@ -299,7 +310,7 @@ export async function retryWithBackoff<T>(
|
|
|
299
310
|
): Promise<T> {
|
|
300
311
|
// `delayFor` stays optional (absent for every caller that does not override the wait),
|
|
301
312
|
// so it is excluded from the Required<> normalization rather than given a default.
|
|
302
|
-
const opts: Required<Omit<RetryOptions, 'signal' | 'delayFor'>> & RetryOptions = {
|
|
313
|
+
const opts: Required<Omit<RetryOptions, 'signal' | 'delayFor' | 'maxTotalDelayMs'>> & RetryOptions = {
|
|
303
314
|
maxRetries: 3,
|
|
304
315
|
initialDelay: 1000,
|
|
305
316
|
maxDelay: 10000,
|
|
@@ -311,6 +322,8 @@ export async function retryWithBackoff<T>(
|
|
|
311
322
|
const startTime = Date.now();
|
|
312
323
|
let lastError: Error | null = null;
|
|
313
324
|
let attempt = 0;
|
|
325
|
+
// Sum of the waits actually slept, for the optional maxTotalDelayMs ceiling.
|
|
326
|
+
let totalDelayMs = 0;
|
|
314
327
|
metrics.increment('retry_attempts_total', 1, { label: opts.label });
|
|
315
328
|
|
|
316
329
|
while (attempt <= opts.maxRetries) {
|
|
@@ -337,7 +350,7 @@ export async function retryWithBackoff<T>(
|
|
|
337
350
|
|
|
338
351
|
// Calculate delay with exponential backoff and jitter
|
|
339
352
|
const baseDelay = opts.initialDelay * Math.pow(2, attempt);
|
|
340
|
-
const jitter = Math.random() * 0.5 * baseDelay; //
|
|
353
|
+
const jitter = Math.random() * 0.5 * baseDelay; // 0–50% positive jitter
|
|
341
354
|
// A caller that knows better (a provider-stated or rate-limit wait) wins over the
|
|
342
355
|
// step — including over maxDelay, which bounds only the ordinary step.
|
|
343
356
|
const override = opts.delayFor?.(attempt + 2, lastError);
|
|
@@ -345,6 +358,21 @@ export async function retryWithBackoff<T>(
|
|
|
345
358
|
? Math.round(override)
|
|
346
359
|
: Math.min(baseDelay + jitter, opts.maxDelay);
|
|
347
360
|
|
|
361
|
+
// Bound the TOTAL waiting before sleeping, so a provider that keeps asking
|
|
362
|
+
// for a long window cannot spend the caller's whole timeout here.
|
|
363
|
+
if (opts.maxTotalDelayMs !== undefined && totalDelayMs + delay > opts.maxTotalDelayMs) {
|
|
364
|
+
const retryAt = new Date(Date.now() + delay).toISOString().slice(11, 19);
|
|
365
|
+
metrics.increment('retry_total_delay_exhausted_total', 1, { label: opts.label });
|
|
366
|
+
throw new Error(
|
|
367
|
+
`Provider capacity: ${opts.label} asked for a ${Math.round(delay / 1000)}s wait, but only `
|
|
368
|
+
+ `${Math.max(0, Math.round((opts.maxTotalDelayMs - totalDelayMs) / 1000))}s of its `
|
|
369
|
+
+ `${Math.round(opts.maxTotalDelayMs / 1000)}s total-wait budget is left. Rerun after ${retryAt}Z. `
|
|
370
|
+
+ `Cause: ${lastError.message}`,
|
|
371
|
+
{ cause: error },
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
totalDelayMs += delay;
|
|
375
|
+
|
|
348
376
|
metrics.increment('retry_backoff_total', 1, { attempt: String(attempt), label: opts.label });
|
|
349
377
|
metrics.observe('retry_backoff_delay_ms', delay, { attempt: String(attempt), label: opts.label });
|
|
350
378
|
logger.warn(`[Retry] ${opts.label} failed (attempt ${attempt + 1}/${opts.maxRetries + 1}), retrying in ${Math.round(delay)}ms: ${lastError.message}`);
|