@lincoln504/pi-research 1.7.23 → 1.7.25

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 (99) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +621 -205
  3. package/dist/prompts/research-tool-usage.md +4 -5
  4. package/dist/prompts/researcher.md +6 -36
  5. package/dist/prompts/system-coordinator.md +1 -1
  6. package/dist/prompts/system-lead-synthesizer.md +5 -5
  7. package/dist/thread-worker.mjs +22 -9
  8. package/docs/CHANGELOG.md +159 -0
  9. package/docs/CONFIGURATION.md +4 -3
  10. package/docs/TROUBLESHOOTING.md +92 -0
  11. package/package.json +9 -9
  12. package/scripts/ddg-socks-proxy.mjs +105 -15
  13. package/src/cli.ts +32 -14
  14. package/src/config.ts +20 -7
  15. package/src/core/interfaces/health-check-interfaces.ts +23 -2
  16. package/src/core/interfaces/knowledge-interfaces.ts +7 -4
  17. package/src/core/interfaces/observer-interfaces.ts +1 -1
  18. package/src/core/interfaces/orchestration-interfaces.ts +17 -12
  19. package/src/core/interfaces/planning-interfaces.ts +5 -5
  20. package/src/core/interfaces/process-interfaces.ts +2 -2
  21. package/src/core/interfaces/state-manager-interfaces.ts +6 -5
  22. package/src/core/llm/agentic-repair.ts +6 -6
  23. package/src/core/llm/llm-utils.ts +7 -4
  24. package/src/core/llm/model-registry-factory.ts +11 -11
  25. package/src/core/llm/research-model-resolver.ts +11 -11
  26. package/src/core/pi-version.ts +10 -1
  27. package/src/core/planning-service.ts +40 -14
  28. package/src/core/planning-utils.ts +33 -7
  29. package/src/core/service-initialization.ts +1 -1
  30. package/src/core/service-registry.ts +18 -11
  31. package/src/healthcheck/index.ts +67 -5
  32. package/src/healthcheck/registry.ts +5 -18
  33. package/src/index.ts +12 -16
  34. package/src/infrastructure/browser/browser-client.ts +4 -4
  35. package/src/infrastructure/browser/browser-error-utils.ts +6 -1
  36. package/src/infrastructure/browser/browser-lifecycle.ts +8 -3
  37. package/src/infrastructure/browser/browser-server.ts +3 -3
  38. package/src/infrastructure/browser/browser-task-scheduler.ts +13 -9
  39. package/src/infrastructure/browser/priority-task-queue.ts +13 -10
  40. package/src/infrastructure/browser/proxy-health.ts +342 -0
  41. package/src/infrastructure/browser/thread-worker-browser.ts +14 -11
  42. package/src/infrastructure/browser/thread-worker-lifecycle.ts +21 -15
  43. package/src/infrastructure/browser/thread-worker-messaging.ts +39 -31
  44. package/src/infrastructure/browser/thread-worker-types.ts +3 -1
  45. package/src/infrastructure/browser/thread-worker.mjs +22 -9
  46. package/src/infrastructure/browser/thread-worker.ts +3 -2
  47. package/src/infrastructure/browser/worker-pool-manager.ts +5 -5
  48. package/src/infrastructure/gpu-resource-service.ts +16 -9
  49. package/src/infrastructure/knowledge-store-service.ts +13 -10
  50. package/src/infrastructure/scheduler-factory-service.ts +4 -3
  51. package/src/infrastructure/service-initialization.ts +1 -1
  52. package/src/infrastructure/state/state-manager-service.ts +2 -2
  53. package/src/infrastructure/state/state-manager.ts +3 -3
  54. package/src/infrastructure/state/state-validator.ts +9 -3
  55. package/src/infrastructure/types/state-types.ts +12 -91
  56. package/src/knowledge/embedder-init.ts +8 -8
  57. package/src/knowledge/embedder-utils.ts +7 -3
  58. package/src/knowledge/embedder.ts +14 -10
  59. package/src/knowledge/onnx-env.ts +2 -2
  60. package/src/knowledge/store.ts +12 -11
  61. package/src/logger.ts +1 -1
  62. package/src/orchestration/deep-research-orchestrator.ts +36 -7
  63. package/src/orchestration/headless-observer.ts +1 -1
  64. package/src/orchestration/orchestration-types.ts +2 -2
  65. package/src/orchestration/quick-research-orchestrator.ts +4 -4
  66. package/src/orchestration/research-orchestration-service.ts +13 -13
  67. package/src/orchestration/research-synthesis-service.ts +15 -8
  68. package/src/orchestration/researcher-executor.ts +51 -8
  69. package/src/orchestration/researcher.ts +19 -7
  70. package/src/orchestration/service-initialization.ts +1 -1
  71. package/src/prompts/research-tool-usage.md +4 -5
  72. package/src/prompts/researcher.md +6 -36
  73. package/src/prompts/system-coordinator.md +1 -1
  74. package/src/prompts/system-lead-synthesizer.md +5 -5
  75. package/src/research-config.ts +11 -9
  76. package/src/sdk.ts +10 -10
  77. package/src/skill-install/skill-installer.ts +19 -10
  78. package/src/tools/grep.ts +57 -5
  79. package/src/tools/index.ts +0 -3
  80. package/src/tools/read-guard.ts +12 -0
  81. package/src/tools/research-knowledge-search.ts +15 -13
  82. package/src/tools/research-tool-definition.ts +15 -10
  83. package/src/tools/scrape.ts +3 -2
  84. package/src/tui/research-panel.ts +1 -1
  85. package/src/types/extension-context.ts +2 -2
  86. package/src/types/llm.ts +8 -7
  87. package/src/types/research-panel-types.ts +3 -1
  88. package/src/types/state-types.ts +98 -0
  89. package/src/utils/coverage-digest.ts +27 -6
  90. package/src/utils/llm-usage.ts +3 -3
  91. package/src/utils/provider-errors.ts +61 -9
  92. package/src/utils/safe-unref.ts +2 -2
  93. package/src/utils/shutdown-manager.ts +6 -6
  94. package/src/utils/stdio-capture.ts +25 -10
  95. package/src/utils/text-utils.ts +35 -0
  96. package/src/web-research/browser-search.ts +13 -1
  97. package/src/web-research/retry-utils.ts +29 -1
  98. package/src/web-research/scraper-utils.ts +9 -3
  99. package/src/web-research/web-scraper.ts +25 -10
@@ -4,7 +4,10 @@
4
4
  * Shared logic for safe and robust LLM interactions.
5
5
  */
6
6
 
7
- import { clampThinkingLevel, type Model, type AssistantMessage, type SimpleStreamOptions, type ModelThinkingLevel, type Tool, type TSchema, type Context, type ToolCall } from '@earendil-works/pi-ai';
7
+ // `TSchema` is a TypeBox type: since pi host 1.5.0, pi-ai no longer re-exports
8
+ // TypeBox, so it is imported from `typebox` (the canonical source) directly.
9
+ import type { TSchema } from 'typebox';
10
+ import { clampThinkingLevel, type Api, type Model, type AssistantMessage, type SimpleStreamOptions, type ModelThinkingLevel, type Tool, type Context, type ToolCall } from '@earendil-works/pi-ai';
8
11
  import { extractText } from '../../utils/text-utils.ts';
9
12
  import { logger } from '../../logger.ts';
10
13
  import { completeSimple } from './pi-ai-completion.ts';
@@ -39,7 +42,7 @@ import { completeSimple } from './pi-ai-completion.ts';
39
42
  * @returns Fully populated SimpleStreamOptions
40
43
  */
41
44
  export function buildSafeOptions(
42
- model: Model<any>,
45
+ model: Model<Api>,
43
46
  options: SimpleStreamOptions,
44
47
  defaultCap: number = 4096,
45
48
  thinkingLevel: ModelThinkingLevel = 'off'
@@ -130,7 +133,7 @@ export function buildConstrainedSubmitTool(name: string, description: string, pa
130
133
  * (args already parsed by pi-ai) or answered in text (fallback path).
131
134
  */
132
135
  export type StructuredCompletion =
133
- | { kind: 'toolCall'; toolName: string; args: Record<string, any>; response: AssistantMessage }
136
+ | { kind: 'toolCall'; toolName: string; args: Record<string, unknown>; response: AssistantMessage }
134
137
  | { kind: 'text'; text: string; response: AssistantMessage };
135
138
 
136
139
  /**
@@ -146,7 +149,7 @@ export type StructuredCompletion =
146
149
  * Errors map identically to validateAndExtractText (shared assertNoLlmError).
147
150
  */
148
151
  export async function completeSimpleStructured(
149
- model: Model<any>,
152
+ model: Model<Api>,
150
153
  context: Pick<Context, 'systemPrompt' | 'messages'>,
151
154
  tool: Tool,
152
155
  options: SimpleStreamOptions,
@@ -10,7 +10,7 @@
10
10
 
11
11
  import { ModelRegistry, ModelRuntime, getAgentDir } from '@earendil-works/pi-coding-agent';
12
12
  import { InMemoryCredentialStore } from '@earendil-works/pi-ai';
13
- import type { Model } from '@earendil-works/pi-ai';
13
+ import type { Api, Model } from '@earendil-works/pi-ai';
14
14
  import * as path from 'node:path';
15
15
  import * as fs from 'node:fs';
16
16
  import { logger } from '../../logger.ts';
@@ -26,10 +26,10 @@ import { logger } from '../../logger.ts';
26
26
  * TypeError that aborts the run.
27
27
  */
28
28
  export interface ModelRegistryLike {
29
- getAll?: () => Model<any>[];
30
- getAvailable?: () => Model<any>[];
31
- find?: (provider: string, id: string) => Model<any> | undefined;
32
- getApiKeyAndHeaders?: (model: Model<any>) => Promise<AuthResultLike>;
29
+ getAll?: () => Model<Api>[];
30
+ getAvailable?: () => Model<Api>[];
31
+ find?: (provider: string, id: string) => Model<Api> | undefined;
32
+ getApiKeyAndHeaders?: (model: Model<Api>) => Promise<AuthResultLike>;
33
33
  }
34
34
 
35
35
  /**
@@ -48,7 +48,7 @@ export type AuthResultLike =
48
48
  | { ok: false; error: string };
49
49
 
50
50
  /** Safe `getAll()` — returns [] if the host registry lacks the method. */
51
- export function safeGetAll(registry: ModelRegistryLike | null | undefined): Model<any>[] {
51
+ export function safeGetAll(registry: ModelRegistryLike | null | undefined): Model<Api>[] {
52
52
  if (registry && typeof registry.getAll === 'function') {
53
53
  try { return registry.getAll() ?? []; } catch (err) {
54
54
  logger.warn('[ModelRegistry] getAll() threw; treating as empty:', err);
@@ -63,7 +63,7 @@ export function safeGetAll(registry: ModelRegistryLike | null | undefined): Mode
63
63
  * missing method degrades to "treat every known model as available" rather than
64
64
  * crashing the researcher.
65
65
  */
66
- export function safeGetAvailable(registry: ModelRegistryLike | null | undefined): Model<any>[] {
66
+ export function safeGetAvailable(registry: ModelRegistryLike | null | undefined): Model<Api>[] {
67
67
  if (registry && typeof registry.getAvailable === 'function') {
68
68
  try { return registry.getAvailable() ?? []; } catch (err) {
69
69
  logger.warn('[ModelRegistry] getAvailable() threw; falling back to getAll():', err);
@@ -84,7 +84,7 @@ export function safeGetAvailable(registry: ModelRegistryLike | null | undefined)
84
84
  */
85
85
  export async function safeGetApiKeyAndHeaders(
86
86
  registry: ModelRegistryLike | null | undefined,
87
- model: Model<any>,
87
+ model: Model<Api>,
88
88
  ): Promise<AuthResultLike> {
89
89
  if (!registry || typeof registry.getApiKeyAndHeaders !== 'function') {
90
90
  logger.warn('[ModelRegistry] host registry has no getApiKeyAndHeaders(); cannot resolve LLM credentials. Possible pi-coding-agent version skew.');
@@ -210,7 +210,7 @@ export function getRuntimeForRegistry(registry: unknown): ModelRuntime | undefin
210
210
  * (e.g., SDK / CLI / agent-skill users without pi installed).
211
211
  * Bypasses the full ModelRegistry which would fail without models.json.
212
212
  */
213
- export function constructMinimalModel(provider: string, modelId: string, _apiKey: string): Model<any> {
213
+ export function constructMinimalModel(provider: string, modelId: string, _apiKey: string): Model<Api> {
214
214
  return {
215
215
  provider,
216
216
  id: modelId,
@@ -240,7 +240,7 @@ export function constructMinimalModel(provider: string, modelId: string, _apiKey
240
240
  contextWindow: 128_000,
241
241
  maxTokens: 32_768,
242
242
  headers: buildHeaders(provider),
243
- } as unknown as Model<any>;
243
+ } as unknown as Model<Api>;
244
244
  }
245
245
 
246
246
  /**
@@ -253,7 +253,7 @@ export function constructMinimalModel(provider: string, modelId: string, _apiKey
253
253
  * @returns The resolved Model instance
254
254
  * @throws Error if no model can be resolved
255
255
  */
256
- export function resolveModel(registry: ModelRegistry, modelSpec?: string, provider?: string, apiKey?: string): Model<any> {
256
+ export function resolveModel(registry: ModelRegistry, modelSpec?: string, provider?: string, apiKey?: string): Model<Api> {
257
257
  // 1. Explicit model string: "provider/modelId" or "modelId"
258
258
  if (modelSpec) {
259
259
  const slashIdx = modelSpec.indexOf('/');
@@ -5,7 +5,7 @@
5
5
  * explicit parameters, configuration, and host context.
6
6
  */
7
7
 
8
- import { type Model } from '@earendil-works/pi-ai';
8
+ import { type Api, type Model } from '@earendil-works/pi-ai';
9
9
  import { type ModelRegistry } from '@earendil-works/pi-coding-agent';
10
10
  import { getConfig } from '../../config.ts';
11
11
  import { logger } from '../../logger.ts';
@@ -24,9 +24,9 @@ export function resolveResearchModel(options: {
24
24
  modelRegistry: ModelRegistry;
25
25
  config?: import('../../config.ts').Config;
26
26
  modelId?: string;
27
- hostModel?: Model<any>;
27
+ hostModel?: Model<Api>;
28
28
  cwd?: string;
29
- }): Model<any> {
29
+ }): Model<Api> {
30
30
  const { modelRegistry, config, modelId, hostModel, cwd } = options;
31
31
  const activeConfig = config || getConfig(cwd);
32
32
 
@@ -38,12 +38,12 @@ export function resolveResearchModel(options: {
38
38
  const authedKeys = new Set(
39
39
  safeGetAvailable(modelRegistry).map((m) => `${m.provider}/${m.id}`)
40
40
  );
41
- const matchById = (id: string): Model<any> | undefined => {
41
+ const matchById = (id: string): Model<Api> | undefined => {
42
42
  // Exact "provider/id" wins outright; otherwise prefer an authed same-id entry.
43
43
  const allModels = safeGetAll(modelRegistry);
44
44
  const exact = allModels.find((m) => `${m.provider}/${m.id}` === id);
45
- if (exact) return exact as Model<any>;
46
- const sameId = allModels.filter((m) => m.id === id) as Model<any>[];
45
+ if (exact) return exact;
46
+ const sameId = allModels.filter((m) => m.id === id);
47
47
  return sameId.find((m) => authedKeys.has(`${m.provider}/${m.id}`)) ?? sameId[0];
48
48
  };
49
49
 
@@ -51,7 +51,7 @@ export function resolveResearchModel(options: {
51
51
  if (modelId) {
52
52
  const found = matchById(modelId);
53
53
  if (found) {
54
- return found as Model<any>;
54
+ return found;
55
55
  }
56
56
  logger.warn(`[ModelResolver] Explicit model '${modelId}' not found in registry; falling back.`);
57
57
  }
@@ -61,7 +61,7 @@ export function resolveResearchModel(options: {
61
61
  const target = activeConfig.RESEARCH_MODEL;
62
62
  const found = matchById(target);
63
63
  if (found) {
64
- return found as Model<any>;
64
+ return found;
65
65
  }
66
66
  logger.warn(`[ModelResolver] RESEARCH_MODEL '${target}' not found in registry; falling back.`);
67
67
  }
@@ -77,14 +77,14 @@ export function resolveResearchModel(options: {
77
77
  // of several authed providers to prefer).
78
78
  const available = safeGetAvailable(modelRegistry);
79
79
  if (available.length > 0) {
80
- return pickPreferredAvailable(available, readModelsJsonProviderOrder()) as Model<any>;
80
+ return pickPreferredAvailable(available, readModelsJsonProviderOrder())!;
81
81
  }
82
82
 
83
83
  // 5. Last resort before failing: any known model at all (host may not expose
84
84
  // getAvailable(), so an empty "available" set is not proof of "no models").
85
85
  const anyModel = safeGetAll(modelRegistry);
86
86
  if (anyModel.length > 0) {
87
- return pickPreferredAvailable(anyModel, readModelsJsonProviderOrder()) as Model<any>;
87
+ return pickPreferredAvailable(anyModel, readModelsJsonProviderOrder())!;
88
88
  }
89
89
 
90
90
  throw new Error(buildNoModelAvailableMessage());
@@ -118,7 +118,7 @@ export function resolveResearchModel(options: {
118
118
  * DEFINITELY active" — a false negative is expected and fine for providers
119
119
  * outside these two cases, but a false positive would be a real bug.
120
120
  */
121
- export function isPromptCachingActiveForModel(model: Model<any> | undefined): boolean {
121
+ export function isPromptCachingActiveForModel(model: Model<Api> | undefined): boolean {
122
122
  if (!model) return false;
123
123
  if (model.api === 'anthropic-messages') return true;
124
124
  if (model.api === 'openai-completions') {
@@ -157,8 +157,17 @@ export const PI_MIN_VERSION: SemverParts = { major: 0, minor: 99, patch: 0 };
157
157
  * package's custom TUI panels do not share), and restores terminal modes on unclean exit. The
158
158
  * `before_provider_headers` attribution-header change and the `generateSummary()`
159
159
  * `reserveTokens` change touch no API this package registers or calls.
160
+ *
161
+ * 1.5.0 (2026-11-08) verified 2026-11-08: the host moves tool-argument validation to
162
+ * `@earendil-works/pi-schema` (TypeBox features outside JSON Schema no longer apply to
163
+ * tool args), re-maps the `Type`/`Static`/`TSchema` imports through pi-ai's compat entry
164
+ * (so this package's test schema imports `Type` from `typebox` directly), and adds a
165
+ * private `getExtensionPathKey` to its ResourceLoader — an internal helper, not a
166
+ * contract method (see `HOST_INTERNAL_HELPERS`). The built-in `createReadTool()` /
167
+ * `createGrepTool()` factories this package wraps are unchanged, and `package.json` still
168
+ * pins `typebox` at `1.3.27`, so the lockstep rule and the 0.99.0 floor are unchanged.
160
169
  */
161
- export const PI_TESTED_MAX_VERSION: SemverParts = { major: 1, minor: 4, patch: 0 };
170
+ export const PI_TESTED_MAX_VERSION: SemverParts = { major: 1, minor: 5, patch: 0 };
162
171
 
163
172
  export type PiCompatibilityLevel = 'ok' | 'unparseable' | 'too-old' | 'untested';
164
173
 
@@ -17,7 +17,7 @@ import type {
17
17
  } from './service-interfaces.ts';
18
18
  import { logger } from '../logger.ts';
19
19
  import { metrics } from '../utils/metrics.ts';
20
- import { isRateLimitError, parseRetryAfterMs, rateLimitBackoffMs } from '../utils/provider-errors.ts';
20
+ import { isRateLimitError, parseRetryAfterMs, rateLimitBackoffMs, RATE_LIMIT_TOTAL_WAIT_MAX_MS } from '../utils/provider-errors.ts';
21
21
  import { completeSimple } from './llm/pi-ai-completion.ts';
22
22
  import { injectCurrentDate } from './llm/inject-date.ts';
23
23
  import { loadPrompt } from './llm/prompts.ts';
@@ -30,7 +30,7 @@ import { safeGetApiKeyAndHeaders } from './llm/model-registry-factory.ts';
30
30
  import { withTimeout } from './llm/llm-timeout.ts';
31
31
  import { retryWithBackoff, isTransientError } from '../web-research/retry-utils.ts';
32
32
  import { getConfig, type Config } from '../config.ts';
33
- import type { Model, Tool } from '@earendil-works/pi-ai';
33
+ import type { Api, Model, Tool } from '@earendil-works/pi-ai';
34
34
  import { DEFAULT_MODEL_CONTEXT_WINDOW } from '../constants.ts';
35
35
  import { deriveCoverageDigest, formatDigestsForRouter } from '../utils/coverage-digest.ts';
36
36
  import {
@@ -44,6 +44,7 @@ import {
44
44
  getComplexityGuidance as _getComplexityGuidance,
45
45
  getEvaluatorComplexityGuidance as _getEvaluatorComplexityGuidance,
46
46
  getRoundPhaseGuidance as _getRoundPhaseGuidance,
47
+ effectiveSingleResearcher,
47
48
  parseJsonPlan as _parseJsonPlan,
48
49
  buildFallbackCoordinatorPlan as _buildFallbackCoordinatorPlan,
49
50
  capResearcherQueries as _capResearcherQueries,
@@ -384,8 +385,8 @@ export class PlanningService implements IPlanningService {
384
385
  return _buildFallbackCoordinatorPlan('PlanningService', rawText, query);
385
386
  }
386
387
 
387
- capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string): ResearchPlan {
388
- return _capResearcherQueries(plan, complexity, serviceName);
388
+ capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string, singleResearcher = false): ResearchPlan {
389
+ return _capResearcherQueries(plan, complexity, serviceName, singleResearcher);
389
390
  }
390
391
 
391
392
  generateResearchers(plan: ResearchPlan, query: string, complexity: 1 | 2 | 3): ResearcherConfig[] {
@@ -417,7 +418,18 @@ export class PlanningService implements IPlanningService {
417
418
 
418
419
  const maxTeamSize = this.getTeamSize(complexity);
419
420
  const queryBudget = this.getQueryBudget(complexity);
420
- const complexityGuidance = this.getComplexityGuidance(complexity, maxTeamSize, queryBudget);
421
+ // Single-researcher mode: one agent carries all the queries, keeping one growing,
422
+ // fully-cached context (each turn re-reads the prior context as a cache hit). Override
423
+ // the team-size and complexity guidance so the plan is a single researcher with the
424
+ // full query budget, not a parallel team. Level 1 always runs a single researcher
425
+ // (the simple, fast lane); Level 2/3 follow the SINGLE_RESEARCHER flag.
426
+ const singleResearcher = effectiveSingleResearcher(complexity, config.SINGLE_RESEARCHER);
427
+ const teamSizeGuidance = singleResearcher
428
+ ? 'Plan **exactly ONE researcher** that covers the entire scope, carrying all the queries. Do NOT split the work across multiple researchers — one agent doing all the work keeps a single growing, fully-cached context.'
429
+ : `**Team size**: Plan between **1 and ${maxTeamSize} researchers**. A **single researcher is a complete, valid plan** — when the topic is focused or singular, assign just one. Add more only for genuinely distinct, non-overlapping angles; never split a narrow topic just to fill the team. (See the complexity guidance below for the default at this level.)`;
430
+ const complexityGuidance = singleResearcher
431
+ ? `**Complexity: ${complexity === 1 ? 'Level 1 (Normal)' : complexity === 2 ? 'Level 2 (Deep)' : 'Level 3 (Ultra)'}** — Plan ONE researcher with the full query budget (${queryBudget} queries) covering the entire scope. Do not split across researchers; the single agent reads every source in sequence.`
432
+ : this.getComplexityGuidance(complexity, maxTeamSize, queryBudget);
421
433
 
422
434
  // Inject steering if present
423
435
  let steeringSection = '';
@@ -435,6 +447,7 @@ export class PlanningService implements IPlanningService {
435
447
  root_query: query,
436
448
  additional_considerations: steeringSection,
437
449
  complexity_label: complexity === 1 ? 'Level 1 (Normal)' : complexity === 2 ? 'Level 2 (Deep)' : 'Level 3 (Ultra)',
450
+ team_size_guidance: teamSizeGuidance,
438
451
  max_team_size: maxTeamSize,
439
452
  query_budget: queryBudget,
440
453
  complexity_guidance: complexityGuidance,
@@ -502,11 +515,14 @@ export class PlanningService implements IPlanningService {
502
515
  signal,
503
516
  isTransientError: (err) => isRetriableLlmError(err, signal),
504
517
  delayFor: rateLimitDelayFor,
518
+ // Bound the TOTAL wait for THIS call: a provider that keeps asking for
519
+ // a long window must not spend the run's whole budget sleeping here.
520
+ maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS,
505
521
  },
506
522
  );
507
523
 
508
524
  // Track usage once, on the successful attempt (failed attempts throw before here).
509
- recordLlmUsage(model, (response as any).usage, { component: 'coordinator', complexity, observer });
525
+ recordLlmUsage(model, response.usage, { component: 'coordinator', complexity, observer });
510
526
 
511
527
  // Truncation is the #1 cause of a malformed plan: a response that hit the
512
528
  // output-token cap ends mid-JSON no matter how well it started. Log the cap
@@ -565,7 +581,7 @@ export class PlanningService implements IPlanningService {
565
581
  }
566
582
 
567
583
  // Final safety cap
568
- plan = this.capResearcherQueries(plan, complexity, this.name);
584
+ plan = this.capResearcherQueries(plan, complexity, this.name, singleResearcher);
569
585
  // The coordinator (round 1) MUST yield runnable researchers. If the model emitted empty or
570
586
  // absent query arrays, capResearcherQueries drops them all and force-synthesizes — but at
571
587
  // round 1 there are zero reports, so that is a silent no-op run ("no summary generated",
@@ -573,7 +589,7 @@ export class PlanningService implements IPlanningService {
573
589
  // empty plan slips through. Fall back to the single-researcher plan so the run investigates.
574
590
  if (!plan.researchers || plan.researchers.length === 0) {
575
591
  logger.warn('[PlanningService] Coordinator produced no runnable researchers (empty queries); using single-researcher fallback');
576
- plan = this.capResearcherQueries(this.buildFallbackCoordinatorPlan(responseText, query), complexity, this.name);
592
+ plan = this.capResearcherQueries(this.buildFallbackCoordinatorPlan(responseText, query), complexity, this.name, singleResearcher);
577
593
  }
578
594
  // Round 1 always delegates. `action` is optional in the parsed schema and the
579
595
  // coordinator prompt neither documents nor asks for one, so any value here is
@@ -612,7 +628,7 @@ export class PlanningService implements IPlanningService {
612
628
  }
613
629
  logger.warn('[PlanningService] Coordinator call failed transiently; building fallback plan so the run can proceed');
614
630
  let plan = this.buildFallbackCoordinatorPlan('', query);
615
- plan = this.capResearcherQueries(plan, complexity, this.name);
631
+ plan = this.capResearcherQueries(plan, complexity, this.name, singleResearcher);
616
632
  if (plan.action !== 'synthesize') {
617
633
  plan.action = 'delegate';
618
634
  }
@@ -653,7 +669,12 @@ export class PlanningService implements IPlanningService {
653
669
  const config = options.config ?? getConfig(options.cwd);
654
670
  const promptTemplate = loadPrompt(isRouter ? 'system-lead-router' : 'system-lead-synthesizer');
655
671
 
656
- const maxTeamSize = this.getTeamSize(complexity);
672
+ // Single-researcher mode: clamp the team size to 1 so the router plans ONE researcher
673
+ // per round (one growing, fully-cached context), not a parallel team. Level 1 always
674
+ // runs a single researcher (the simple, fast lane); Level 2/3 follow the
675
+ // SINGLE_RESEARCHER flag.
676
+ const singleResearcher = effectiveSingleResearcher(complexity, config.SINGLE_RESEARCHER);
677
+ const maxTeamSize = singleResearcher ? 1 : this.getTeamSize(complexity);
657
678
  const queryBudget = this.getQueryBudget(complexity);
658
679
  // Prefer the caller's live, steering-extended round budget (e.g. the
659
680
  // orchestrator's maxRounds, which grows past the base complexity-table
@@ -937,7 +958,7 @@ export class PlanningService implements IPlanningService {
937
958
 
938
959
  // Final safety cap if delegating
939
960
  if (finalPlan.action === 'delegate') {
940
- const capped = this.capResearcherQueries(finalPlan, complexity, this.name);
961
+ const capped = this.capResearcherQueries(finalPlan, complexity, this.name, singleResearcher);
941
962
  // Mirror generatePlan's empty-after-cap guard, adapted to mid-run: a
942
963
  // delegate whose researchers ALL had empty query arrays caps to zero and
943
964
  // comes back force-synthesized — indistinguishable to the orchestrator
@@ -952,6 +973,7 @@ export class PlanningService implements IPlanningService {
952
973
  { action: 'delegate', content: '', researchers: previousPlan.researchers },
953
974
  complexity,
954
975
  this.name,
976
+ singleResearcher,
955
977
  );
956
978
  if (fallback.researchers && fallback.researchers.length > 0) {
957
979
  logger.warn('[PlanningService] Evaluator delegated zero runnable researchers; continuing the prior agenda rather than synthesizing early');
@@ -1006,6 +1028,7 @@ export class PlanningService implements IPlanningService {
1006
1028
  { action: 'delegate', content: '', researchers: previousPlan.researchers },
1007
1029
  complexity,
1008
1030
  this.name,
1031
+ singleResearcher,
1009
1032
  );
1010
1033
  this.currentPlans.set(sessionId, fallback);
1011
1034
  return fallback;
@@ -1094,7 +1117,7 @@ export class PlanningService implements IPlanningService {
1094
1117
  * the caller.
1095
1118
  */
1096
1119
  private async callLead(args: {
1097
- model: Model<any>;
1120
+ model: Model<Api>;
1098
1121
  apiKey: string;
1099
1122
  headers?: Record<string, string | null>;
1100
1123
  signal?: AbortSignal;
@@ -1172,11 +1195,14 @@ export class PlanningService implements IPlanningService {
1172
1195
  signal,
1173
1196
  isTransientError: (err) => isRetriableLlmError(err, signal),
1174
1197
  delayFor: rateLimitDelayFor,
1198
+ // Bound the TOTAL wait for THIS call: a provider that keeps asking for
1199
+ // a long window must not spend the run's whole budget sleeping here.
1200
+ maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS,
1175
1201
  },
1176
1202
  );
1177
1203
 
1178
1204
  // Track usage once, on the successful attempt (failed attempts throw before here).
1179
- recordLlmUsage(model, (response as any).usage, { component: args.component, complexity, observer });
1205
+ recordLlmUsage(model, response.usage, { component: args.component, complexity, observer });
1180
1206
  return responseText;
1181
1207
  }
1182
1208
 
@@ -1191,7 +1217,7 @@ export class PlanningService implements IPlanningService {
1191
1217
  * partition plus a merge for that cliff.
1192
1218
  */
1193
1219
  private async synthesizeCorpus(args: {
1194
- model: Model<any>;
1220
+ model: Model<Api>;
1195
1221
  apiKey: string;
1196
1222
  headers?: Record<string, string | null>;
1197
1223
  signal?: AbortSignal;
@@ -30,6 +30,23 @@ export function getTeamSize(complexity: 1 | 2 | 3): number {
30
30
  : MAX_TEAM_SIZE_LEVEL_3;
31
31
  }
32
32
 
33
+ /**
34
+ * Resolve the effective single-researcher mode for a complexity level.
35
+ *
36
+ * Level 1 (Normal) always runs a single researcher — it is the simple, fast lane, and
37
+ * one focused researcher handles normal-complexity queries. This is structural, not a
38
+ * prompt nudge: the flag cannot turn it off. Level 2 and 3 follow the
39
+ * `SINGLE_RESEARCHER` config flag (default false → flexible delegation; true → one
40
+ * researcher carrying the full team budget).
41
+ *
42
+ * This is the single source of truth for "how many researchers": the coordinator
43
+ * guidance, the router clamp, and the query-cap all read this, so there is no second
44
+ * mechanism (no per-level prompt default) that can drift from it.
45
+ */
46
+ export function effectiveSingleResearcher(complexity: 1 | 2 | 3, singleResearcher: boolean): boolean {
47
+ return complexity === 1 ? true : singleResearcher;
48
+ }
49
+
33
50
  /**
34
51
  * Get the query budget per researcher for a complexity level
35
52
  */
@@ -53,7 +70,7 @@ export function getMaxRounds(complexity: 1 | 2 | 3): number {
53
70
  */
54
71
  export function getComplexityGuidance(complexity: 1 | 2 | 3, maxTeamSize: number, queryBudget: number): string {
55
72
  if (complexity === 1) {
56
- return '**Complexity: Level 1 (Normal)**. Conduct a thorough, well-rounded investigation of the topic covering the primary angles with adequate citations. **Plan ONLY Round 1** — a single comprehensive round. **Default to a single researcher** for most Level 1 topics — one focused researcher can handle the majority of normal-complexity queries efficiently. Use 2 researchers only when the topic clearly spans two distinct, non-overlapping domains that benefit from parallel investigation. This is a ONE-SHOT effort: plan Round 1 as if it is the only round, because it should be. Only Level 2 or Level 3 research should involve multiple rounds.';
73
+ return '**Complexity: Level 1 (Normal)**. Conduct a thorough, well-rounded investigation of the topic covering the primary angles with adequate citations. **Plan ONLY Round 1** — a single comprehensive round. **Use ONE researcher** — one focused researcher handles normal-complexity queries. This is a ONE-SHOT effort: plan Round 1 as if it is the only round, because it should be. Only Level 2 or Level 3 research should involve multiple rounds.';
57
74
  } else if (complexity === 2) {
58
75
  return `**Complexity: Level 2 (Deep)**. **ONLY for HIGH/EXTREME research needs.** Level 2 should be reserved for topics that clearly require deeper investigation than a single comprehensive round can provide. **Plan ONLY Round 1** — a thorough, well-structured first round. Subsequent rounds are reactive and only delegated when Round 1 findings reveal clear gaps that warrant deeper or broader coverage. Do not pre-plan multiple rounds; delegate follow-ups only when Round 1 demonstrates genuine need.
59
76
 
@@ -93,7 +110,7 @@ export function getEvaluatorComplexityGuidance(complexity: 1 | 2 | 3, researchRo
93
110
  - **SYNTHESIZE when**: The primary topic is covered from multiple angles with evidence from diverse sources and no significant gaps remain that would prevent a complete answer.
94
111
  - **DELEGATE when**: Coverage is incomplete, important angles are missing, or additional sources would meaningfully strengthen the findings.
95
112
 
96
- **DEFAULT PATH**: Synthesize after Round 1 if the researcher produced solid coverage of the core topic. **Level 1 should almost always be a single round** — only delegate a second round when Round 1 clearly missed important angles or lacks source diversity. A single researcher is the default for Level 1 follow-up rounds — only use 2 researchers if the remaining gaps clearly span two distinct domains. Level 2 research escalation should be reserved for truly high/extreme research needs only.`;
113
+ **DEFAULT PATH**: Synthesize after Round 1 if the researcher produced solid coverage of the core topic. **Level 1 should almost always be a single round** — only delegate a second round when Round 1 clearly missed important angles or lacks source diversity. **Use ONE researcher** for follow-up rounds. Level 2 research escalation should be reserved for truly high/extreme research needs only.`;
97
114
  } else if (complexity === 2) {
98
115
  return `**Level 2 (Deep)** - Thorough, multi-phase investigation with comprehensive citations.
99
116
 
@@ -206,7 +223,9 @@ export function parseJsonPlan(text: string): ResearchPlan {
206
223
  // 2. Validate against schema
207
224
  if (!Value.Check(ResearchPlanSchema, coerced)) {
208
225
  const errors = [...Value.Errors(ResearchPlanSchema, coerced)];
209
- const errorMsg = errors.map((e: any) => `${e.path}: ${e.message}`).join(', ');
226
+ // TLocalizedValidationError carries the failing property in `instancePath` (not
227
+ // `path`); the old `(e: any).path` read was always undefined, dropping the path.
228
+ const errorMsg = errors.map(e => `${e.instancePath || ''} ${e.message}`).join(', ');
210
229
  // If validation fails, we throw to satisfy tests and ensure system integrity
211
230
  throw new Error(`Plan validation failed: ${errorMsg}`);
212
231
  }
@@ -257,8 +276,13 @@ export function buildFallbackCoordinatorPlan(serviceName: string, _rawText: stri
257
276
  /**
258
277
  * Cap researcher queries to stay within budget
259
278
  */
260
- export function capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string): ResearchPlan {
261
- const budget = getQueryBudget(complexity);
279
+ export function capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string, singleResearcher = false): ResearchPlan {
280
+ // In single-researcher mode the lone researcher carries the whole team's query load, so
281
+ // its per-researcher cap is the full team budget (maxTeamSize × per-researcher), not the
282
+ // per-researcher figure a parallel team would each get. Default (false) keeps the
283
+ // per-researcher cap.
284
+ const perResearcher = getQueryBudget(complexity);
285
+ const budget = singleResearcher ? getTeamSize(complexity) * perResearcher : perResearcher;
262
286
 
263
287
  // Hard caps per round - based on actual maximum possible queries
264
288
  // Level 1: 2 researchers x 10 queries = 20 maximum
@@ -271,8 +295,10 @@ export function capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3,
271
295
  if (!plan.researchers) return plan;
272
296
 
273
297
  // 1. Normalize IDs to strings and cap individual researchers
274
- // CRITICAL: Only keep researchers with non-empty queries to guarantee search results
275
- const maxTeam = getTeamSize(complexity);
298
+ // CRITICAL: Only keep researchers with non-empty queries to guarantee search results.
299
+ // In single-researcher mode the team is ONE researcher (one growing, fully-cached
300
+ // context), so the count cap is 1, not the complexity table's team size.
301
+ const maxTeam = singleResearcher ? 1 : getTeamSize(complexity);
276
302
  plan.researchers = plan.researchers
277
303
  .filter(r => r && typeof r === 'object' && Array.isArray(r.queries) && r.queries.length > 0)
278
304
  .slice(0, maxTeam)
@@ -53,7 +53,7 @@ export function registerCoreServices(container: ServiceContainer = getServiceCon
53
53
  * @param ctx - Optional extension context to pass to services
54
54
  * @param container - Service container instance
55
55
  */
56
- export async function initializeCoreServices(ctx?: any, container: ServiceContainer = getServiceContainer()): Promise<{ success: boolean; initialized: string[]; failed: string[] }> {
56
+ export async function initializeCoreServices(ctx?: unknown, container: ServiceContainer = getServiceContainer()): Promise<{ success: boolean; initialized: string[]; failed: string[] }> {
57
57
  logger.log('[ServiceInitialization] Initializing core services...');
58
58
 
59
59
  const initialized: string[] = [];
@@ -54,7 +54,7 @@ export interface IService {
54
54
  /**
55
55
  * Initialize the service (called before first use)
56
56
  */
57
- initialize?(ctx?: any): Promise<void> | void;
57
+ initialize?(ctx?: unknown): Promise<void> | void;
58
58
 
59
59
  /**
60
60
  * Dispose the service (called during shutdown)
@@ -111,7 +111,7 @@ const initializationContext = new AsyncLocalStorage<string>();
111
111
  * Centralized service container for dependency injection
112
112
  */
113
113
  export class ServiceContainer {
114
- private services: Map<string, ServiceRegistration<any>> = new Map();
114
+ private services: Map<string, ServiceRegistration<IService>> = new Map();
115
115
  private dependencies: Map<string, Set<string>> = new Map();
116
116
  public isDisposing: boolean = false;
117
117
  // The single in-flight disposeAll() run. Only reset() JOINS it (awaiting teardown
@@ -120,7 +120,7 @@ export class ServiceContainer {
120
120
  private _disposalPromise: Promise<void> | null = null;
121
121
  public isReady: boolean = false;
122
122
  public cwd: string = process.cwd();
123
- public config: any = null;
123
+ public config: unknown = null;
124
124
  private readonly defaultOptions: Required<ServiceContainerOptions>;
125
125
 
126
126
  constructor(options: ServiceContainerOptions = {}) {
@@ -225,7 +225,7 @@ export class ServiceContainer {
225
225
  /**
226
226
  * Get a service instance, initializing it if necessary
227
227
  */
228
- async get<T extends IService>(name: string, ctx?: any): Promise<T> {
228
+ async get<T extends IService>(name: string, ctx?: unknown): Promise<T> {
229
229
  if (this.isDisposing) {
230
230
  throw new Error(`Cannot get service '${name}' during container disposal`);
231
231
  }
@@ -419,7 +419,10 @@ export class ServiceContainer {
419
419
  }
420
420
 
421
421
  if (registration.instance && registration.instance.dispose) {
422
- await registration.instance.dispose().catch((err: unknown) => {
422
+ // dispose() may return a bare void (non-async implementation) — normalize to a
423
+ // promise so the catch handler always applies.
424
+ const disposal = Promise.resolve(registration.instance.dispose());
425
+ await disposal.catch((err: unknown) => {
423
426
  logger.warn(`[ServiceContainer] Error disposing service '${name}':`, err);
424
427
  });
425
428
  }
@@ -462,7 +465,10 @@ export class ServiceContainer {
462
465
 
463
466
  // Dispose old instance if present
464
467
  if (registration.instance && registration.instance.dispose) {
465
- await registration.instance.dispose().catch((err: unknown) => {
468
+ // dispose() may return a bare void (non-async implementation) — normalize to a
469
+ // promise so the catch handler always applies.
470
+ const disposal = Promise.resolve(registration.instance.dispose());
471
+ await disposal.catch((err: unknown) => {
466
472
  logger.warn(`[ServiceContainer] Error disposing old service '${name}':`, err);
467
473
  });
468
474
  }
@@ -731,7 +737,7 @@ export class ServiceContainer {
731
737
  */
732
738
  private async _initializeService<T extends IService>(
733
739
  registration: ServiceRegistration<T>,
734
- ctx?: any
740
+ ctx?: unknown
735
741
  ): Promise<T> {
736
742
  let instance: T | null = null;
737
743
  try {
@@ -831,7 +837,7 @@ export function replaceService<T extends IService>(
831
837
  /**
832
838
  * Convenience function to get a service
833
839
  */
834
- export function getService<T extends IService>(name: string, ctx?: any, container: ServiceContainer = globalServiceContainer): Promise<T> {
840
+ export function getService<T extends IService>(name: string, ctx?: unknown, container: ServiceContainer = globalServiceContainer): Promise<T> {
835
841
  return container.get<T>(name, ctx);
836
842
  }
837
843
 
@@ -866,9 +872,10 @@ export function isServiceInitialized(name: string, container: ServiceContainer =
866
872
  /**
867
873
  * Helper to extract a service container from a context object, if present.
868
874
  */
869
- export function tryGetServiceContainerFromCtx(ctx: any): ServiceContainer {
870
- if (ctx?.container && typeof ctx.container.get === 'function' && typeof ctx.container.register === 'function') {
871
- return ctx.container;
875
+ export function tryGetServiceContainerFromCtx(ctx: unknown): ServiceContainer {
876
+ const container = (ctx as { container?: { get?: unknown; register?: unknown } } | undefined)?.container;
877
+ if (container && typeof container.get === 'function' && typeof container.register === 'function') {
878
+ return container as unknown as ServiceContainer;
872
879
  }
873
880
  return globalServiceContainer;
874
881
  }