@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.
- package/agent-skill/pi-research/SKILL.md +1 -1
- package/dist/cli.mjs +276 -171
- 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 +49 -0
- package/docs/CONFIGURATION.md +1 -0
- package/package.json +9 -9
- 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 +33 -13
- 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 +5 -4
- 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/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 +15 -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 +23 -7
- 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/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/scraper-utils.ts +9 -3
- package/src/web-research/web-scraper.ts +25 -10
package/src/sdk.ts
CHANGED
|
@@ -33,7 +33,7 @@ import type { IPlanningService } from './core/interfaces/planning-interfaces.ts'
|
|
|
33
33
|
import type { ResearchObserver, HeadlessObserverOptions } from './core/interfaces/observer-interfaces.ts';
|
|
34
34
|
import type { ResearchPlan } from './core/interfaces/research-plan-types.ts';
|
|
35
35
|
import { HeadlessObserver, isHeadlessObserverBag } from './orchestration/headless-observer.ts';
|
|
36
|
-
import type { Model } from '@earendil-works/pi-ai';
|
|
36
|
+
import type { Api, Model } from '@earendil-works/pi-ai';
|
|
37
37
|
import { type ExtensionContext, ModelRegistry } from '@earendil-works/pi-coding-agent';
|
|
38
38
|
import { logger, createLogger, setLogger } from './logger.ts';
|
|
39
39
|
import { redactSecrets } from './utils/log-utils.ts';
|
|
@@ -58,7 +58,7 @@ import type { ResearchDepth } from './types/index.ts';
|
|
|
58
58
|
let isInitialized = false;
|
|
59
59
|
let _initPromise: Promise<void> | null = null;
|
|
60
60
|
let globalRegistry: ModelRegistry | null = null;
|
|
61
|
-
let globalModel: Model<
|
|
61
|
+
let globalModel: Model<Api> | null = null;
|
|
62
62
|
let globalCwd: string = process.cwd();
|
|
63
63
|
let globalApiKey: string | undefined = undefined;
|
|
64
64
|
let globalContainer: ServiceContainer | null = null;
|
|
@@ -189,7 +189,7 @@ export interface ResearchSDKOptions {
|
|
|
189
189
|
* in pi's configuration. The SDK never follows the model selected
|
|
190
190
|
* interactively inside the pi extension.
|
|
191
191
|
*/
|
|
192
|
-
model?: string | Model<
|
|
192
|
+
model?: string | Model<Api>;
|
|
193
193
|
|
|
194
194
|
/**
|
|
195
195
|
* Optional explicit API key for the model.
|
|
@@ -289,7 +289,7 @@ async function _doInit(options: ResearchSDKOptions = {}): Promise<void> {
|
|
|
289
289
|
if (options.model) {
|
|
290
290
|
const explicit = typeof options.model === 'string'
|
|
291
291
|
? options.model
|
|
292
|
-
: `${
|
|
292
|
+
: `${options.model.provider}/${options.model.id}`;
|
|
293
293
|
globalConfig = { ...globalConfig, RESEARCH_MODEL: explicit };
|
|
294
294
|
}
|
|
295
295
|
|
|
@@ -303,8 +303,8 @@ async function _doInit(options: ResearchSDKOptions = {}): Promise<void> {
|
|
|
303
303
|
if (slashIdx > 0) {
|
|
304
304
|
parsedProvider = effectiveModel.slice(0, slashIdx);
|
|
305
305
|
}
|
|
306
|
-
} else if (
|
|
307
|
-
parsedProvider =
|
|
306
|
+
} else if (effectiveModel.provider) {
|
|
307
|
+
parsedProvider = effectiveModel.provider;
|
|
308
308
|
}
|
|
309
309
|
}
|
|
310
310
|
|
|
@@ -324,8 +324,8 @@ async function _doInit(options: ResearchSDKOptions = {}): Promise<void> {
|
|
|
324
324
|
// planning would silently run on the fallback. The initial coordinator
|
|
325
325
|
// (round 1) always uses ctx.model (the parent chat's model) for prompt-
|
|
326
326
|
// cache continuity, regardless of this seeding.
|
|
327
|
-
if (effectiveModel && typeof effectiveModel === 'object' &&
|
|
328
|
-
globalModel = effectiveModel
|
|
327
|
+
if (effectiveModel && typeof effectiveModel === 'object' && effectiveModel.id) {
|
|
328
|
+
globalModel = effectiveModel;
|
|
329
329
|
} else {
|
|
330
330
|
globalModel = resolveModel(
|
|
331
331
|
globalRegistry,
|
|
@@ -826,7 +826,7 @@ export async function runQuickResearch(
|
|
|
826
826
|
options: Omit<ResearchOptions, 'ctx' | 'query' | 'model' | 'sessionId' | 'researchId' | 'depth'> = {},
|
|
827
827
|
signal?: AbortSignal
|
|
828
828
|
): Promise<string> {
|
|
829
|
-
return runDeepResearch(query, { ...options, depth: 0 }
|
|
829
|
+
return runDeepResearch(query, { ...options, depth: 0 }, signal);
|
|
830
830
|
}
|
|
831
831
|
|
|
832
832
|
/**
|
|
@@ -1125,6 +1125,6 @@ function createMockContext(sessionId: string): ExtensionContext {
|
|
|
1125
1125
|
getSessionId: () => sessionId,
|
|
1126
1126
|
getBranch: () => [],
|
|
1127
1127
|
},
|
|
1128
|
-
} as
|
|
1128
|
+
} as unknown as ExtensionContext;
|
|
1129
1129
|
}
|
|
1130
1130
|
|
|
@@ -24,6 +24,15 @@ import * as os from 'node:os';
|
|
|
24
24
|
import * as path from 'node:path';
|
|
25
25
|
import { fileURLToPath } from 'node:url';
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Best-effort detail for a caught error: a thrown Node errno carries `code`
|
|
29
|
+
* (e.g. EPERM), most Errors carry `message`, and non-Error throws stringify.
|
|
30
|
+
*/
|
|
31
|
+
function errDetail(err: unknown): string {
|
|
32
|
+
const e = err as { code?: string; message?: string } | undefined;
|
|
33
|
+
return e?.code ?? e?.message ?? String(err);
|
|
34
|
+
}
|
|
35
|
+
|
|
27
36
|
export type HarnessConfidence = 'confirmed' | 'partial' | 'unverified';
|
|
28
37
|
|
|
29
38
|
export interface HarnessDef {
|
|
@@ -442,7 +451,7 @@ export function installSkill(toolIds: string[], opts: InstallOptions = {}): Inst
|
|
|
442
451
|
fs.symlinkSync(source, absSkillPath, process.platform === 'win32' ? 'junction' : 'dir');
|
|
443
452
|
upsertEntry(manifest, { tool: id, path: absSkillPath, type: 'symlink', source, createdAt: now, ...(skillVersion ? { version: skillVersion } : {}) });
|
|
444
453
|
results.push({ tool: id, path: absSkillPath, type: 'symlink', status: 'installed', message: 're-pointed stale symlink to current source' });
|
|
445
|
-
} catch (relinkErr:
|
|
454
|
+
} catch (relinkErr: unknown) {
|
|
446
455
|
// The old link is already gone at this point (unlinkSync above
|
|
447
456
|
// succeeded) — letting this escape to the outer catch below
|
|
448
457
|
// silently fell through to reporting 'already-installed' for a
|
|
@@ -454,9 +463,9 @@ export function installSkill(toolIds: string[], opts: InstallOptions = {}): Inst
|
|
|
454
463
|
try {
|
|
455
464
|
copyDir(source, absSkillPath);
|
|
456
465
|
upsertEntry(manifest, { tool: id, path: absSkillPath, type: 'copy', source, createdAt: now, ...(skillVersion ? { version: skillVersion } : {}) });
|
|
457
|
-
results.push({ tool: id, path: absSkillPath, type: 'copy', status: 'installed', message: `symlink re-point unavailable (${relinkErr
|
|
458
|
-
} catch (copyErr:
|
|
459
|
-
results.push({ tool: id, path: absSkillPath, type: 'symlink', status: 'error', message: `symlink re-point failed (${relinkErr
|
|
466
|
+
results.push({ tool: id, path: absSkillPath, type: 'copy', status: 'installed', message: `symlink re-point unavailable (${errDetail(relinkErr)}); copied instead` });
|
|
467
|
+
} catch (copyErr: unknown) {
|
|
468
|
+
results.push({ tool: id, path: absSkillPath, type: 'symlink', status: 'error', message: `symlink re-point failed (${errDetail(relinkErr)}) and the copy fallback also failed: ${errDetail(copyErr)}` });
|
|
460
469
|
}
|
|
461
470
|
}
|
|
462
471
|
continue;
|
|
@@ -498,11 +507,11 @@ export function installSkill(toolIds: string[], opts: InstallOptions = {}): Inst
|
|
|
498
507
|
if (type === 'symlink') {
|
|
499
508
|
try {
|
|
500
509
|
fs.symlinkSync(source, absSkillPath, process.platform === 'win32' ? 'junction' : 'dir');
|
|
501
|
-
} catch (err:
|
|
510
|
+
} catch (err: unknown) {
|
|
502
511
|
// Windows without privilege, or cross-device: fall back to copy.
|
|
503
512
|
copyDir(source, absSkillPath);
|
|
504
513
|
upsertEntry(manifest, { tool: id, path: absSkillPath, type: 'copy', source, createdAt: now, ...(skillVersion ? { version: skillVersion } : {}) });
|
|
505
|
-
results.push({ tool: id, path: absSkillPath, type: 'copy', status: 'installed', message: `symlink unavailable (${err
|
|
514
|
+
results.push({ tool: id, path: absSkillPath, type: 'copy', status: 'installed', message: `symlink unavailable (${errDetail(err)}); copied instead` });
|
|
506
515
|
continue;
|
|
507
516
|
}
|
|
508
517
|
} else {
|
|
@@ -510,8 +519,8 @@ export function installSkill(toolIds: string[], opts: InstallOptions = {}): Inst
|
|
|
510
519
|
}
|
|
511
520
|
upsertEntry(manifest, { tool: id, path: absSkillPath, type, source, createdAt: now, ...(skillVersion ? { version: skillVersion } : {}) });
|
|
512
521
|
results.push({ tool: id, path: absSkillPath, type, status: 'installed' });
|
|
513
|
-
} catch (err:
|
|
514
|
-
results.push({ tool: id, path: absSkillPath, type, status: 'error', message:
|
|
522
|
+
} catch (err: unknown) {
|
|
523
|
+
results.push({ tool: id, path: absSkillPath, type, status: 'error', message: errDetail(err) });
|
|
515
524
|
}
|
|
516
525
|
}
|
|
517
526
|
|
|
@@ -575,8 +584,8 @@ export function uninstallSkill(toolIds?: string[], opts: InstallOptions = {}): U
|
|
|
575
584
|
if (isSymlinkPresent(skillPath)) fs.unlinkSync(skillPath);
|
|
576
585
|
else fs.rmSync(skillPath, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
|
577
586
|
results.push({ tool, path: skillPath, status: 'removed' });
|
|
578
|
-
} catch (err:
|
|
579
|
-
results.push({ tool, path: skillPath, status: 'error', message:
|
|
587
|
+
} catch (err: unknown) {
|
|
588
|
+
results.push({ tool, path: skillPath, status: 'error', message: errDetail(err) });
|
|
580
589
|
const e = manifest.entries.find(x => x.path === skillPath);
|
|
581
590
|
if (e) keep.push(e);
|
|
582
591
|
}
|
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 {
|