@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.
Files changed (32) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +399 -163
  3. package/dist/thread-worker.mjs +77 -31
  4. package/docs/CHANGELOG.md +46 -0
  5. package/docs/CONFIGURATION.md +8 -3
  6. package/docs/THIRD-PARTY-NOTICES.md +29 -13
  7. package/docs/TROUBLESHOOTING.md +16 -0
  8. package/package.json +12 -9
  9. package/scripts/ddg-socks-proxy.mjs +279 -0
  10. package/scripts/lib/npm-cmd.cjs +66 -0
  11. package/scripts/lib/private-addresses.mjs +143 -0
  12. package/src/config.ts +75 -2
  13. package/src/core/interfaces/steering-interfaces.ts +11 -0
  14. package/src/core/llm/coordinator-model.ts +104 -0
  15. package/src/core/planning-service.ts +24 -0
  16. package/src/index.ts +7 -1
  17. package/src/infrastructure/browser/proxy-prefs.ts +124 -0
  18. package/src/infrastructure/browser/thread-worker-browser.ts +5 -21
  19. package/src/infrastructure/browser/thread-worker-messaging.ts +9 -4
  20. package/src/infrastructure/browser/thread-worker.mjs +77 -31
  21. package/src/knowledge/embedder-utils.ts +1 -1
  22. package/src/knowledge/sql-utils.ts +15 -0
  23. package/src/knowledge/store-operations.ts +3 -2
  24. package/src/knowledge/store.ts +15 -14
  25. package/src/orchestration/deep-research-orchestrator.ts +71 -2
  26. package/src/orchestration/research-synthesis-service.ts +14 -1
  27. package/src/orchestration/researcher-executor.ts +33 -33
  28. package/src/orchestration/session-state.ts +155 -7
  29. package/src/tools/read-guard.ts +23 -4
  30. package/src/tui/tui-controller.ts +25 -1
  31. package/src/utils/provider-errors.ts +149 -0
  32. package/src/web-research/retry-utils.ts +22 -3
@@ -9,7 +9,7 @@
9
9
 
10
10
  import type { ExtensionUIContext } from '@earendil-works/pi-coding-agent';
11
11
  import { isKeyRelease, matchesKey } from '@earendil-works/pi-tui';
12
- import { getActiveSessionCount, abortAllSessions, refreshAllSessions, hideMasterWidget } from '../orchestration/session-state.ts';
12
+ import { getActiveSessionCount, abortAllSessions, refreshAllSessions, hideMasterWidget, hasForwardedSteering } from '../orchestration/session-state.ts';
13
13
  import { logger } from '../logger.ts';
14
14
 
15
15
  /**
@@ -140,6 +140,30 @@ export function initGlobalTuiController(ui: ExtensionUIContext, piSessionId?: st
140
140
  } catch (err) {
141
141
  logger.error('[TUI] Failed to abort sessions on cancel:', err);
142
142
  }
143
+
144
+ // EXCEPTION to the fall-through above: the user handed a steering message
145
+ // to pi (Alt+P) during this run, so pi is holding it in its own queue.
146
+ //
147
+ // pi's Esc-while-streaming path is `restoreQueuedMessagesToEditor({abort:
148
+ // true})` (verified in pi's bundled TUI): it calls `clearAllQueues()`, joins
149
+ // the queued texts into the EDITOR, and then aborts the turn. So falling
150
+ // through un-queues the popped message, turns it into editor text, and ends
151
+ // the turn — it is never delivered as an instruction, and any later editor
152
+ // clear loses it. That is the "my popped message vanished" report.
153
+ //
154
+ // Consuming the key skips that path: research still cancels (abortAllSessions
155
+ // above), the research tool returns into pi's turn, and pi drains its steering
156
+ // queue at the next step — exactly what "pop" promised. Steering the user did
157
+ // NOT pop never reached pi's queue, stays in this extension's state, and is
158
+ // still dropped with the run, as before.
159
+ //
160
+ // Cost, deliberately accepted: pi does not abort its own turn for this Esc. A
161
+ // second Esc (no active research) falls through normally, so the panic-cancel
162
+ // gesture is one extra keystroke away, not gone.
163
+ if (hasForwardedSteering(state.piSessionId)) {
164
+ logger.info('[TUI] Esc while a popped steering message is queued in pi — aborting research and consuming the key so pi delivers the message.');
165
+ return { consume: true };
166
+ }
143
167
  }
144
168
  return undefined;
145
169
  }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Provider capacity-error classification.
3
+ *
4
+ * Two places need the same answer to "is this failure the provider running out of
5
+ * room, rather than this run being wrong?":
6
+ *
7
+ * - the researcher retry loop, which must wait long enough for a shared-pool
8
+ * rate limit to clear instead of burning its whole retry budget in 7 seconds
9
+ * (researcher-executor.ts), and
10
+ * - the run-level failure threshold, which must not treat "every researcher hit
11
+ * the provider's rate limit" as "the research model cannot do this topic"
12
+ * (session-state.ts shouldStopResearch).
13
+ *
14
+ * Kept in a leaf module so neither importer has to depend on the other; the
15
+ * executor already imports session-state, so putting the predicate there would
16
+ * create a cycle.
17
+ */
18
+
19
+ /**
20
+ * A SPENT ACCOUNT, which is often reported as a 429 too.
21
+ *
22
+ * This is the single wording list for the class. OpenAI-style quotas answer `429` with
23
+ * `insufficient_quota`; OpenRouter answers `402` with "requires more credits". The status
24
+ * code cannot separate these from a transient rate limit, but the consequence is opposite:
25
+ * the balance does not refill between attempts, so this class is unretriable AND must
26
+ * never be treated as capacity — a run kept alive through three rounds against an account
27
+ * that cannot pay does nothing but burn DuckDuckGo load. `isUnretriableResearcherError`
28
+ * (researcher-executor.ts) delegates here rather than keeping a second copy.
29
+ */
30
+ export function isSpentAccountError(error: unknown): boolean {
31
+ const msg = (error instanceof Error ? error.message : String(error)).toLowerCase();
32
+ return msg.includes('insufficient_quota')
33
+ || msg.includes('insufficient credits')
34
+ || msg.includes('requires more credits')
35
+ || msg.includes('exceeded your current quota')
36
+ || msg.includes('out of credits');
37
+ }
38
+
39
+ /**
40
+ * Provider wording for "too many requests right now".
41
+ *
42
+ * Matched on the provider's wording rather than a bare status code, for the same
43
+ * reason as isSpentAccountError: a `429` substring can appear inside an
44
+ * unrelated payload (a token count, a URL, a quoted response body), and this
45
+ * predicate decides how long a researcher sleeps and whether a run keeps going.
46
+ *
47
+ * The real OpenRouter shape (observed 2026-10-25):
48
+ * `429: {"message":"Provider returned error","code":429,"metadata":{"raw":
49
+ * "inclusionai/ling-3.0-flash is temporarily rate-limited upstream. Please
50
+ * retry shortly, ...","provider_name":"DeepInfra",
51
+ * "provider_error_code":"engine_overloaded",
52
+ * "limit_source":"upstream_provider_shared_pool"}}`
53
+ * pi-research's own wrapper adds the prefix `Model API rate limit (429) — wait a
54
+ * moment and retry.`
55
+ *
56
+ * `engine_overloaded` / `provider_overloaded` are the upstream-pool variants that
57
+ * arrive as a 429 body; matched explicitly so a bare "overloaded" cannot collide
58
+ * with unrelated wording (e.g. a CSS/DOM "overloaded selector" in scraped text).
59
+ */
60
+ export function isRateLimitError(error: unknown): boolean {
61
+ // A spent account answers 429 as well; it is NOT a transient limit. Checked first so
62
+ // no caller that forgot the distinction (backoff, stop threshold, retry policy) can
63
+ // treat an empty balance as a temporary condition.
64
+ if (isSpentAccountError(error)) return false;
65
+ const msg = (error instanceof Error ? error.message : String(error)).toLowerCase();
66
+ return /\b429\b/.test(msg)
67
+ || msg.includes('rate limit')
68
+ || msg.includes('rate-limit')
69
+ || msg.includes('rate limited')
70
+ || msg.includes('too many requests')
71
+ || msg.includes('engine_overloaded')
72
+ || msg.includes('provider_overloaded');
73
+ }
74
+
75
+ /**
76
+ * The same question, asked of a recorded failure REASON (a string, not an Error).
77
+ * A missing reason is not a capacity failure: the conservative default is to count
78
+ * it toward the stop threshold, exactly as before this classification existed.
79
+ */
80
+ export function isCapacityFailureReason(reason: string | undefined): boolean {
81
+ // isRateLimitError already excludes the spent-account class, so an out-of-credits
82
+ // failure is NOT capacity and still counts toward the stop threshold.
83
+ return reason !== undefined && reason !== '' && isRateLimitError(reason);
84
+ }
85
+
86
+ /**
87
+ * The `Retry-After` a provider error asked for, in ms, clamped to [5s, 60s], or null when
88
+ * the error carries none. Read out of the message because every caller sees a serialized
89
+ * provider error, not the raw Response headers: pi's `after_provider_response` hook
90
+ * (src/index.ts) is the only place with headers, and it does not feed these retry loops.
91
+ *
92
+ * Shared (researcher loop + planning/router retries) so the two cannot drift; it lives
93
+ * here rather than in either caller because core/ must not import orchestration/.
94
+ */
95
+ export function parseRetryAfterMs(error: unknown): number | null {
96
+ const message = error instanceof Error ? error.message : String(error);
97
+ const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
98
+ if (!m) return null;
99
+ const seconds = Number(m[1]);
100
+ if (!Number.isFinite(seconds) || seconds <= 0) return null;
101
+ return Math.min(Math.max(seconds, 5), 60) * 1000;
102
+ }
103
+
104
+ /**
105
+ * Base delay for a researcher's first retry after a rate limit. 15s, not the 1s
106
+ * the ordinary exponential step uses: a shared-pool limit is enforced over
107
+ * seconds-to-minutes, and the observed outage (2026-10-25) outlasted four
108
+ * attempts spaced 1s/2s/4s by more than six minutes.
109
+ */
110
+ export const RATE_LIMIT_BACKOFF_BASE_MS = 15_000;
111
+
112
+ /**
113
+ * Ceiling for one rate-limit wait. The provider's own `Retry-After` wins when
114
+ * present (clamped by parseRetryAfterMs to 60s); this only bounds the exponential
115
+ * fallback, so three retries cost at most 15s + 30s + 60s of waiting.
116
+ */
117
+ export const RATE_LIMIT_BACKOFF_MAX_MS = 60_000;
118
+
119
+ /**
120
+ * How long to wait before retry `attempt` (2 = first retry).
121
+ *
122
+ * `retryAfterMs` is the provider's stated window when the error carried one — it
123
+ * overrides the exponential step, because the provider knows when its pool frees
124
+ * up and we do not. Otherwise: 15s, 30s, 60s (capped), each with ±20% jitter.
125
+ *
126
+ * The jitter is load-bearing, not cosmetic: every researcher in a round normally
127
+ * retries on the same second, so without it N researchers slam the same exhausted
128
+ * upstream pool in lockstep and all fail again, which is exactly what happened on
129
+ * 2026-10-25 (researchers 1.1 and 1.2 retried at 15:58:03, 15:58:27 and 15:58:54
130
+ * and failed three times each in cadence).
131
+ */
132
+ export function rateLimitBackoffMs(
133
+ attempt: number,
134
+ retryAfterMs: number | null,
135
+ random: () => number = Math.random,
136
+ ): number {
137
+ if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
138
+ return clampRateLimitWait(retryAfterMs);
139
+ }
140
+ const exponent = Math.max(0, attempt - 2);
141
+ const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
142
+ const jitter = base * 0.2 * (random() * 2 - 1);
143
+ return clampRateLimitWait(base + jitter);
144
+ }
145
+
146
+ /** Keep a wait inside [1s, 60s] — the same bounds parseRetryAfterMs applies to a stated window. */
147
+ export function clampRateLimitWait(ms: number): number {
148
+ return Math.min(Math.max(Math.round(ms), 1_000), RATE_LIMIT_BACKOFF_MAX_MS);
149
+ }
@@ -35,6 +35,18 @@ export interface RetryOptions {
35
35
  // When provided, aborting it short-circuits the inter-attempt backoff wait and
36
36
  // stops further retries, so a caller cancel isn't stuck behind a long sleep.
37
37
  readonly signal?: AbortSignal;
38
+ /**
39
+ * Optional per-attempt delay override. Return a value (ms) to use it instead of the
40
+ * exponential step, or null to keep the default. `nextAttempt` is 1-based in the
41
+ * caller's terms (2 = the first retry), i.e. the same numbering
42
+ * `rateLimitBackoffMs` uses.
43
+ *
44
+ * Exists for provider-mandated waits: a 429 against a shared pool needs tens of
45
+ * seconds, and `maxDelay` (10s here) exists to bound the ORDINARY step, not to cap a
46
+ * wait the provider asked for. The planning/router calls use it; see
47
+ * `rateLimitDelayFor` in src/core/planning-service.ts.
48
+ */
49
+ readonly delayFor?: (nextAttempt: number, error: Error) => number | null;
38
50
  }
39
51
 
40
52
  /**
@@ -285,7 +297,9 @@ export async function retryWithBackoff<T>(
285
297
  fn: () => Promise<T>,
286
298
  options: Partial<RetryOptions> = {},
287
299
  ): Promise<T> {
288
- const opts: Required<Omit<RetryOptions, 'signal'>> & { signal?: AbortSignal } = {
300
+ // `delayFor` stays optional (absent for every caller that does not override the wait),
301
+ // so it is excluded from the Required<> normalization rather than given a default.
302
+ const opts: Required<Omit<RetryOptions, 'signal' | 'delayFor'>> & RetryOptions = {
289
303
  maxRetries: 3,
290
304
  initialDelay: 1000,
291
305
  maxDelay: 10000,
@@ -323,8 +337,13 @@ export async function retryWithBackoff<T>(
323
337
 
324
338
  // Calculate delay with exponential backoff and jitter
325
339
  const baseDelay = opts.initialDelay * Math.pow(2, attempt);
326
- const jitter = Math.random() * 0.5 * baseDelay; // ±50% jitter
327
- const delay = Math.min(baseDelay + jitter, opts.maxDelay);
340
+ const jitter = Math.random() * 0.5 * baseDelay; // 0–50% positive jitter
341
+ // A caller that knows better (a provider-stated or rate-limit wait) wins over the
342
+ // step — including over maxDelay, which bounds only the ordinary step.
343
+ const override = opts.delayFor?.(attempt + 2, lastError);
344
+ const delay = override != null && Number.isFinite(override) && override > 0
345
+ ? Math.round(override)
346
+ : Math.min(baseDelay + jitter, opts.maxDelay);
328
347
 
329
348
  metrics.increment('retry_backoff_total', 1, { attempt: String(attempt), label: opts.label });
330
349
  metrics.observe('retry_backoff_delay_ms', delay, { attempt: String(attempt), label: opts.label });