@lincoln504/pi-research 1.7.24 → 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 (93) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +276 -171
  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 +49 -0
  9. package/docs/CONFIGURATION.md +1 -0
  10. package/package.json +9 -9
  11. package/src/cli.ts +32 -14
  12. package/src/config.ts +20 -7
  13. package/src/core/interfaces/health-check-interfaces.ts +23 -2
  14. package/src/core/interfaces/knowledge-interfaces.ts +7 -4
  15. package/src/core/interfaces/observer-interfaces.ts +1 -1
  16. package/src/core/interfaces/orchestration-interfaces.ts +17 -12
  17. package/src/core/interfaces/planning-interfaces.ts +5 -5
  18. package/src/core/interfaces/process-interfaces.ts +2 -2
  19. package/src/core/interfaces/state-manager-interfaces.ts +6 -5
  20. package/src/core/llm/agentic-repair.ts +6 -6
  21. package/src/core/llm/llm-utils.ts +7 -4
  22. package/src/core/llm/model-registry-factory.ts +11 -11
  23. package/src/core/llm/research-model-resolver.ts +11 -11
  24. package/src/core/pi-version.ts +10 -1
  25. package/src/core/planning-service.ts +33 -13
  26. package/src/core/planning-utils.ts +33 -7
  27. package/src/core/service-initialization.ts +1 -1
  28. package/src/core/service-registry.ts +18 -11
  29. package/src/healthcheck/index.ts +5 -4
  30. package/src/healthcheck/registry.ts +5 -18
  31. package/src/index.ts +12 -16
  32. package/src/infrastructure/browser/browser-client.ts +4 -4
  33. package/src/infrastructure/browser/browser-error-utils.ts +6 -1
  34. package/src/infrastructure/browser/browser-lifecycle.ts +8 -3
  35. package/src/infrastructure/browser/browser-server.ts +3 -3
  36. package/src/infrastructure/browser/browser-task-scheduler.ts +13 -9
  37. package/src/infrastructure/browser/priority-task-queue.ts +13 -10
  38. package/src/infrastructure/browser/thread-worker-browser.ts +14 -11
  39. package/src/infrastructure/browser/thread-worker-lifecycle.ts +21 -15
  40. package/src/infrastructure/browser/thread-worker-messaging.ts +39 -31
  41. package/src/infrastructure/browser/thread-worker-types.ts +3 -1
  42. package/src/infrastructure/browser/thread-worker.mjs +22 -9
  43. package/src/infrastructure/browser/thread-worker.ts +3 -2
  44. package/src/infrastructure/browser/worker-pool-manager.ts +5 -5
  45. package/src/infrastructure/gpu-resource-service.ts +16 -9
  46. package/src/infrastructure/knowledge-store-service.ts +13 -10
  47. package/src/infrastructure/scheduler-factory-service.ts +4 -3
  48. package/src/infrastructure/service-initialization.ts +1 -1
  49. package/src/infrastructure/state/state-manager-service.ts +2 -2
  50. package/src/infrastructure/state/state-manager.ts +3 -3
  51. package/src/infrastructure/state/state-validator.ts +9 -3
  52. package/src/infrastructure/types/state-types.ts +12 -91
  53. package/src/knowledge/embedder-init.ts +8 -8
  54. package/src/knowledge/embedder-utils.ts +7 -3
  55. package/src/knowledge/embedder.ts +14 -10
  56. package/src/knowledge/onnx-env.ts +2 -2
  57. package/src/knowledge/store.ts +12 -11
  58. package/src/logger.ts +1 -1
  59. package/src/orchestration/deep-research-orchestrator.ts +15 -7
  60. package/src/orchestration/headless-observer.ts +1 -1
  61. package/src/orchestration/orchestration-types.ts +2 -2
  62. package/src/orchestration/quick-research-orchestrator.ts +4 -4
  63. package/src/orchestration/research-orchestration-service.ts +13 -13
  64. package/src/orchestration/research-synthesis-service.ts +15 -8
  65. package/src/orchestration/researcher-executor.ts +23 -7
  66. package/src/orchestration/researcher.ts +19 -7
  67. package/src/orchestration/service-initialization.ts +1 -1
  68. package/src/prompts/research-tool-usage.md +4 -5
  69. package/src/prompts/researcher.md +6 -36
  70. package/src/prompts/system-coordinator.md +1 -1
  71. package/src/prompts/system-lead-synthesizer.md +5 -5
  72. package/src/research-config.ts +11 -9
  73. package/src/sdk.ts +10 -10
  74. package/src/skill-install/skill-installer.ts +19 -10
  75. package/src/tools/grep.ts +57 -5
  76. package/src/tools/index.ts +0 -3
  77. package/src/tools/read-guard.ts +12 -0
  78. package/src/tools/research-knowledge-search.ts +15 -13
  79. package/src/tools/research-tool-definition.ts +15 -10
  80. package/src/tools/scrape.ts +3 -2
  81. package/src/tui/research-panel.ts +1 -1
  82. package/src/types/extension-context.ts +2 -2
  83. package/src/types/llm.ts +8 -7
  84. package/src/types/research-panel-types.ts +3 -1
  85. package/src/types/state-types.ts +98 -0
  86. package/src/utils/coverage-digest.ts +27 -6
  87. package/src/utils/llm-usage.ts +3 -3
  88. package/src/utils/safe-unref.ts +2 -2
  89. package/src/utils/shutdown-manager.ts +6 -6
  90. package/src/utils/stdio-capture.ts +25 -10
  91. package/src/utils/text-utils.ts +35 -0
  92. package/src/web-research/scraper-utils.ts +9 -3
  93. package/src/web-research/web-scraper.ts +25 -10
@@ -8,7 +8,7 @@ import type { ResearchPlan, ResearcherConfig } from './planning-interfaces.ts';
8
8
  import type { QueryResultWithError } from '../../web-research/types.ts';
9
9
  import type { StoreUrlEntry } from './knowledge-interfaces.ts';
10
10
 
11
- import type { Model } from '@earendil-works/pi-ai';
11
+ import type { Api, Model } from '@earendil-works/pi-ai';
12
12
  import type { ExtensionContext, AgentToolResult } from '@earendil-works/pi-coding-agent';
13
13
  import type { ResearchObserver, HeadlessObserverOptions } from './observer-interfaces.ts';
14
14
  import type { SteeringMessage } from './steering-interfaces.ts';
@@ -21,9 +21,9 @@ export interface ResearchOptions {
21
21
  query: string;
22
22
  depth?: 0 | 1 | 2 | 3;
23
23
  complexity?: 1 | 2 | 3;
24
- model?: Model<any>;
24
+ model?: Model<Api>;
25
25
  observer?: ResearchObserver | HeadlessObserverOptions;
26
- onUpdate?: (update: AgentToolResult<any>) => void;
26
+ onUpdate?: (update: AgentToolResult<unknown>) => void;
27
27
  sessionId: string;
28
28
  researchId: string;
29
29
  config?: Config;
@@ -44,7 +44,7 @@ export interface RunResearchersOptions {
44
44
  complexity: 1 | 2 | 3;
45
45
  excludeTools?: string[];
46
46
  ctx: ExtensionContext;
47
- model: Model<any>;
47
+ model: Model<Api>;
48
48
  config?: Config;
49
49
  observer?: ResearchObserver;
50
50
  initialLinks?: string[];
@@ -57,7 +57,12 @@ export interface RunResearchersOptions {
57
57
  * Research Synthesis Service Interface
58
58
  */
59
59
  export interface IResearchSynthesisService extends IService {
60
- storeReport(researchId: string, researcherId: string, report: string): void;
60
+ /**
61
+ * Store a researcher report. `digest` is the researcher's coverage digest, passed
62
+ * explicitly in the raw-scrape flow where the "report" is the raw tool results (which
63
+ * carry no embedded digest). When omitted, the digest is split off the report head.
64
+ */
65
+ storeReport(researchId: string, researcherId: string, report: string, digest?: string): void;
61
66
  getAllReports(researchId: string): Map<string, string>;
62
67
  /** Coverage digest per stored report, derived when a researcher emitted none. */
63
68
  getAllDigests(researchId: string): Map<string, string>;
@@ -76,13 +81,13 @@ export interface IResearchSynthesisService extends IService {
76
81
  * Research Orchestration Service Interface
77
82
  */
78
83
  export interface IResearchOrchestration extends IService {
79
- resolveResearchModel(options: ResearchOptions): Promise<Model<any>>;
84
+ resolveResearchModel(options: ResearchOptions): Promise<Model<Api>>;
80
85
  runResearch(options: ResearchOptions, signal?: AbortSignal): Promise<string>;
81
- cleanupResearchServices(sessionId?: string, researchId?: string, ctx?: any, config?: Config, opts?: { skipStoreMaintenance?: boolean }): Promise<void>;
82
- distributeSearchResults(plan: ResearchPlan, results: QueryResultWithError[], ctx?: any): Promise<Map<string, string[]>>;
83
- runResearchers(options: RunResearchersOptions, researcherLinks?: Map<string, string[]>, storeLinks?: Map<string, StoreUrlEntry[]>, ctx?: any): Promise<void>;
84
- runSearchBurst(queries: string[], config: Config, signal?: AbortSignal, onProgress?: (links: number) => void, ctx?: any): Promise<QueryResultWithError[]>;
85
- storeLinkDescriptions(sessionId: string, round: number, researchId: string, config: Config, ctx?: any): Promise<void>;
86
+ cleanupResearchServices(sessionId?: string, researchId?: string, ctx?: unknown, config?: Config, opts?: { skipStoreMaintenance?: boolean }): Promise<void>;
87
+ distributeSearchResults(plan: ResearchPlan, results: QueryResultWithError[], ctx?: unknown): Promise<Map<string, string[]>>;
88
+ runResearchers(options: RunResearchersOptions, researcherLinks?: Map<string, string[]>, storeLinks?: Map<string, StoreUrlEntry[]>, ctx?: unknown): Promise<void>;
89
+ runSearchBurst(queries: string[], config: Config, signal?: AbortSignal, onProgress?: (links: number) => void, ctx?: unknown): Promise<QueryResultWithError[]>;
90
+ storeLinkDescriptions(sessionId: string, round: number, researchId: string, config: Config, ctx?: unknown): Promise<void>;
86
91
  // Advisory only — logs infrastructure health; research never aborts on the result.
87
- checkHealth(round: number, researchId?: string, ctx?: any, signal?: AbortSignal): Promise<void>;
92
+ checkHealth(round: number, researchId?: string, ctx?: unknown, signal?: AbortSignal): Promise<void>;
88
93
  }
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { IService } from '../service-registry.ts';
6
- import type { Model } from '@earendil-works/pi-ai';
6
+ import type { Api, Model } from '@earendil-works/pi-ai';
7
7
  import type { ModelRegistry } from '@earendil-works/pi-coding-agent';
8
8
  import type { ResearchObserver } from './observer-interfaces.ts';
9
9
  import type { ResearchPlan, ResearcherConfig } from './research-plan-types.ts';
@@ -27,7 +27,7 @@ export interface GeneratePlanOptions {
27
27
  sessionId: string;
28
28
  query: string;
29
29
  complexity: 1 | 2 | 3;
30
- model: Model<any>;
30
+ model: Model<Api>;
31
31
  modelRegistry: ModelRegistry;
32
32
  cwd: string;
33
33
  signal?: AbortSignal;
@@ -46,7 +46,7 @@ export interface GenerateQueriesOptions {
46
46
  researcher: ResearcherConfig;
47
47
  query: string;
48
48
  complexity: 1 | 2 | 3;
49
- model: Model<any>;
49
+ model: Model<Api>;
50
50
  signal?: AbortSignal;
51
51
  }
52
52
 
@@ -65,7 +65,7 @@ export interface UpdatePlanOptions {
65
65
  round: number;
66
66
  query: string;
67
67
  complexity: 1 | 2 | 3;
68
- model: Model<any>;
68
+ model: Model<Api>;
69
69
  modelRegistry: ModelRegistry;
70
70
  cwd: string;
71
71
  signal?: AbortSignal;
@@ -106,7 +106,7 @@ export interface IPlanningService extends IService {
106
106
  getComplexityGuidance(complexity: 1 | 2 | 3, maxTeamSize: number, queryBudget: number): string;
107
107
  getEvaluatorComplexityGuidance(complexity: 1 | 2 | 3, researchRounds: number): string;
108
108
  getRoundPhaseGuidance(currentRound: number, maxRounds: number, complexity: 1 | 2 | 3, maxTeamSize: number): string;
109
- capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string): ResearchPlan;
109
+ capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string, singleResearcher?: boolean): ResearchPlan;
110
110
  parseJsonPlan(text: string): ResearchPlan;
111
111
  buildFallbackCoordinatorPlan(rawText: string, query: string): ResearchPlan;
112
112
  clearPlanningState(sessionId?: string): void;
@@ -32,6 +32,6 @@ export interface IProcessLifecycle extends IService {
32
32
  * GPU Resource Service Interface
33
33
  */
34
34
  export interface IGPUResourceService extends IService {
35
- acquireGpuLock(sessionId?: string, timeoutMs?: number, ctx?: any): Promise<boolean>;
36
- releaseGpuLock(pid?: number, ctx?: any): Promise<void>;
35
+ acquireGpuLock(sessionId?: string, timeoutMs?: number, ctx?: unknown): Promise<boolean>;
36
+ releaseGpuLock(pid?: number, ctx?: unknown): Promise<void>;
37
37
  }
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { IService } from '../service-registry.ts';
6
+ import type { SingletonState, StateMetrics } from '../../types/state-types.ts';
6
7
 
7
8
  /**
8
9
  * State manager service interface
@@ -16,9 +17,9 @@ export interface IStateManager extends IService {
16
17
  * implement it; callers use `isReadOnly?.()` (absent ⇒ not read-only).
17
18
  */
18
19
  isReadOnly?(): boolean;
19
- readState(): Promise<any>;
20
- writeState(state: any): Promise<void>;
21
- updateState(updater: (state: any) => any | Promise<any>): Promise<void>;
20
+ readState(): Promise<SingletonState>;
21
+ writeState(state: SingletonState): Promise<void>;
22
+ updateState(updater: (state: SingletonState) => SingletonState | Promise<SingletonState>): Promise<void>;
22
23
  addSession(sessionId: string, param: number | string): Promise<void>;
23
24
  removeSession(sessionId: string): Promise<void>;
24
25
  updateHeartbeat(sessionId: string): Promise<void>;
@@ -38,7 +39,7 @@ export interface IStateManager extends IService {
38
39
  isPidAlive(pid: number, expectedSchedulerId?: string, skipLock?: boolean): Promise<boolean>;
39
40
  acquireGpuLock(sessionId?: string, timeoutMs?: number): Promise<boolean>;
40
41
  releaseGpuLock(pid?: number): Promise<void>;
41
- getGpuOwner(): Promise<any | null>;
42
- getMetrics(): Promise<any>;
42
+ getGpuOwner(): Promise<NonNullable<SingletonState['gpuOwner']> | null>;
43
+ getMetrics(): Promise<StateMetrics>;
43
44
  cleanup(): Promise<void>;
44
45
  }
@@ -14,7 +14,7 @@
14
14
  * catch below for why a timeout is not retried where a validation failure is).
15
15
  */
16
16
 
17
- import type { Model, AssistantMessage, SimpleStreamOptions, ModelThinkingLevel } from '@earendil-works/pi-ai';
17
+ import type { Api, Model, AssistantMessage, Message, SimpleStreamOptions, ModelThinkingLevel } from '@earendil-works/pi-ai';
18
18
  import { logger } from '../../logger.ts';
19
19
  import { extractJson } from '../../utils/json-utils.ts';
20
20
  import { withTimeout, getLlmTimeoutMs } from './llm-timeout.ts';
@@ -28,7 +28,7 @@ import { Value } from 'typebox/value';
28
28
  */
29
29
  export interface JsonRepairOptions {
30
30
  /** The model to use for the repair pass */
31
- model: Model<any>;
31
+ model: Model<Api>;
32
32
  /** Original user prompt or context for the repair */
33
33
  context?: string;
34
34
  /** Optional schema for validation after repair */
@@ -65,8 +65,8 @@ export interface JsonRepairOptions {
65
65
  * LLM completion function compatible with `completeSimple` (see ./pi-ai-completion.ts).
66
66
  */
67
67
  export type LlmCompleter = (
68
- model: Model<any>,
69
- context: { systemPrompt?: string; messages: any[] },
68
+ model: Model<Api>,
69
+ context: { systemPrompt?: string; messages: Message[] },
70
70
  options?: SimpleStreamOptions
71
71
  ) => Promise<AssistantMessage>;
72
72
 
@@ -79,7 +79,7 @@ export type LlmCompleter = (
79
79
  * @param options - Repair options
80
80
  * @returns Salvaged object or null if repair fails
81
81
  */
82
- export async function repairJsonWithLlm<T = any>(
82
+ export async function repairJsonWithLlm<T = unknown>(
83
83
  text: string,
84
84
  completer: LlmCompleter,
85
85
  // headers values are string | null to match pi-ai's ProviderHeaders — a null
@@ -185,7 +185,7 @@ Return ONLY the valid JSON object. No prose before or after.`;
185
185
  const coerced = Value.Convert(schema, salvaged);
186
186
  if (!Value.Check(schema, coerced)) {
187
187
  const errors = [...Value.Errors(schema, coerced)];
188
- const errorDetail = errors.map((e: any) => `${e.path}: ${e.message}`).join(', ');
188
+ const errorDetail = errors.map((e: { path?: unknown; message?: string }) => `${e.path}: ${e.message}`).join(', ');
189
189
  logger.warn(`[${serviceName}] Salvage attempt ${attempt} succeeded but validation failed: ${errorDetail}. Salvaged: ${JSON.stringify(salvaged)}, Coerced: ${JSON.stringify(coerced)}`);
190
190
 
191
191
  if (attempt < maxAttempts) {
@@ -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
 
@@ -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,
@@ -509,7 +522,7 @@ export class PlanningService implements IPlanningService {
509
522
  );
510
523
 
511
524
  // Track usage once, on the successful attempt (failed attempts throw before here).
512
- recordLlmUsage(model, (response as any).usage, { component: 'coordinator', complexity, observer });
525
+ recordLlmUsage(model, response.usage, { component: 'coordinator', complexity, observer });
513
526
 
514
527
  // Truncation is the #1 cause of a malformed plan: a response that hit the
515
528
  // output-token cap ends mid-JSON no matter how well it started. Log the cap
@@ -568,7 +581,7 @@ export class PlanningService implements IPlanningService {
568
581
  }
569
582
 
570
583
  // Final safety cap
571
- plan = this.capResearcherQueries(plan, complexity, this.name);
584
+ plan = this.capResearcherQueries(plan, complexity, this.name, singleResearcher);
572
585
  // The coordinator (round 1) MUST yield runnable researchers. If the model emitted empty or
573
586
  // absent query arrays, capResearcherQueries drops them all and force-synthesizes — but at
574
587
  // round 1 there are zero reports, so that is a silent no-op run ("no summary generated",
@@ -576,7 +589,7 @@ export class PlanningService implements IPlanningService {
576
589
  // empty plan slips through. Fall back to the single-researcher plan so the run investigates.
577
590
  if (!plan.researchers || plan.researchers.length === 0) {
578
591
  logger.warn('[PlanningService] Coordinator produced no runnable researchers (empty queries); using single-researcher fallback');
579
- plan = this.capResearcherQueries(this.buildFallbackCoordinatorPlan(responseText, query), complexity, this.name);
592
+ plan = this.capResearcherQueries(this.buildFallbackCoordinatorPlan(responseText, query), complexity, this.name, singleResearcher);
580
593
  }
581
594
  // Round 1 always delegates. `action` is optional in the parsed schema and the
582
595
  // coordinator prompt neither documents nor asks for one, so any value here is
@@ -615,7 +628,7 @@ export class PlanningService implements IPlanningService {
615
628
  }
616
629
  logger.warn('[PlanningService] Coordinator call failed transiently; building fallback plan so the run can proceed');
617
630
  let plan = this.buildFallbackCoordinatorPlan('', query);
618
- plan = this.capResearcherQueries(plan, complexity, this.name);
631
+ plan = this.capResearcherQueries(plan, complexity, this.name, singleResearcher);
619
632
  if (plan.action !== 'synthesize') {
620
633
  plan.action = 'delegate';
621
634
  }
@@ -656,7 +669,12 @@ export class PlanningService implements IPlanningService {
656
669
  const config = options.config ?? getConfig(options.cwd);
657
670
  const promptTemplate = loadPrompt(isRouter ? 'system-lead-router' : 'system-lead-synthesizer');
658
671
 
659
- 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);
660
678
  const queryBudget = this.getQueryBudget(complexity);
661
679
  // Prefer the caller's live, steering-extended round budget (e.g. the
662
680
  // orchestrator's maxRounds, which grows past the base complexity-table
@@ -940,7 +958,7 @@ export class PlanningService implements IPlanningService {
940
958
 
941
959
  // Final safety cap if delegating
942
960
  if (finalPlan.action === 'delegate') {
943
- const capped = this.capResearcherQueries(finalPlan, complexity, this.name);
961
+ const capped = this.capResearcherQueries(finalPlan, complexity, this.name, singleResearcher);
944
962
  // Mirror generatePlan's empty-after-cap guard, adapted to mid-run: a
945
963
  // delegate whose researchers ALL had empty query arrays caps to zero and
946
964
  // comes back force-synthesized — indistinguishable to the orchestrator
@@ -955,6 +973,7 @@ export class PlanningService implements IPlanningService {
955
973
  { action: 'delegate', content: '', researchers: previousPlan.researchers },
956
974
  complexity,
957
975
  this.name,
976
+ singleResearcher,
958
977
  );
959
978
  if (fallback.researchers && fallback.researchers.length > 0) {
960
979
  logger.warn('[PlanningService] Evaluator delegated zero runnable researchers; continuing the prior agenda rather than synthesizing early');
@@ -1009,6 +1028,7 @@ export class PlanningService implements IPlanningService {
1009
1028
  { action: 'delegate', content: '', researchers: previousPlan.researchers },
1010
1029
  complexity,
1011
1030
  this.name,
1031
+ singleResearcher,
1012
1032
  );
1013
1033
  this.currentPlans.set(sessionId, fallback);
1014
1034
  return fallback;
@@ -1097,7 +1117,7 @@ export class PlanningService implements IPlanningService {
1097
1117
  * the caller.
1098
1118
  */
1099
1119
  private async callLead(args: {
1100
- model: Model<any>;
1120
+ model: Model<Api>;
1101
1121
  apiKey: string;
1102
1122
  headers?: Record<string, string | null>;
1103
1123
  signal?: AbortSignal;
@@ -1182,7 +1202,7 @@ export class PlanningService implements IPlanningService {
1182
1202
  );
1183
1203
 
1184
1204
  // Track usage once, on the successful attempt (failed attempts throw before here).
1185
- recordLlmUsage(model, (response as any).usage, { component: args.component, complexity, observer });
1205
+ recordLlmUsage(model, response.usage, { component: args.component, complexity, observer });
1186
1206
  return responseText;
1187
1207
  }
1188
1208
 
@@ -1197,7 +1217,7 @@ export class PlanningService implements IPlanningService {
1197
1217
  * partition plus a merge for that cliff.
1198
1218
  */
1199
1219
  private async synthesizeCorpus(args: {
1200
- model: Model<any>;
1220
+ model: Model<Api>;
1201
1221
  apiKey: string;
1202
1222
  headers?: Record<string, string | null>;
1203
1223
  signal?: AbortSignal;