@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.
- package/agent-skill/pi-research/SKILL.md +1 -1
- package/dist/cli.mjs +621 -205
- package/dist/prompts/research-tool-usage.md +4 -5
- package/dist/prompts/researcher.md +6 -36
- package/dist/prompts/system-coordinator.md +1 -1
- package/dist/prompts/system-lead-synthesizer.md +5 -5
- package/dist/thread-worker.mjs +22 -9
- package/docs/CHANGELOG.md +159 -0
- package/docs/CONFIGURATION.md +4 -3
- package/docs/TROUBLESHOOTING.md +92 -0
- package/package.json +9 -9
- package/scripts/ddg-socks-proxy.mjs +105 -15
- package/src/cli.ts +32 -14
- package/src/config.ts +20 -7
- package/src/core/interfaces/health-check-interfaces.ts +23 -2
- package/src/core/interfaces/knowledge-interfaces.ts +7 -4
- package/src/core/interfaces/observer-interfaces.ts +1 -1
- package/src/core/interfaces/orchestration-interfaces.ts +17 -12
- package/src/core/interfaces/planning-interfaces.ts +5 -5
- package/src/core/interfaces/process-interfaces.ts +2 -2
- package/src/core/interfaces/state-manager-interfaces.ts +6 -5
- package/src/core/llm/agentic-repair.ts +6 -6
- package/src/core/llm/llm-utils.ts +7 -4
- package/src/core/llm/model-registry-factory.ts +11 -11
- package/src/core/llm/research-model-resolver.ts +11 -11
- package/src/core/pi-version.ts +10 -1
- package/src/core/planning-service.ts +40 -14
- package/src/core/planning-utils.ts +33 -7
- package/src/core/service-initialization.ts +1 -1
- package/src/core/service-registry.ts +18 -11
- package/src/healthcheck/index.ts +67 -5
- package/src/healthcheck/registry.ts +5 -18
- package/src/index.ts +12 -16
- package/src/infrastructure/browser/browser-client.ts +4 -4
- package/src/infrastructure/browser/browser-error-utils.ts +6 -1
- package/src/infrastructure/browser/browser-lifecycle.ts +8 -3
- package/src/infrastructure/browser/browser-server.ts +3 -3
- package/src/infrastructure/browser/browser-task-scheduler.ts +13 -9
- package/src/infrastructure/browser/priority-task-queue.ts +13 -10
- package/src/infrastructure/browser/proxy-health.ts +342 -0
- package/src/infrastructure/browser/thread-worker-browser.ts +14 -11
- package/src/infrastructure/browser/thread-worker-lifecycle.ts +21 -15
- package/src/infrastructure/browser/thread-worker-messaging.ts +39 -31
- package/src/infrastructure/browser/thread-worker-types.ts +3 -1
- package/src/infrastructure/browser/thread-worker.mjs +22 -9
- package/src/infrastructure/browser/thread-worker.ts +3 -2
- package/src/infrastructure/browser/worker-pool-manager.ts +5 -5
- package/src/infrastructure/gpu-resource-service.ts +16 -9
- package/src/infrastructure/knowledge-store-service.ts +13 -10
- package/src/infrastructure/scheduler-factory-service.ts +4 -3
- package/src/infrastructure/service-initialization.ts +1 -1
- package/src/infrastructure/state/state-manager-service.ts +2 -2
- package/src/infrastructure/state/state-manager.ts +3 -3
- package/src/infrastructure/state/state-validator.ts +9 -3
- package/src/infrastructure/types/state-types.ts +12 -91
- package/src/knowledge/embedder-init.ts +8 -8
- package/src/knowledge/embedder-utils.ts +7 -3
- package/src/knowledge/embedder.ts +14 -10
- package/src/knowledge/onnx-env.ts +2 -2
- package/src/knowledge/store.ts +12 -11
- package/src/logger.ts +1 -1
- package/src/orchestration/deep-research-orchestrator.ts +36 -7
- package/src/orchestration/headless-observer.ts +1 -1
- package/src/orchestration/orchestration-types.ts +2 -2
- package/src/orchestration/quick-research-orchestrator.ts +4 -4
- package/src/orchestration/research-orchestration-service.ts +13 -13
- package/src/orchestration/research-synthesis-service.ts +15 -8
- package/src/orchestration/researcher-executor.ts +51 -8
- package/src/orchestration/researcher.ts +19 -7
- package/src/orchestration/service-initialization.ts +1 -1
- package/src/prompts/research-tool-usage.md +4 -5
- package/src/prompts/researcher.md +6 -36
- package/src/prompts/system-coordinator.md +1 -1
- package/src/prompts/system-lead-synthesizer.md +5 -5
- package/src/research-config.ts +11 -9
- package/src/sdk.ts +10 -10
- package/src/skill-install/skill-installer.ts +19 -10
- package/src/tools/grep.ts +57 -5
- package/src/tools/index.ts +0 -3
- package/src/tools/read-guard.ts +12 -0
- package/src/tools/research-knowledge-search.ts +15 -13
- package/src/tools/research-tool-definition.ts +15 -10
- package/src/tools/scrape.ts +3 -2
- package/src/tui/research-panel.ts +1 -1
- package/src/types/extension-context.ts +2 -2
- package/src/types/llm.ts +8 -7
- package/src/types/research-panel-types.ts +3 -1
- package/src/types/state-types.ts +98 -0
- package/src/utils/coverage-digest.ts +27 -6
- package/src/utils/llm-usage.ts +3 -3
- package/src/utils/provider-errors.ts +61 -9
- package/src/utils/safe-unref.ts +2 -2
- package/src/utils/shutdown-manager.ts +6 -6
- package/src/utils/stdio-capture.ts +25 -10
- package/src/utils/text-utils.ts +35 -0
- package/src/web-research/browser-search.ts +13 -1
- package/src/web-research/retry-utils.ts +29 -1
- package/src/web-research/scraper-utils.ts +9 -3
- package/src/web-research/web-scraper.ts +25 -10
package/src/tools/grep.ts
CHANGED
|
@@ -1,15 +1,44 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Grep Tool
|
|
3
3
|
*
|
|
4
|
-
* Thin wrapper around the SDK's built-in grep tool that adds
|
|
5
|
-
*
|
|
4
|
+
* Thin wrapper around the SDK's built-in grep tool that adds ToolUsageTracker
|
|
5
|
+
* budget enforcement AND confines the search to the project directory.
|
|
6
|
+
*
|
|
7
|
+
* The SDK's grep runs `rg` as a child process that reads files directly (the
|
|
8
|
+
* matched line for a zero-context match comes from `rg`'s JSON, not from the
|
|
9
|
+
* pluggable `readFile`), so `GrepOperations` cannot confine it. The exfil
|
|
10
|
+
* surface is therefore the search path: a researcher whose `scrape` can reach
|
|
11
|
+
* a public attacker URL could be talked into `grep`ing a secret and carrying
|
|
12
|
+
* it out. This wrapper confines the search path to the project (symlinks
|
|
13
|
+
* resolved, credential dirs/files refused, same policy as the read guard) and
|
|
14
|
+
* filters any secret-file match out of the result so it never reaches the LLM.
|
|
6
15
|
*/
|
|
7
16
|
|
|
8
|
-
import { createGrepToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
17
|
+
import { createGrepToolDefinition, type GrepToolInput } from '@earendil-works/pi-coding-agent';
|
|
9
18
|
import { Value } from 'typebox/value';
|
|
10
19
|
import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
20
|
+
import { resolve as resolvePath, isAbsolute } from 'node:path';
|
|
11
21
|
import type { ToolUsageTracker } from '../utils/tool-usage-tracker.ts';
|
|
12
22
|
import { MAX_GREP_CALLS } from '../constants.ts';
|
|
23
|
+
import { assertReadAllowed, isDeniedPathName, ReadDeniedError } from './read-guard.ts';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Drop result lines whose file path names a credential/secret. The path prefix
|
|
27
|
+
* is relative to the confined search path: a match/context-match line is
|
|
28
|
+
* `path:line: text` and a context line is `path-line- text`. Notice lines carry
|
|
29
|
+
* no such prefix and are kept.
|
|
30
|
+
*/
|
|
31
|
+
function filterDeniedLines(text: string): string {
|
|
32
|
+
const lines = text.split('\n');
|
|
33
|
+
const kept: string[] = [];
|
|
34
|
+
for (const line of lines) {
|
|
35
|
+
const m = line.match(/^(.+?):\d+: /) ?? line.match(/^(.+?)-\d+- /);
|
|
36
|
+
const prefix = m?.[1];
|
|
37
|
+
if (prefix && isDeniedPathName(prefix)) continue;
|
|
38
|
+
kept.push(line);
|
|
39
|
+
}
|
|
40
|
+
return kept.join('\n');
|
|
41
|
+
}
|
|
13
42
|
|
|
14
43
|
export function createGrepTool(options: {
|
|
15
44
|
tracker: ToolUsageTracker;
|
|
@@ -23,7 +52,7 @@ export function createGrepTool(options: {
|
|
|
23
52
|
...sdkGrep,
|
|
24
53
|
label: 'Code Search',
|
|
25
54
|
promptGuidelines: [
|
|
26
|
-
'Available for fast recursive text search in
|
|
55
|
+
'Available for fast recursive text search in the local project directory (nothing outside it; credential files and directories are refused).',
|
|
27
56
|
'Pattern supports regex. Use glob to scope to file types (e.g., "**/*.ts").',
|
|
28
57
|
'Options: ignoreCase, literal (disable regex), context (lines around match), limit (max matches).',
|
|
29
58
|
`Local code search — it does NOT consume your web-gathering budget (limit: ${MAX_GREP_CALLS} calls).`,
|
|
@@ -43,8 +72,31 @@ export function createGrepTool(options: {
|
|
|
43
72
|
};
|
|
44
73
|
}
|
|
45
74
|
|
|
75
|
+
// Confine the search path to the project before delegating: the SDK's
|
|
76
|
+
// rg process reads whatever path it is given, and the grep `path` is
|
|
77
|
+
// attacker-influenceable (the researcher is fed untrusted web content).
|
|
78
|
+
const searchDir = (params as { path?: string }).path ?? '.';
|
|
79
|
+
const searchPath = isAbsolute(searchDir) ? searchDir : resolvePath(cwd, searchDir);
|
|
80
|
+
try {
|
|
81
|
+
await assertReadAllowed(cwd, searchPath);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
const msg = err instanceof ReadDeniedError ? err.message : `read denied: ${String(err)}`;
|
|
84
|
+
return {
|
|
85
|
+
content: [{ type: 'text', text: `Grep refused: ${msg}` }],
|
|
86
|
+
details: { error: 'denied_path' },
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
46
90
|
try {
|
|
47
|
-
|
|
91
|
+
const result = await sdkExecute(toolCallId, params as GrepToolInput, signal, onUpdate, ctx);
|
|
92
|
+
// The rg process has already read the matched files; the exfil surface
|
|
93
|
+
// is the result text reaching the LLM. Strip any secret-file line so
|
|
94
|
+
// the secret is never carried out.
|
|
95
|
+
const content = (result as { content: { type: string; text: string }[] }).content;
|
|
96
|
+
for (const block of content) {
|
|
97
|
+
if (block.type === 'text') block.text = filterDeniedLines(block.text);
|
|
98
|
+
}
|
|
99
|
+
return result;
|
|
48
100
|
} catch (err) {
|
|
49
101
|
const msg = err instanceof Error ? err.message : String(err);
|
|
50
102
|
return {
|
package/src/tools/index.ts
CHANGED
|
@@ -13,8 +13,6 @@
|
|
|
13
13
|
import type { ToolDefinition, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
14
14
|
import type { ToolUsageTracker } from '../utils/tool-usage-tracker.ts';
|
|
15
15
|
import type { SystemResearchState } from '../orchestration/deep-research-types.ts';
|
|
16
|
-
import { createGuardedReadOperations } from './read-guard.ts';
|
|
17
|
-
import { createReadToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
18
16
|
import { createSearchTool } from './search.ts';
|
|
19
17
|
import { createScrapeTool } from './scrape.ts';
|
|
20
18
|
import { createSecuritySearchTool } from './security.ts';
|
|
@@ -75,7 +73,6 @@ export function createResearchTools(options: CreateToolsOptions): ToolDefinition
|
|
|
75
73
|
};
|
|
76
74
|
|
|
77
75
|
return [
|
|
78
|
-
createReadToolDefinition(options.cwd, { operations: createGuardedReadOperations(options.cwd) }) as ToolDefinition,
|
|
79
76
|
createSearchTool({
|
|
80
77
|
...resolvedOptions,
|
|
81
78
|
onProgress: options.onSearchProgress,
|
package/src/tools/read-guard.ts
CHANGED
|
@@ -80,6 +80,18 @@ export async function assertReadAllowed(cwd: string, absolutePath: string): Prom
|
|
|
80
80
|
}
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
/**
|
|
84
|
+
* True if a path (relative to the confined root, or absolute) names a credential
|
|
85
|
+
* directory segment or a credential/secret file basename. Shared by the read
|
|
86
|
+
* guard and the confined grep tool so both refuse the same names.
|
|
87
|
+
*/
|
|
88
|
+
export function isDeniedPathName(name: string): boolean {
|
|
89
|
+
const segments = name.split(sep);
|
|
90
|
+
if (segments.some((s) => DENIED_SEGMENTS.has(s.toLowerCase()))) return true;
|
|
91
|
+
const base = normalizeName(basename(name));
|
|
92
|
+
return !ALLOWED_ENV_TEMPLATE.test(base) && DENIED_BASENAME.test(base);
|
|
93
|
+
}
|
|
94
|
+
|
|
83
95
|
export function createGuardedReadOperations(cwd: string): ReadOperations {
|
|
84
96
|
return {
|
|
85
97
|
access: async (p) => {
|
|
@@ -28,11 +28,13 @@ import type {
|
|
|
28
28
|
ToolDefinition,
|
|
29
29
|
AgentToolResult,
|
|
30
30
|
ExtensionContext,
|
|
31
|
+
AgentToolUpdateCallback,
|
|
31
32
|
} from '@earendil-works/pi-coding-agent';
|
|
32
33
|
import { Type, type Static } from 'typebox';
|
|
33
34
|
import { Value } from 'typebox/value';
|
|
34
35
|
import { completeSimple } from '../core/llm/pi-ai-completion.ts';
|
|
35
|
-
import type { Model } from '@earendil-works/pi-ai';
|
|
36
|
+
import type { Api, Model } from '@earendil-works/pi-ai';
|
|
37
|
+
import type { ExtendedExtensionContext } from '../types/extension-context.ts';
|
|
36
38
|
import { recordLlmUsage } from '../utils/llm-usage.ts';
|
|
37
39
|
import { buildSafeOptions, validateAndExtractText, buildConstrainedSubmitTool, completeSimpleStructured } from '../core/llm/llm-utils.ts';
|
|
38
40
|
import { getService, tryGetServiceContainerFromCtx } from '../core/service-registry.ts';
|
|
@@ -156,7 +158,7 @@ function showKnowledgeSearchWidget(ctx: ExtensionContext): void {
|
|
|
156
158
|
knowledgeWidgetRefCount++;
|
|
157
159
|
try {
|
|
158
160
|
const panelFactory = createKnowledgeSearchPanel();
|
|
159
|
-
ctx.ui.setWidget(KNOWLEDGE_WIDGET_ID, panelFactory
|
|
161
|
+
ctx.ui.setWidget(KNOWLEDGE_WIDGET_ID, panelFactory, { placement: 'aboveEditor' });
|
|
160
162
|
} catch (err) {
|
|
161
163
|
logger.debug(`[research-knowledge-search] Failed to show TUI widget: ${err}`);
|
|
162
164
|
}
|
|
@@ -173,7 +175,7 @@ function hideKnowledgeSearchWidget(ctx: ExtensionContext): void {
|
|
|
173
175
|
knowledgeWidgetRefCount = Math.max(0, knowledgeWidgetRefCount - 1);
|
|
174
176
|
if (knowledgeWidgetRefCount > 0) return;
|
|
175
177
|
try {
|
|
176
|
-
ctx.ui.setWidget(KNOWLEDGE_WIDGET_ID, undefined
|
|
178
|
+
ctx.ui.setWidget(KNOWLEDGE_WIDGET_ID, undefined, { placement: 'aboveEditor' });
|
|
177
179
|
} catch (err) {
|
|
178
180
|
logger.debug(`[research-knowledge-search] Failed to hide TUI widget: ${err}`);
|
|
179
181
|
}
|
|
@@ -347,11 +349,11 @@ import { frameUntrustedReport } from '../utils/untrusted-notice.ts';
|
|
|
347
349
|
* Resolve the model to use for the background synthesis LLM.
|
|
348
350
|
* Priority: explicit modelId → RESEARCH_MODEL → ctx.model → fallback
|
|
349
351
|
*/
|
|
350
|
-
function resolveSynthesisModel(ctx: ExtensionContext, config: Config): { model?: Model<
|
|
352
|
+
function resolveSynthesisModel(ctx: ExtensionContext, config: Config): { model?: Model<Api>; error?: string } {
|
|
351
353
|
try {
|
|
352
354
|
const model = resolveResearchModel({
|
|
353
355
|
modelRegistry: ctx.modelRegistry,
|
|
354
|
-
hostModel: ctx.model
|
|
356
|
+
hostModel: ctx.model,
|
|
355
357
|
cwd: ctx.cwd,
|
|
356
358
|
config,
|
|
357
359
|
});
|
|
@@ -452,7 +454,7 @@ export function splitPromptAtUserTurn(template: string): { system: string; user:
|
|
|
452
454
|
|
|
453
455
|
/** Exported for unit testing of the transient-retry loop. */
|
|
454
456
|
export async function runBackgroundExtraction(
|
|
455
|
-
model: Model<
|
|
457
|
+
model: Model<Api>,
|
|
456
458
|
// headers values are string | null (pi-ai's ProviderHeaders) — forwarded
|
|
457
459
|
// to completeSimple's own SimpleStreamOptions.headers unchanged.
|
|
458
460
|
auth: { apiKey: string; headers?: Record<string, string | null> },
|
|
@@ -538,7 +540,7 @@ export async function runBackgroundExtraction(
|
|
|
538
540
|
const response = structured.response;
|
|
539
541
|
|
|
540
542
|
// Track token and cost metrics for the background synthesis call
|
|
541
|
-
recordLlmUsage(model,
|
|
543
|
+
recordLlmUsage(model, response.usage, { component: 'knowledge_search' });
|
|
542
544
|
|
|
543
545
|
// Tool-call arguments are re-serialized so the SAME parse → coerce →
|
|
544
546
|
// validate pipeline below runs for both outcomes; text passes through
|
|
@@ -574,7 +576,7 @@ export async function runBackgroundExtraction(
|
|
|
574
576
|
// Log why validation failed
|
|
575
577
|
try {
|
|
576
578
|
const errors = [...Value.Errors(ResearchKnowledgeSynthesisResponseSchema, extracted.value)];
|
|
577
|
-
const errorDetail = errors.map((e:
|
|
579
|
+
const errorDetail = errors.map((e: { path?: unknown; message?: string }) => `${e.path}: ${e.message}`).join(', ');
|
|
578
580
|
logger.debug(`[research-knowledge-search] Schema validation failed: ${errorDetail}`);
|
|
579
581
|
} catch (validationErr) {
|
|
580
582
|
logger.debug(`[research-knowledge-search] TypeBox validation error: ${validationErr}`);
|
|
@@ -638,7 +640,7 @@ export async function runBackgroundExtraction(
|
|
|
638
640
|
* Exported for unit testing.
|
|
639
641
|
*/
|
|
640
642
|
export async function triageRelevantUrls(
|
|
641
|
-
model: Model<
|
|
643
|
+
model: Model<Api>,
|
|
642
644
|
// headers values are string | null (pi-ai's ProviderHeaders) — forwarded
|
|
643
645
|
// to completeSimple's own SimpleStreamOptions.headers unchanged.
|
|
644
646
|
auth: { apiKey: string; headers?: Record<string, string | null> },
|
|
@@ -704,7 +706,7 @@ export async function triageRelevantUrls(
|
|
|
704
706
|
'knowledge-relevance-triage',
|
|
705
707
|
);
|
|
706
708
|
|
|
707
|
-
recordLlmUsage(model,
|
|
709
|
+
recordLlmUsage(model, response.usage, { component: 'knowledge_triage' });
|
|
708
710
|
|
|
709
711
|
responseText = validateAndExtractText(response, 'Knowledge Triage');
|
|
710
712
|
break;
|
|
@@ -905,7 +907,7 @@ export function createResearchKnowledgeSearchTool(iface?: ConfigInterface): Tool
|
|
|
905
907
|
_toolCallId: string,
|
|
906
908
|
params: unknown,
|
|
907
909
|
signal: AbortSignal | undefined,
|
|
908
|
-
_onUpdate:
|
|
910
|
+
_onUpdate: AgentToolUpdateCallback<unknown> | undefined,
|
|
909
911
|
ctx: ExtensionContext,
|
|
910
912
|
): Promise<AgentToolResult<unknown>> {
|
|
911
913
|
const startTime = Date.now();
|
|
@@ -1058,8 +1060,8 @@ export function createResearchKnowledgeSearchTool(iface?: ConfigInterface): Tool
|
|
|
1058
1060
|
// Cache/session-affinity hint only (keeps repeated calls on the same warmed
|
|
1059
1061
|
// replica) — same resolution research-config.ts uses, since this tool has no
|
|
1060
1062
|
// researchId of its own to key on. ctx.sessionId is read defensively: it is
|
|
1061
|
-
// not on every host's ExtensionContext shape, hence the
|
|
1062
|
-
(ctx as
|
|
1063
|
+
// not on every host's ExtensionContext shape, hence the cast.
|
|
1064
|
+
(ctx as ExtendedExtensionContext).sessionId || ctx.sessionManager?.getSessionId(),
|
|
1063
1065
|
);
|
|
1064
1066
|
|
|
1065
1067
|
const durationMs = Date.now() - startTime;
|
|
@@ -34,7 +34,11 @@ import { startResearchSession, endResearchSession, registerSessionAbort } from '
|
|
|
34
34
|
import { createResearchTuiManager, hideWorkingIndicator } from '../tui/research-tui-manager.ts';
|
|
35
35
|
import { createCleanupFunction } from '../cleanup/research-cleanup.ts';
|
|
36
36
|
import { createResearchObserver, createObserverState, stopObserverWaveAnimation } from '../observers/research-observer-impl.ts';
|
|
37
|
+
import type { ObserverState } from '../observers/research-observer-impl.ts';
|
|
37
38
|
import { HeadlessObserver } from '../orchestration/headless-observer.ts';
|
|
39
|
+
import type { ResearchPanelState } from '../tui/research-panel.ts';
|
|
40
|
+
import type { IMetricsSnapshot } from '../utils/metrics.ts';
|
|
41
|
+
import type { Api, Model } from '@earendil-works/pi-ai';
|
|
38
42
|
import { isPromptCachingActiveForModel } from '../core/llm/research-model-resolver.ts';
|
|
39
43
|
|
|
40
44
|
import { ensureFunctionalHealth, createHealthMonitor } from '../tui/research-health.ts';
|
|
@@ -51,10 +55,10 @@ import { frameUntrustedReport } from '../utils/untrusted-notice.ts';
|
|
|
51
55
|
*/
|
|
52
56
|
function appendResearchSummary(
|
|
53
57
|
result: string,
|
|
54
|
-
metricsSnapshot:
|
|
58
|
+
metricsSnapshot: IMetricsSnapshot,
|
|
55
59
|
errorReport: ErrorReport,
|
|
56
60
|
): string {
|
|
57
|
-
const stats = extractRunStats(metricsSnapshot
|
|
61
|
+
const stats = extractRunStats(metricsSnapshot);
|
|
58
62
|
|
|
59
63
|
if (!stats) {
|
|
60
64
|
// The run produced no meaningful metrics (hard failure before any research ran).
|
|
@@ -192,7 +196,7 @@ export function createResearchTool(iface?: ConfigInterface): ToolDefinition {
|
|
|
192
196
|
_toolCallId: string,
|
|
193
197
|
params: unknown,
|
|
194
198
|
aborted: AbortSignal | undefined,
|
|
195
|
-
onUpdate: AgentToolUpdateCallback<
|
|
199
|
+
onUpdate: AgentToolUpdateCallback<unknown>,
|
|
196
200
|
ctx: ExtensionContext,
|
|
197
201
|
): Promise<AgentToolResult<unknown>> {
|
|
198
202
|
// 1. System Readiness Check
|
|
@@ -251,9 +255,9 @@ export function createResearchTool(iface?: ConfigInterface): ToolDefinition {
|
|
|
251
255
|
const internalAbort = new AbortController();
|
|
252
256
|
let tuiManager: ReturnType<typeof createResearchTuiManager> | null = null;
|
|
253
257
|
let healthMonitorInstance: ReturnType<typeof createHealthMonitor> | null = null;
|
|
254
|
-
let observer:
|
|
255
|
-
let observerState:
|
|
256
|
-
let panelState:
|
|
258
|
+
let observer: ReturnType<typeof createResearchObserver> | HeadlessObserver | undefined;
|
|
259
|
+
let observerState: ObserverState | undefined;
|
|
260
|
+
let panelState: ResearchPanelState | undefined;
|
|
257
261
|
// Assigned only after the TUI panel and observers are wired up. A failure
|
|
258
262
|
// before that point (e.g. the pre-run health check) leaves it undefined,
|
|
259
263
|
// so teardownUi() guards before calling it.
|
|
@@ -332,7 +336,7 @@ export function createResearchTool(iface?: ConfigInterface): ToolDefinition {
|
|
|
332
336
|
const selectedModel = await orch.resolveResearchModel({
|
|
333
337
|
ctx,
|
|
334
338
|
query: sanitizedQuery,
|
|
335
|
-
model: modelId ? { id: modelId } as
|
|
339
|
+
model: modelId ? { id: modelId } as unknown as Model<Api> : undefined,
|
|
336
340
|
config,
|
|
337
341
|
sessionId: piSessionId,
|
|
338
342
|
researchId,
|
|
@@ -419,9 +423,10 @@ export function createResearchTool(iface?: ConfigInterface): ToolDefinition {
|
|
|
419
423
|
|
|
420
424
|
// Minimal stub — only stopObserverWaveAnimation touches panelState in the
|
|
421
425
|
// headless path (it clears wave fields). Run totals come from the metrics
|
|
422
|
-
// registry, so no token/cost state is needed here.
|
|
423
|
-
|
|
424
|
-
|
|
426
|
+
// registry, so no token/cost state is needed here. The cast is safe:
|
|
427
|
+
// the stub's only consumer guards the fields it touches.
|
|
428
|
+
panelState = {} as ResearchPanelState;
|
|
429
|
+
observerState = {} as ObserverState;
|
|
425
430
|
}
|
|
426
431
|
|
|
427
432
|
// Handle abort signal. Track the handler so teardownUi() can detach it
|
package/src/tools/scrape.ts
CHANGED
|
@@ -13,6 +13,7 @@ import type { ToolDefinition, AgentToolResult, ExtensionContext, AgentToolUpdate
|
|
|
13
13
|
import { Type, type Static } from 'typebox';
|
|
14
14
|
import { Value } from 'typebox/value';
|
|
15
15
|
import { scrape } from '../web-research/web-scraper.ts';
|
|
16
|
+
import type { ScrapeResult } from '../web-research/types.ts';
|
|
16
17
|
import type { ToolUsageTracker } from '../utils/tool-usage-tracker.ts';
|
|
17
18
|
import type { SystemResearchState } from '../orchestration/deep-research-types.ts';
|
|
18
19
|
import { deduplicateUrls, normalizeUrl, getCachedScrapedContent, registerResearcherScrapes, buildSessionPoolFooter } from '../utils/shared-links.ts';
|
|
@@ -119,7 +120,7 @@ export function createScrapeTool(options: {
|
|
|
119
120
|
'PDFs are auto-detected and extracted with high fidelity.',
|
|
120
121
|
],
|
|
121
122
|
parameters: ScrapeParamsSchema,
|
|
122
|
-
async execute(_callId: string, params: unknown, signal: AbortSignal, _onUpdate: AgentToolUpdateCallback<
|
|
123
|
+
async execute(_callId: string, params: unknown, signal: AbortSignal, _onUpdate: AgentToolUpdateCallback<unknown>): Promise<AgentToolResult<unknown>> {
|
|
123
124
|
const callStartTime = Date.now();
|
|
124
125
|
|
|
125
126
|
// Validate BEFORE spending the budget slot — the doctrine security.ts /
|
|
@@ -281,7 +282,7 @@ export function createScrapeTool(options: {
|
|
|
281
282
|
}
|
|
282
283
|
}
|
|
283
284
|
|
|
284
|
-
let freshResults:
|
|
285
|
+
let freshResults: ScrapeResult[];
|
|
285
286
|
const concurrency = p.maxConcurrency || defaultConcurrency;
|
|
286
287
|
|
|
287
288
|
try {
|
|
@@ -443,7 +443,7 @@ export function createMasterResearchPanel(
|
|
|
443
443
|
const display = truncateToWidth(`${prefix}${msg.text}`, width);
|
|
444
444
|
// Use 'warning' style for queued (amber/yellow), 'muted' for active
|
|
445
445
|
const color = msg.status === 'queued' ? 'warning' : 'muted';
|
|
446
|
-
allLines.push(theme.fg(color
|
|
446
|
+
allLines.push(theme.fg(color, display));
|
|
447
447
|
}
|
|
448
448
|
} else if (isSteeringAcceptable) {
|
|
449
449
|
// No messages yet but steering is acceptable — show the "available" hint
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* to provide type safety for additional properties that are accessed at runtime.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
8
|
+
import type { ExtensionContext, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
9
9
|
export type { AgentSessionEvent } from '@earendil-works/pi-coding-agent';
|
|
10
10
|
|
|
11
11
|
/**
|
|
@@ -21,7 +21,7 @@ export interface ExtendedExtensionContext extends ExtensionContext {
|
|
|
21
21
|
/** Session ID (provided by extension host) */
|
|
22
22
|
sessionId?: string;
|
|
23
23
|
/** Settings manager (provided in some contexts) */
|
|
24
|
-
settingsManager?:
|
|
24
|
+
settingsManager?: SettingsManager;
|
|
25
25
|
/** Current tool exclusion list */
|
|
26
26
|
excludeTools?: string[];
|
|
27
27
|
}
|
package/src/types/llm.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* more specific typing for our use cases.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import { calculateCost, type Model } from '@earendil-works/pi-ai';
|
|
9
|
+
import { calculateCost, type Api, type AnyModel, type Model, type Usage } from '@earendil-works/pi-ai';
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Token usage and cost information from LLM responses
|
|
@@ -55,7 +55,7 @@ export interface ToolCallBlock {
|
|
|
55
55
|
type: 'tool_call';
|
|
56
56
|
id?: string;
|
|
57
57
|
name: string;
|
|
58
|
-
arguments:
|
|
58
|
+
arguments: Record<string, unknown>;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
/**
|
|
@@ -78,7 +78,7 @@ function parseTokenUsage(usage: unknown): Partial<TokenUsage> {
|
|
|
78
78
|
return {};
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
-
const obj = usage as Record<string,
|
|
81
|
+
const obj = usage as Record<string, unknown>;
|
|
82
82
|
const result: Partial<TokenUsage> = {};
|
|
83
83
|
|
|
84
84
|
if (typeof obj['input'] === 'number') {
|
|
@@ -97,7 +97,7 @@ function parseTokenUsage(usage: unknown): Partial<TokenUsage> {
|
|
|
97
97
|
result.totalTokens = obj['totalTokens'];
|
|
98
98
|
}
|
|
99
99
|
if (obj['cost'] && typeof obj['cost'] === 'object') {
|
|
100
|
-
result.cost = obj['cost'];
|
|
100
|
+
result.cost = obj['cost'] as TokenUsage['cost'];
|
|
101
101
|
}
|
|
102
102
|
|
|
103
103
|
return result;
|
|
@@ -126,7 +126,7 @@ function calculateTotalTokens(usage: Partial<TokenUsage>): number {
|
|
|
126
126
|
* @param model - The model used for the call (for cost estimation)
|
|
127
127
|
* @param rawUsage - The raw usage object from the LLM response
|
|
128
128
|
*/
|
|
129
|
-
export function extractUsage(model: Model<
|
|
129
|
+
export function extractUsage(model: Model<Api>, rawUsage: unknown): { tokens: number; cost: number; parsed: Partial<TokenUsage> } {
|
|
130
130
|
if (!rawUsage) {
|
|
131
131
|
return { tokens: 0, cost: 0, parsed: {} };
|
|
132
132
|
}
|
|
@@ -135,10 +135,11 @@ export function extractUsage(model: Model<any>, rawUsage: any): { tokens: number
|
|
|
135
135
|
const tokens = calculateTotalTokens(parsed);
|
|
136
136
|
|
|
137
137
|
// Ultra-accurate cost calculation
|
|
138
|
-
|
|
138
|
+
const usage = rawUsage as { cost?: { total?: number } };
|
|
139
|
+
let cost = parsed.cost?.total ?? usage.cost?.total ?? 0;
|
|
139
140
|
if (cost === 0 && tokens > 0) {
|
|
140
141
|
try {
|
|
141
|
-
const calculatedCost = calculateCost(model,
|
|
142
|
+
const calculatedCost = calculateCost(model as AnyModel, usage as Usage);
|
|
142
143
|
cost = calculatedCost.total;
|
|
143
144
|
} catch {
|
|
144
145
|
// Best-effort cost calculation; if calculateCost fails (e.g. model not in registry), keep 0.
|
|
@@ -4,11 +4,13 @@
|
|
|
4
4
|
* Type definitions for the research TUI panel.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
import type { ThemeColor } from '@earendil-works/pi-coding-agent';
|
|
8
|
+
|
|
7
9
|
/**
|
|
8
10
|
* Local Theme interface — mirrors pi-tui Theme.fg()
|
|
9
11
|
*/
|
|
10
12
|
export interface Theme {
|
|
11
|
-
fg: (color:
|
|
13
|
+
fg: (color: ThemeColor, text: string) => string;
|
|
12
14
|
}
|
|
13
15
|
|
|
14
16
|
export interface SliceState {
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* State Types
|
|
3
|
+
*
|
|
4
|
+
* Shared types for state management. These live in the foundation `types/` layer
|
|
5
|
+
* (not `infrastructure/`) so that `core/interfaces/` — which defines the
|
|
6
|
+
* `IStateManager` contract — can name the state shape without depending on
|
|
7
|
+
* `infrastructure/` (a layer above it in the dependency order). The TypeBox
|
|
8
|
+
* schemas are runtime values, so this file is imported (not `import type`) by the
|
|
9
|
+
* infrastructure that validates and migrates the on-disk state.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { Type, type Static } from 'typebox';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Current on-disk state schema version. Bump this (and add a migration step in
|
|
16
|
+
* state-migration.ts) whenever the persisted shape changes incompatibly. The
|
|
17
|
+
* schema's `version` literal is pinned to this value so a reader only accepts a
|
|
18
|
+
* state it actually understands; older/newer files are routed through migration
|
|
19
|
+
* or future-version quarantine rather than being silently overwritten.
|
|
20
|
+
*/
|
|
21
|
+
export const CURRENT_STATE_VERSION = 1 as const;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* State metrics interface
|
|
25
|
+
*/
|
|
26
|
+
export interface StateMetrics {
|
|
27
|
+
totalSessions: number;
|
|
28
|
+
activeSessions: number;
|
|
29
|
+
oldestSession: number | null;
|
|
30
|
+
newestSession: number | null;
|
|
31
|
+
containerUptime: number | null;
|
|
32
|
+
lastHeartbeatAge: number | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Session information interface
|
|
37
|
+
*/
|
|
38
|
+
export const SessionInfoSchema = Type.Object({
|
|
39
|
+
pid: Type.Number(),
|
|
40
|
+
startTime: Type.Optional(Type.Number()),
|
|
41
|
+
lastSeen: Type.Number(),
|
|
42
|
+
connectedAt: Type.Number(),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Main state structure interface
|
|
47
|
+
*/
|
|
48
|
+
export const SingletonStateSchema = Type.Object({
|
|
49
|
+
version: Type.Literal(CURRENT_STATE_VERSION),
|
|
50
|
+
containerId: Type.String(),
|
|
51
|
+
containerName: Type.String(),
|
|
52
|
+
port: Type.Number(),
|
|
53
|
+
sessions: Type.Record(Type.String(), SessionInfoSchema),
|
|
54
|
+
lastUpdated: Type.Number(),
|
|
55
|
+
browserServer: Type.Optional(Type.Object({
|
|
56
|
+
port: Type.Number(),
|
|
57
|
+
pid: Type.Number(),
|
|
58
|
+
startTime: Type.Optional(Type.Number()),
|
|
59
|
+
schedulerId: Type.Optional(Type.String()),
|
|
60
|
+
authSecret: Type.Optional(Type.String()),
|
|
61
|
+
})),
|
|
62
|
+
schedulerVersion: Type.Optional(Type.String()),
|
|
63
|
+
gpuOwner: Type.Optional(Type.Object({
|
|
64
|
+
pid: Type.Number(),
|
|
65
|
+
startTime: Type.Optional(Type.Number()),
|
|
66
|
+
startedAt: Type.Number(),
|
|
67
|
+
sessionId: Type.Optional(Type.String()),
|
|
68
|
+
// Re-entrant hold count for the owning process. The lock is shared by N
|
|
69
|
+
// concurrent in-process embedding calls (activeEmbeddings is designed > 1);
|
|
70
|
+
// each re-entrant acquire increments and each release decrements, so the
|
|
71
|
+
// cross-process owner record is only cleared when the last in-process hold
|
|
72
|
+
// is released. Absent on state written before refcounting — treated as 1.
|
|
73
|
+
holds: Type.Optional(Type.Number()),
|
|
74
|
+
})),
|
|
75
|
+
embeddingServer: Type.Optional(Type.Object({
|
|
76
|
+
port: Type.Number(),
|
|
77
|
+
pid: Type.Number(),
|
|
78
|
+
startTime: Type.Optional(Type.Number()),
|
|
79
|
+
serverId: Type.String(),
|
|
80
|
+
// EMBEDDING_MODEL the leader serves. A follower configured with a DIFFERENT
|
|
81
|
+
// model must not adopt this leader (same-dimension models would silently
|
|
82
|
+
// cross-embed and corrupt the vector space) — it falls back to a local
|
|
83
|
+
// in-process embedder instead. Optional for entries written by older
|
|
84
|
+
// processes, which are tolerated as matching.
|
|
85
|
+
model: Type.Optional(Type.String()),
|
|
86
|
+
// Shared secret a follower must present on every embed request. Mirrors
|
|
87
|
+
// browserServer.authSecret: the server listens on loopback, but loopback is
|
|
88
|
+
// not an authorization boundary — any local process could otherwise enqueue
|
|
89
|
+
// embedding work, and because the serial queue steps the leader down when
|
|
90
|
+
// poisoned, sustained abuse denies the knowledge store rather than merely
|
|
91
|
+
// burning GPU. Optional so an entry written by an older leader still parses;
|
|
92
|
+
// a client that finds none simply sends no header, and such a leader does not
|
|
93
|
+
// check one either.
|
|
94
|
+
authSecret: Type.Optional(Type.String()),
|
|
95
|
+
})),
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
export type SingletonState = Static<typeof SingletonStateSchema>;
|
|
@@ -65,18 +65,18 @@ const MAX_DIGEST_BLOCK_CHARS = 8000;
|
|
|
65
65
|
* a reader that does not exist — while telling the model about a "research lead" that is
|
|
66
66
|
* not part of its run.
|
|
67
67
|
*/
|
|
68
|
-
export const RESEARCHER_DIGEST_SECTION = `Your
|
|
68
|
+
export const RESEARCHER_DIGEST_SECTION = `Your final message is the COVERAGE DIGEST block. Emit it and stop — do NOT write a report. The raw content you scraped is what the synthesis step reads; your job is to scrape, then account for what you covered.
|
|
69
69
|
|
|
70
|
-
###
|
|
70
|
+
### COVERAGE DIGEST (mandatory)
|
|
71
71
|
|
|
72
|
-
|
|
72
|
+
The research lead reads this to decide what still needs investigating. On the round your work arrives the lead reads the digest alongside the raw content and checks one against the other; on every later round it sees ONLY this digest — so anything you leave out of it is invisible to every decision after the first.
|
|
73
73
|
|
|
74
74
|
${COVERAGE_DIGEST_HEADER}
|
|
75
75
|
Goal: [your assigned goal, restated in one line]
|
|
76
76
|
Covered: [the specific topics you actually established from sources, separated by semicolons — be concrete, name the things you found out, not the areas you looked at]
|
|
77
77
|
Unsubstantiated: [claims you searched for but could not ground in any source; write "none" if there are none]
|
|
78
78
|
Gaps: [what a follow-up researcher would still need to investigate on this goal; write "none" if your goal is fully covered]
|
|
79
|
-
Sources: [the number of
|
|
79
|
+
Sources: [the number of URLs you scraped]
|
|
80
80
|
${COVERAGE_DIGEST_TERMINATOR}
|
|
81
81
|
|
|
82
82
|
Rules for the digest:
|
|
@@ -84,8 +84,6 @@ Rules for the digest:
|
|
|
84
84
|
- Be honest about \`Gaps\` and \`Unsubstantiated\`. Claiming full coverage you do not have is the single most damaging thing you can write here: it argues for ending the research on this topic, and after the round it arrives there is no report left for the lead to check the claim against.
|
|
85
85
|
- Write both delimiter lines exactly, in capitals, each on its own line.
|
|
86
86
|
|
|
87
|
-
### Part 2 — Report body
|
|
88
|
-
|
|
89
87
|
`;
|
|
90
88
|
|
|
91
89
|
/** Line-leading delimiter matcher, tolerating the markdown decoration models add. */
|
|
@@ -168,6 +166,29 @@ export function splitCoverageDigest(report: string): SplitReport {
|
|
|
168
166
|
* many sources it cited — and says plainly that the rest is unknown. A router told
|
|
169
167
|
* "coverage unknown" delegates; a router told nothing assumes the gap was filled.
|
|
170
168
|
*/
|
|
169
|
+
/**
|
|
170
|
+
* Build a clean fallback digest for a raw-scrape researcher that emitted no digest of its
|
|
171
|
+
* own.
|
|
172
|
+
*
|
|
173
|
+
* In the raw-scrape flow the report body is the researcher's raw tool results, which carry
|
|
174
|
+
* no [N] citations and open with a tool-name header — so `deriveCoverageDigest` reads the
|
|
175
|
+
* body as `Covered: <tool name>` and `Sources: 0`, actively misleading the router (it reads
|
|
176
|
+
* "0 sources" as "nothing grounded" and "covered: scrape" as the topic). This fallback
|
|
177
|
+
* instead states the two facts the executor knows directly: the researcher's assigned goal
|
|
178
|
+
* (what it was sent to cover) and how many URLs it actually scraped (its real source count).
|
|
179
|
+
*
|
|
180
|
+
* @param goal - The researcher's assigned goal
|
|
181
|
+
* @param scrapeCount - The researcher's successful-scrape count
|
|
182
|
+
*/
|
|
183
|
+
export function buildFallbackDigest(goal: string, scrapeCount: number): string {
|
|
184
|
+
const topic = goal.trim() || 'unknown — no goal recorded';
|
|
185
|
+
return [
|
|
186
|
+
`Covered: ${topic} (no coverage digest emitted; goal restated)`,
|
|
187
|
+
`Gaps: unknown — this researcher emitted no coverage digest`,
|
|
188
|
+
`Sources: ${scrapeCount}`,
|
|
189
|
+
].join('\n');
|
|
190
|
+
}
|
|
191
|
+
|
|
171
192
|
export function deriveCoverageDigest(body: string): string {
|
|
172
193
|
const citationCount = parseCitations(body).length;
|
|
173
194
|
|
package/src/utils/llm-usage.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* counted nothing at all) silently under-reported cost. Route every call site here.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import type { Model } from '@earendil-works/pi-ai';
|
|
14
|
+
import type { Api, Model } from '@earendil-works/pi-ai';
|
|
15
15
|
import { extractUsage, type TokenUsage } from '../types/llm.ts';
|
|
16
16
|
import { logger } from '../logger.ts';
|
|
17
17
|
import { metrics } from './metrics.ts';
|
|
@@ -31,7 +31,7 @@ const unpricedModelsWarned = new Set<string>();
|
|
|
31
31
|
* suppressed a zero cost. The message deliberately does not assert a fault — it
|
|
32
32
|
* states the condition and names the usual cause.
|
|
33
33
|
*/
|
|
34
|
-
function warnIfUnpriced(model: Model<
|
|
34
|
+
function warnIfUnpriced(model: Model<Api>, tokens: number, cost: number): void {
|
|
35
35
|
if (tokens <= 0 || cost > 0) return;
|
|
36
36
|
const m = model as unknown as { provider?: string; id?: string; cost?: Record<string, number> };
|
|
37
37
|
const key = `${m.provider ?? 'unknown'}/${m.id ?? 'unknown'}`;
|
|
@@ -112,7 +112,7 @@ export interface RecordUsageOptions {
|
|
|
112
112
|
* Returns the extracted { tokens, cost } for callers that also need the value.
|
|
113
113
|
*/
|
|
114
114
|
export function recordLlmUsage(
|
|
115
|
-
model: Model<
|
|
115
|
+
model: Model<Api>,
|
|
116
116
|
rawUsage: unknown,
|
|
117
117
|
opts: RecordUsageOptions
|
|
118
118
|
): { tokens: number; cost: number } {
|