@lincoln504/pi-research 1.7.21 → 1.7.23
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 +399 -163
- package/dist/thread-worker.mjs +77 -31
- package/docs/CHANGELOG.md +46 -0
- package/docs/CONFIGURATION.md +8 -3
- package/docs/THIRD-PARTY-NOTICES.md +29 -13
- package/docs/TROUBLESHOOTING.md +16 -0
- package/package.json +12 -9
- package/scripts/ddg-socks-proxy.mjs +279 -0
- package/scripts/lib/npm-cmd.cjs +66 -0
- package/scripts/lib/private-addresses.mjs +143 -0
- package/src/config.ts +75 -2
- package/src/core/interfaces/steering-interfaces.ts +11 -0
- package/src/core/llm/coordinator-model.ts +104 -0
- package/src/core/planning-service.ts +24 -0
- package/src/index.ts +7 -1
- package/src/infrastructure/browser/proxy-prefs.ts +124 -0
- package/src/infrastructure/browser/thread-worker-browser.ts +5 -21
- package/src/infrastructure/browser/thread-worker-messaging.ts +9 -4
- package/src/infrastructure/browser/thread-worker.mjs +77 -31
- 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 +71 -2
- package/src/orchestration/research-synthesis-service.ts +14 -1
- package/src/orchestration/researcher-executor.ts +33 -33
- package/src/orchestration/session-state.ts +155 -7
- package/src/tools/read-guard.ts +23 -4
- package/src/tui/tui-controller.ts +25 -1
- package/src/utils/provider-errors.ts +149 -0
- package/src/web-research/retry-utils.ts +22 -3
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
|
|
|
@@ -8,7 +8,7 @@ import type { ExtensionContext, AgentToolResult } from '@earendil-works/pi-codin
|
|
|
8
8
|
import { type Model } from '@earendil-works/pi-ai';
|
|
9
9
|
import { logger } from '../logger.ts';
|
|
10
10
|
import { metrics } from '../utils/metrics.ts';
|
|
11
|
-
import { getSteeringMessages, consumeQueuedMessages, getActiveSteeringMessages, getFailedResearchers, getResearcherFailureReasons } from './session-state.ts';
|
|
11
|
+
import { getSteeringMessages, consumeQueuedMessages, getActiveSteeringMessages, getFailedResearchers, getResearcherFailureReasons, shouldStopResearch, createResearchStopError, hasOnlyCapacityFailures } from './session-state.ts';
|
|
12
12
|
import { MAX_EXTRA_ROUNDS_WITH_STEERING, MIN_SYNTHESIS_PROSE_CHARS, SYNTHESIS_FALLBACK_NOTICE, resolveExcludedTools } from '../constants.ts';
|
|
13
13
|
import { synthesisProseBody, isAnalysisFreeSynthesis } from '../utils/text-utils.ts';
|
|
14
14
|
import {
|
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
import { getService, tryGetServiceContainerFromCtx } from '../core/service-registry.ts';
|
|
29
29
|
import { getConfig } from '../config.ts';
|
|
30
30
|
import type { Config } from '../config.ts';
|
|
31
|
+
import { findModelByReference, resolveCoordinatorModel } from '../core/llm/coordinator-model.ts';
|
|
31
32
|
import type { PlanningService } from '../core/planning-service.ts';
|
|
32
33
|
|
|
33
34
|
export interface DeepResearchOrchestratorOptions {
|
|
@@ -111,7 +112,32 @@ export class DeepResearchOrchestrator {
|
|
|
111
112
|
// Later evaluator rounds (round 2+ routing) and final synthesis
|
|
112
113
|
// use the research model (RESEARCH_MODEL override or host model),
|
|
113
114
|
// which is also what the researcher sub-agents use.
|
|
114
|
-
|
|
115
|
+
//
|
|
116
|
+
// PI_RESEARCH_COORDINATOR_MODEL overrides that first call: `research` (or an
|
|
117
|
+
// explicit provider/id) when the chat model is a poor or single-seat planner.
|
|
118
|
+
// See src/core/llm/coordinator-model.ts for the measured case.
|
|
119
|
+
const initialCoordinatorModel = resolveCoordinatorModel<Model<any>>({
|
|
120
|
+
setting: this.config.COORDINATOR_MODEL,
|
|
121
|
+
hostModel: ctx.model as Model<any> | undefined,
|
|
122
|
+
researchModel: model,
|
|
123
|
+
// STRICT lookup (never resolveResearchModel): that resolver always returns a
|
|
124
|
+
// model — it falls back through RESEARCH_MODEL to "first available" — so a typo
|
|
125
|
+
// would silently run on an arbitrary model AND never trigger onUnresolved.
|
|
126
|
+
findByReference: (reference) => {
|
|
127
|
+
try {
|
|
128
|
+
const registry = ctx.modelRegistry;
|
|
129
|
+
const all = (registry?.getAll?.() ?? []) as Model<any>[];
|
|
130
|
+
const available = (registry?.getAvailable?.() ?? []) as Model<any>[];
|
|
131
|
+
return findModelByReference(reference, all, available);
|
|
132
|
+
} catch {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
onUnresolved: (reference) => logger.warn(
|
|
137
|
+
`[DeepOrchestrator] COORDINATOR_MODEL '${reference}' is not an available model; ` +
|
|
138
|
+
'falling back to the research model (not the chat model, which this setting exists to replace).',
|
|
139
|
+
),
|
|
140
|
+
});
|
|
115
141
|
const evaluatorModel = model;
|
|
116
142
|
|
|
117
143
|
const orchestrationService = await this.getOrchestrationService();
|
|
@@ -162,6 +188,14 @@ export class DeepResearchOrchestrator {
|
|
|
162
188
|
|
|
163
189
|
const MAX_WAIT_RETRIES = 5;
|
|
164
190
|
let waitRetryCount = 0;
|
|
191
|
+
// Rounds that produced ZERO new reports while every failure was a provider-capacity
|
|
192
|
+
// failure. Capacity failures are excluded from shouldStopResearch (one upstream
|
|
193
|
+
// outage must not end a healthy run), which would otherwise keep the run alive for
|
|
194
|
+
// every remaining round — a full search burst each time — against a provider that
|
|
195
|
+
// cannot answer. One such round is tolerated (the outage may clear; the observed one
|
|
196
|
+
// lasted six minutes and each round already spends ~100s in the researcher retries);
|
|
197
|
+
// a second consecutive one stops the run at the fallback synthesis.
|
|
198
|
+
let capacityOnlyRounds = 0;
|
|
165
199
|
// Whether the ROUTER chose to finish inside the loop, as opposed to the loop ending
|
|
166
200
|
// because the round budget ran out. The router never carries the report: it is asked
|
|
167
201
|
// for a decision, is given no corpus to write from (it sees each report once, on the
|
|
@@ -366,6 +400,17 @@ export class DeepResearchOrchestrator {
|
|
|
366
400
|
// Reset wait retry counter on successful actions
|
|
367
401
|
waitRetryCount = 0;
|
|
368
402
|
|
|
403
|
+
// Stop BEFORE the round's search burst when the failure threshold is already
|
|
404
|
+
// crossed. runResearchers performs the same check, but only after the planner
|
|
405
|
+
// and the whole search phase have run: on 2026-10-25 round 2 fanned out 36
|
|
406
|
+
// searches (296 results) that runResearchers then discarded, because round 1
|
|
407
|
+
// had already crossed the threshold. The stop error is identical to the one
|
|
408
|
+
// runResearchers raises, so the run's outcome (fallback synthesis from the
|
|
409
|
+
// reports already collected) does not change — only the wasted work does.
|
|
410
|
+
if (shouldStopResearch(this.options.sessionId, researchId, this.config.MAX_FAILED_RESEARCHERS)) {
|
|
411
|
+
throw createResearchStopError(this.options.sessionId, researchId);
|
|
412
|
+
}
|
|
413
|
+
|
|
369
414
|
// Track how many researchers were planned this round
|
|
370
415
|
// updatePlanForRound has a comment "We'll update totalResearchersPlanned in the orchestrator"
|
|
371
416
|
if (plan.action === 'delegate' && plan.researchers && plan.researchers.length > 0) {
|
|
@@ -377,6 +422,11 @@ export class DeepResearchOrchestrator {
|
|
|
377
422
|
planningService.addToQueryHistory(researchId, plan.allQueries);
|
|
378
423
|
}
|
|
379
424
|
|
|
425
|
+
// Report count BEFORE this round, for the capacity-only grace-round check below.
|
|
426
|
+
const reportsBeforeRound = (await getService<IResearchSynthesisService>(
|
|
427
|
+
ServiceNames.RESEARCH_SYNTHESIS_SERVICE, ctx, container,
|
|
428
|
+
)).getReportCount(researchId);
|
|
429
|
+
|
|
380
430
|
// 2. Search Phase + per-researcher store queries (run in parallel)
|
|
381
431
|
let researcherLinks: Map<string, string[]> | undefined;
|
|
382
432
|
let storeLinks: Map<string, { url: string; description: string }[]> | undefined;
|
|
@@ -456,6 +506,25 @@ export class DeepResearchOrchestrator {
|
|
|
456
506
|
currentRound: this.currentRound,
|
|
457
507
|
signal
|
|
458
508
|
}, researcherLinks, storeLinks);
|
|
509
|
+
|
|
510
|
+
// Did this round produce anything? Report count is cumulative, so a delta is
|
|
511
|
+
// the only honest answer; the failure list is cumulative too, hence the
|
|
512
|
+
// "all recorded failures are capacity" check rather than a per-round one.
|
|
513
|
+
const reportsAfterRound = (await getService<IResearchSynthesisService>(
|
|
514
|
+
ServiceNames.RESEARCH_SYNTHESIS_SERVICE, ctx, container,
|
|
515
|
+
)).getReportCount(researchId);
|
|
516
|
+
if (reportsAfterRound <= reportsBeforeRound && hasOnlyCapacityFailures(this.options.sessionId, researchId)) {
|
|
517
|
+
capacityOnlyRounds++;
|
|
518
|
+
logger.warn(
|
|
519
|
+
`[DeepOrchestrator] Round ${this.currentRound} produced no report and every failure was a provider ` +
|
|
520
|
+
`capacity failure (${capacityOnlyRounds} consecutive, 1 tolerated)`,
|
|
521
|
+
);
|
|
522
|
+
if (capacityOnlyRounds > 1) {
|
|
523
|
+
throw createResearchStopError(this.options.sessionId, researchId);
|
|
524
|
+
}
|
|
525
|
+
} else {
|
|
526
|
+
capacityOnlyRounds = 0;
|
|
527
|
+
}
|
|
459
528
|
}
|
|
460
529
|
|
|
461
530
|
// Esc/abort responsiveness: runResearchers returns NORMALLY when the signal
|
|
@@ -283,8 +283,21 @@ export class ResearchSynthesisService implements IService {
|
|
|
283
283
|
// the second, and telling a user the run was interrupted when it was not is exactly
|
|
284
284
|
// the kind of misleading output this fallback exists to avoid.
|
|
285
285
|
synthesis += `This is an automated compilation of ${reportCount} individual researcher report(s). The synthesis step did not produce a usable summary for this run, so the findings are presented as collected.\n\n`;
|
|
286
|
+
// Report keys are `${round}.${researcherId}` (see researcher-executor's storeReport),
|
|
287
|
+
// and planner-assigned researcher ids are frequently themselves dotted (`1.1`, `1.2`),
|
|
288
|
+
// so printing the raw key labelled round 1's third researcher as "Researcher 1.1.3" —
|
|
289
|
+
// ambiguous, and read as a researcher that never existed. Print the two fields
|
|
290
|
+
// separately: the round belongs in prose, the id verbatim.
|
|
286
291
|
synthesis += Array.from(reports.entries())
|
|
287
|
-
.map(([
|
|
292
|
+
.map(([key, report]) => {
|
|
293
|
+
const dot = key.indexOf('.');
|
|
294
|
+
const round = dot > 0 ? key.slice(0, dot) : '';
|
|
295
|
+
const researcherId = dot > 0 ? key.slice(dot + 1) : key;
|
|
296
|
+
const label = round && /^\d+$/.test(round)
|
|
297
|
+
? `Researcher ${researcherId} (round ${round})`
|
|
298
|
+
: `Researcher ${key}`;
|
|
299
|
+
return `${label}\n\n${report}`;
|
|
300
|
+
})
|
|
288
301
|
.join('\n\n');
|
|
289
302
|
}
|
|
290
303
|
|
|
@@ -24,6 +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
28
|
|
|
28
29
|
/**
|
|
29
30
|
* Failures a retry cannot fix, because the next attempt sends the same request to
|
|
@@ -50,14 +51,13 @@ import { RESEARCHER_DIGEST_SECTION } from '../utils/coverage-digest.ts';
|
|
|
50
51
|
* bounding total retry time rather than by refusing the retry that usually works.
|
|
51
52
|
*/
|
|
52
53
|
export function isUnretriableResearcherError(error: unknown): boolean {
|
|
53
|
-
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|| message.includes('insufficient_quota');
|
|
54
|
+
// Delegated to isSpentAccountError (src/utils/provider-errors.ts) so there is ONE
|
|
55
|
+
// wording list. Both answer the same question — "is this a balance that will not
|
|
56
|
+
// refill?" — and when they drifted, a 429 worded "exceeded your current quota" was
|
|
57
|
+
// retried on the ordinary curve here while the capacity classifier already refused to
|
|
58
|
+
// call it capacity. Both match the provider's wording, never a bare status code: a code
|
|
59
|
+
// can appear inside an unrelated payload, and this gate ends a researcher's run.
|
|
60
|
+
return isSpentAccountError(error);
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
/**
|
|
@@ -75,21 +75,6 @@ export function isInFlightBudgetError(error: unknown): boolean {
|
|
|
75
75
|
|| lower.includes('would exceed your available credits given your current in-flight requests');
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
/**
|
|
79
|
-
* The `Retry-After` a provider error asked for, in ms, clamped to [5s, 60s], or null when
|
|
80
|
-
* the error carries none. Read out of the message because the researcher retry loop sees a
|
|
81
|
-
* serialized provider error, not the raw Response headers: pi's `after_provider_response`
|
|
82
|
-
* hook (src/index.ts) is the only place with headers, and it does not feed this loop.
|
|
83
|
-
*/
|
|
84
|
-
export function parseRetryAfterMs(error: unknown): number | null {
|
|
85
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
86
|
-
const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
|
|
87
|
-
if (!m) return null;
|
|
88
|
-
const seconds = Number(m[1]);
|
|
89
|
-
if (!Number.isFinite(seconds) || seconds <= 0) return null;
|
|
90
|
-
return Math.min(Math.max(seconds, 5), 60) * 1000;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
78
|
/**
|
|
94
79
|
* Run a single researcher with retries
|
|
95
80
|
*/
|
|
@@ -244,8 +229,9 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
|
|
|
244
229
|
.replace('{{digest_section}}', () => RESEARCHER_DIGEST_SECTION)
|
|
245
230
|
.trim();
|
|
246
231
|
|
|
247
|
-
// Set when the previous attempt failed on the provider's in-flight budget
|
|
248
|
-
// backoff uses the provider's Retry-After
|
|
232
|
+
// Set when the previous attempt failed on the provider's in-flight budget or on a
|
|
233
|
+
// rate limit: the next backoff uses the provider's Retry-After (or the long
|
|
234
|
+
// rate-limit step) instead of the small exponential 1-2s step.
|
|
249
235
|
let inFlightBackoffMs: number | null = null;
|
|
250
236
|
|
|
251
237
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
@@ -259,9 +245,13 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
|
|
|
259
245
|
return;
|
|
260
246
|
}
|
|
261
247
|
if (attempt > 1) {
|
|
262
|
-
// A provider-declared in-flight window overrides the exponential step
|
|
263
|
-
// one attempt: the condition cannot clear in 1-2s, and the provider
|
|
264
|
-
// how long it needs (isInFlightBudgetError / parseRetryAfterMs)
|
|
248
|
+
// A provider-declared rate-limit / in-flight window overrides the exponential step
|
|
249
|
+
// for exactly one attempt: the condition cannot clear in 1-2s, and the provider
|
|
250
|
+
// already said how long it needs (isInFlightBudgetError / parseRetryAfterMs), or —
|
|
251
|
+
// for an unadorned 429 — the rate-limit step (rateLimitBackoffMs) applies instead
|
|
252
|
+
// of the ordinary 1s/2s/4s curve, which cannot outlast a shared-pool limit.
|
|
253
|
+
// RESEARCHER_MAX_RETRY_DELAY_MS caps the ORDINARY step only; it is user-tunable to
|
|
254
|
+
// as little as a second, so it must never shorten a provider-mandated wait.
|
|
265
255
|
const delay = inFlightBackoffMs ?? Math.min(1000 * Math.pow(2, attempt - 2), config.RESEARCHER_MAX_RETRY_DELAY_MS);
|
|
266
256
|
inFlightBackoffMs = null;
|
|
267
257
|
logger.warn(`[ResearcherExecutor] Researcher ${id} retry ${attempt - 1}/${config.RESEARCHER_MAX_RETRIES} after ${delay}ms`);
|
|
@@ -632,12 +622,22 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
|
|
|
632
622
|
break;
|
|
633
623
|
}
|
|
634
624
|
|
|
635
|
-
// Transient provider
|
|
625
|
+
// Transient provider conditions that need a real wait, not a retry loop: honor the
|
|
636
626
|
// Retry-After it returned (clamped) for the next attempt instead of 1-2s.
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
627
|
+
// • in-flight budget (402): the account's own open requests must settle.
|
|
628
|
+
// • rate limit / 429: the upstream provider's shared pool is full. Observed on
|
|
629
|
+
// 2026-10-25 lasting over six minutes, while four attempts spaced 1s/2s/4s
|
|
630
|
+
// burned out in ~40s and failed two of three researchers.
|
|
631
|
+
if (attempt < maxAttempts) {
|
|
632
|
+
if (isInFlightBudgetError(err)) {
|
|
633
|
+
inFlightBackoffMs = parseRetryAfterMs(err) ?? 15000;
|
|
634
|
+
metrics.increment('researcher_inflight_budget_backoff_total', 1, { mode: 'deep', complexity: String(complexity) });
|
|
635
|
+
logger.warn(`[ResearcherExecutor] Researcher ${id} hit the provider's in-flight budget; backing off ${inFlightBackoffMs}ms (provider Retry-After, else 15s) before attempt ${attempt + 1}`);
|
|
636
|
+
} else if (isRateLimitError(err)) {
|
|
637
|
+
inFlightBackoffMs = rateLimitBackoffMs(attempt + 1, parseRetryAfterMs(err));
|
|
638
|
+
metrics.increment('researcher_rate_limit_backoff_total', 1, { mode: 'deep', complexity: String(complexity) });
|
|
639
|
+
logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
|
|
640
|
+
}
|
|
641
641
|
}
|
|
642
642
|
|
|
643
643
|
if (attempt < maxAttempts) {
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { generateSessionId as generateUniqueSessionId, clearAllSharedLinks } from '../utils/shared-links.ts';
|
|
9
|
+
import { isCapacityFailureReason } from '../utils/provider-errors.ts';
|
|
9
10
|
import { logger } from '../logger.ts';
|
|
10
11
|
import { getConfig } from '../config.ts';
|
|
11
12
|
import type { ResearchPanelState } from '../types/research-panel-types.ts';
|
|
@@ -176,6 +177,7 @@ export function addSteeringMessage(piSessionId: string | undefined, message: str
|
|
|
176
177
|
addedAt: Date.now(),
|
|
177
178
|
consumedAt: null,
|
|
178
179
|
poppedAt: null,
|
|
180
|
+
forwardedToPiAt: null,
|
|
179
181
|
};
|
|
180
182
|
|
|
181
183
|
logger.debug(`[session-state] Adding steering message to session ${sid}: ${message} (id: ${steeringMsg.id})`);
|
|
@@ -297,10 +299,53 @@ export function requeuePoppedMessage(piSessionId: string | undefined, messageId:
|
|
|
297
299
|
if (!msg) return;
|
|
298
300
|
msg.status = 'queued';
|
|
299
301
|
msg.poppedAt = null;
|
|
302
|
+
msg.forwardedToPiAt = null;
|
|
300
303
|
logger.debug(`[session-state] Restored popped steering message to queued in session ${sid} (id: ${messageId})`);
|
|
301
304
|
refreshAllSessions(sid);
|
|
302
305
|
}
|
|
303
306
|
|
|
307
|
+
/**
|
|
308
|
+
* Record that a popped message was successfully handed to pi's own steering queue
|
|
309
|
+
* (Alt+P). Called only AFTER pi accepted it: a failed forward is requeued instead.
|
|
310
|
+
*/
|
|
311
|
+
export function markSteeringForwardedToPi(piSessionId: string | undefined, messageIds: readonly string[]): void {
|
|
312
|
+
const sid = normalizeSessionId(piSessionId);
|
|
313
|
+
const state = piSessions.get(sid);
|
|
314
|
+
if (!state || messageIds.length === 0) return;
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
const want = new Set(messageIds);
|
|
317
|
+
let marked = 0;
|
|
318
|
+
for (const msg of state.steeringMessages) {
|
|
319
|
+
if (msg.status === 'popped' && want.has(msg.id) && msg.forwardedToPiAt === null) {
|
|
320
|
+
msg.forwardedToPiAt = now;
|
|
321
|
+
marked++;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (marked > 0) {
|
|
325
|
+
logger.debug(`[session-state] Marked ${marked} popped steering message(s) as forwarded to pi in session ${sid}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* True while this pi session still has a steering message this extension handed to
|
|
331
|
+
* pi and pi has not necessarily delivered yet.
|
|
332
|
+
*
|
|
333
|
+
* Used by the global TUI controller: while streaming, pi's Esc handler is
|
|
334
|
+
* `restoreQueuedMessagesToEditor({abort:true})`, which CLEARS pi's steering queue,
|
|
335
|
+
* dumps the queued texts into the editor and aborts the turn. A popped message that
|
|
336
|
+
* fell through that path therefore stops being an instruction and a later editor
|
|
337
|
+
* clear loses it. See the Esc branch in tui-controller.ts.
|
|
338
|
+
*
|
|
339
|
+
* Deliberately a per-session read, not per-run: the marker is cleared when the run
|
|
340
|
+
* ends (the message is pruned with the run) or when a new run starts.
|
|
341
|
+
*/
|
|
342
|
+
export function hasForwardedSteering(piSessionId: string | undefined): boolean {
|
|
343
|
+
const sid = normalizeSessionId(piSessionId);
|
|
344
|
+
const state = piSessions.get(sid);
|
|
345
|
+
if (!state) return false;
|
|
346
|
+
return state.steeringMessages.some(m => m.status === 'popped' && m.forwardedToPiAt !== null);
|
|
347
|
+
}
|
|
348
|
+
|
|
304
349
|
/**
|
|
305
350
|
* Clear all steering messages for a Pi session regardless of status.
|
|
306
351
|
*/
|
|
@@ -502,6 +547,12 @@ export function startResearchSession(piSessionId: string | undefined, customRese
|
|
|
502
547
|
const state = getPiState(sid);
|
|
503
548
|
state.failures.set(researchId, []);
|
|
504
549
|
state.failureReasons.set(researchId, new Map());
|
|
550
|
+
// A message forwarded to pi belongs to the run it was popped during: by the time a
|
|
551
|
+
// NEW run starts, pi has had its next agent step and delivered it. Keeping the
|
|
552
|
+
// marker would make the next run's FIRST Esc consume itself for no reason.
|
|
553
|
+
for (const msg of state.steeringMessages) {
|
|
554
|
+
if (msg.forwardedToPiAt !== null) msg.forwardedToPiAt = null;
|
|
555
|
+
}
|
|
505
556
|
return researchId;
|
|
506
557
|
}
|
|
507
558
|
|
|
@@ -683,12 +734,64 @@ export function getFailedResearchers(piSessionId: string | undefined, researchId
|
|
|
683
734
|
*/
|
|
684
735
|
const DEFAULT_MAX_FAILED_RESEARCHERS = 2;
|
|
685
736
|
|
|
737
|
+
/**
|
|
738
|
+
* Failures that must NOT count toward the stop threshold.
|
|
739
|
+
*
|
|
740
|
+
* A provider-capacity failure (429 / upstream pool exhausted / in-flight budget) says
|
|
741
|
+
* nothing about whether the topic is researchable — the same model produces a report
|
|
742
|
+
* once the pool frees up. Counting it lets one upstream outage end an otherwise healthy
|
|
743
|
+
* run: on 2026-10-25 two of three researchers lost every attempt to a DeepInfra
|
|
744
|
+
* `engine_overloaded` 429, the threshold (2) tripped, and the run stopped with one
|
|
745
|
+
* third of its angle set explored and a raw-compilation fallback as the answer.
|
|
746
|
+
* Dropping these from the count keeps the run alive; it is still bounded by the round
|
|
747
|
+
* budget and RESEARCHER_TIMEOUT_MS, and each researcher still owns its own retries.
|
|
748
|
+
*/
|
|
749
|
+
function countTowardStopThreshold(reasons: Map<string, string> | undefined, researcherId: string): boolean {
|
|
750
|
+
return !isCapacityFailureReason(reasons?.get(researcherId));
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* True when this run has at least one recorded failure and EVERY one of them is a
|
|
755
|
+
* provider-capacity failure.
|
|
756
|
+
*
|
|
757
|
+
* Run-scoped and de-duplicated by design (`state.failures` keeps unique ids, first reason
|
|
758
|
+
* wins). It answers "has anything in this run failed for a non-capacity reason?", which is
|
|
759
|
+
* the right question when paired with "this round produced no report": a round cannot have
|
|
760
|
+
* produced nothing for a quality reason without recording a quality failure. It cannot
|
|
761
|
+
* attribute a single round, and no caller should read it that way.
|
|
762
|
+
*
|
|
763
|
+
* Used to bound the cost of an outage: capacity failures are excluded from
|
|
764
|
+
* shouldStopResearch, so a total outage would otherwise keep the run alive for every
|
|
765
|
+
* remaining round, paying a full search burst each time against a provider that cannot
|
|
766
|
+
* answer. The orchestrator allows exactly one such empty round (the outage may clear —
|
|
767
|
+
* the observed one lasted six minutes, and each round already spends ~100s in the
|
|
768
|
+
* researcher retries) and stops after a second.
|
|
769
|
+
*/
|
|
770
|
+
export function hasOnlyCapacityFailures(piSessionId: string | undefined, researchId: string): boolean {
|
|
771
|
+
const sid = normalizeSessionId(piSessionId);
|
|
772
|
+
const failed = getFailedResearchers(sid, researchId);
|
|
773
|
+
if (failed.length === 0) return false;
|
|
774
|
+
const reasons = peekPiState(sid)?.failureReasons.get(researchId);
|
|
775
|
+
return failed.every((id) => isCapacityFailureReason(reasons?.get(id)));
|
|
776
|
+
}
|
|
777
|
+
|
|
686
778
|
/**
|
|
687
779
|
* Check if research should stop due to too many unique failures
|
|
688
780
|
*/
|
|
689
781
|
export function shouldStopResearch(piSessionId: string | undefined, researchId: string, maxFailedResearchers: number = DEFAULT_MAX_FAILED_RESEARCHERS): boolean {
|
|
690
782
|
const sid = normalizeSessionId(piSessionId);
|
|
691
|
-
|
|
783
|
+
const failed = getFailedResearchers(sid, researchId);
|
|
784
|
+
if (failed.length === 0) return false;
|
|
785
|
+
// Peek, never create — same read-path rule as getResearcherFailureReasons.
|
|
786
|
+
const reasons = peekPiState(sid)?.failureReasons.get(researchId);
|
|
787
|
+
const counted = failed.filter((id) => countTowardStopThreshold(reasons, id));
|
|
788
|
+
if (counted.length !== failed.length) {
|
|
789
|
+
logger.debug(
|
|
790
|
+
`[ResearchSessionState] ${failed.length - counted.length} capacity failure(s) excluded from the stop threshold ` +
|
|
791
|
+
`(${counted.length}/${maxFailedResearchers} counted: ${counted.join(', ') || 'none'})`,
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
return counted.length >= maxFailedResearchers;
|
|
692
795
|
}
|
|
693
796
|
|
|
694
797
|
/**
|
|
@@ -697,7 +800,16 @@ export function shouldStopResearch(piSessionId: string | undefined, researchId:
|
|
|
697
800
|
export function getResearchStopMessage(piSessionId: string | undefined, researchId: string): string {
|
|
698
801
|
const sid = normalizeSessionId(piSessionId);
|
|
699
802
|
const failed = getFailedResearchers(sid, researchId);
|
|
700
|
-
|
|
803
|
+
// Capacity failures do NOT count toward the threshold (see countTowardStopThreshold),
|
|
804
|
+
// so they must not inflate the headline either: it must agree with the rule that
|
|
805
|
+
// actually stopped the run. They are reported separately below, because the user still
|
|
806
|
+
// wants to know the provider refused them.
|
|
807
|
+
const stateForReasons = peekPiState(sid);
|
|
808
|
+
const reasonsForCount = stateForReasons?.failureReasons.get(researchId);
|
|
809
|
+
const countedFailures = failed.filter((id) => countTowardStopThreshold(reasonsForCount, id));
|
|
810
|
+
const capacityFailures = failed.filter((id) => !countTowardStopThreshold(reasonsForCount, id));
|
|
811
|
+
const count = countedFailures.length;
|
|
812
|
+
const failedList = countedFailures.length > 0 ? countedFailures.join(', ') : failed.join(', ');
|
|
701
813
|
|
|
702
814
|
// Order the causes by likelihood. The pre-run health check verifies search and
|
|
703
815
|
// scrape BEFORE researchers run, so when it passed (the normal case) the browser
|
|
@@ -715,14 +827,50 @@ export function getResearchStopMessage(piSessionId: string | undefined, research
|
|
|
715
827
|
? ['Recorded errors:', ...[...reasons].map(([id, r]) => `• researcher ${id}: ${r}`), '']
|
|
716
828
|
: [];
|
|
717
829
|
|
|
830
|
+
// Two headlines, because the two stoppage paths mean different things: a threshold stop
|
|
831
|
+
// has a real count to report; a capacity-only stop (the orchestrator's grace-round bound)
|
|
832
|
+
// has no counted failure at all, and "0 researcher(s) did not return a usable report"
|
|
833
|
+
// would read as nonsense.
|
|
834
|
+
//
|
|
835
|
+
// The capacity wording is deliberately about what is RECORDED, not about this round:
|
|
836
|
+
// the failure list is run-scoped and de-duplicated, so a round that failed the same
|
|
837
|
+
// researchers again adds nothing to it. "every recorded failure was a provider-capacity
|
|
838
|
+
// failure" is exactly true either way; "this round failed on capacity" would not be.
|
|
839
|
+
const headline = countedFailures.length > 0
|
|
840
|
+
? `Research stopped: ${count} researcher(s) did not return a usable report: ${failedList}.`
|
|
841
|
+
: `Research stopped: no report was collected, and every recorded failure was a provider-capacity failure${failedList ? `: ${failedList}` : ''}.`;
|
|
842
|
+
|
|
718
843
|
return [
|
|
719
|
-
|
|
844
|
+
headline,
|
|
720
845
|
'',
|
|
846
|
+
...(capacityFailures.length > 0
|
|
847
|
+
? [
|
|
848
|
+
`Provider capacity failures (excluded from the stop threshold): ${capacityFailures.join(', ')}.`,
|
|
849
|
+
'Those researchers lost every retry to a rate limit or an exhausted in-flight budget,',
|
|
850
|
+
'not to anything about the topic. Retrying the run later is the repair.',
|
|
851
|
+
'',
|
|
852
|
+
]
|
|
853
|
+
: []),
|
|
721
854
|
...recorded,
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
855
|
+
// Only give the "get a better model" advice when the model's output was actually the
|
|
856
|
+
// problem. When every failure was the provider refusing to serve (a rate limit or an
|
|
857
|
+
// exhausted budget), the model never ran — telling the user to change models sends
|
|
858
|
+
// them to buy a different one for a supply problem.
|
|
859
|
+
...(capacityFailures.length > 0 && capacityFailures.length === failed.length
|
|
860
|
+
? [
|
|
861
|
+
'Most likely cause — the provider would not serve the requests:',
|
|
862
|
+
'• Every researcher lost its retries to a rate limit or an exhausted in-flight budget.',
|
|
863
|
+
'• Wait and retry. A shared/free upstream pool (OpenRouter free tier, for one) is',
|
|
864
|
+
' routinely overloaded, and nothing about your setup needs to change.',
|
|
865
|
+
'• If it keeps happening, set PI_RESEARCH_MODEL to a model with a dedicated key or',
|
|
866
|
+
' a provider that is not sharing a pool.',
|
|
867
|
+
]
|
|
868
|
+
: [
|
|
869
|
+
'Most likely cause — the research model could not produce grounded results:',
|
|
870
|
+
'• Try a more capable research model. Very small or "thinking-only" models often',
|
|
871
|
+
' emit no final text after their tool calls, which fails every researcher.',
|
|
872
|
+
'• Verify the model is available and the API key / context settings are valid.',
|
|
873
|
+
]),
|
|
726
874
|
'',
|
|
727
875
|
'Less likely — a network or browser problem (only if the health check did NOT pass):',
|
|
728
876
|
'• Verify the network connection is active.',
|
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
|
}
|