@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/dist/cli.mjs
CHANGED
|
@@ -1113,8 +1113,9 @@ function tryGetService(name, container = globalServiceContainer) {
|
|
|
1113
1113
|
return container.tryGet(name);
|
|
1114
1114
|
}
|
|
1115
1115
|
function tryGetServiceContainerFromCtx(ctx) {
|
|
1116
|
-
|
|
1117
|
-
|
|
1116
|
+
const container = ctx?.container;
|
|
1117
|
+
if (container && typeof container.get === "function" && typeof container.register === "function") {
|
|
1118
|
+
return container;
|
|
1118
1119
|
}
|
|
1119
1120
|
return globalServiceContainer;
|
|
1120
1121
|
}
|
|
@@ -1339,7 +1340,8 @@ var init_service_registry = __esm({
|
|
|
1339
1340
|
});
|
|
1340
1341
|
}
|
|
1341
1342
|
if (registration.instance && registration.instance.dispose) {
|
|
1342
|
-
|
|
1343
|
+
const disposal = Promise.resolve(registration.instance.dispose());
|
|
1344
|
+
await disposal.catch((err) => {
|
|
1343
1345
|
logger.warn(`[ServiceContainer] Error disposing service '${name}':`, err);
|
|
1344
1346
|
});
|
|
1345
1347
|
}
|
|
@@ -1372,7 +1374,8 @@ var init_service_registry = __esm({
|
|
|
1372
1374
|
});
|
|
1373
1375
|
}
|
|
1374
1376
|
if (registration.instance && registration.instance.dispose) {
|
|
1375
|
-
|
|
1377
|
+
const disposal = Promise.resolve(registration.instance.dispose());
|
|
1378
|
+
await disposal.catch((err) => {
|
|
1376
1379
|
logger.warn(`[ServiceContainer] Error disposing old service '${name}':`, err);
|
|
1377
1380
|
});
|
|
1378
1381
|
}
|
|
@@ -1935,10 +1938,11 @@ function extractUsage(model, rawUsage) {
|
|
|
1935
1938
|
}
|
|
1936
1939
|
const parsed = parseTokenUsage(rawUsage);
|
|
1937
1940
|
const tokens = calculateTotalTokens(parsed);
|
|
1938
|
-
|
|
1941
|
+
const usage = rawUsage;
|
|
1942
|
+
let cost = parsed.cost?.total ?? usage.cost?.total ?? 0;
|
|
1939
1943
|
if (cost === 0 && tokens > 0) {
|
|
1940
1944
|
try {
|
|
1941
|
-
const calculatedCost = calculateCost(model,
|
|
1945
|
+
const calculatedCost = calculateCost(model, usage);
|
|
1942
1946
|
cost = calculatedCost.total;
|
|
1943
1947
|
} catch {
|
|
1944
1948
|
}
|
|
@@ -2127,6 +2131,21 @@ var init_url_utils = __esm({
|
|
|
2127
2131
|
|
|
2128
2132
|
// src/utils/text-utils.ts
|
|
2129
2133
|
import * as path4 from "node:path";
|
|
2134
|
+
function extractToolResults(session) {
|
|
2135
|
+
const parts = [];
|
|
2136
|
+
for (const msg2 of session.messages) {
|
|
2137
|
+
if (msg2.role !== "toolResult") continue;
|
|
2138
|
+
const tr = msg2;
|
|
2139
|
+
if (tr.isError) continue;
|
|
2140
|
+
let text = (tr.content ?? []).map((c) => c && c.type === "text" ? String(c.text ?? "") : "").join("");
|
|
2141
|
+
text = text.replace(/\n-{3,}\n## Session URL Pool\n[\s\S]*$/, "").trimEnd();
|
|
2142
|
+
if (text.trim()) {
|
|
2143
|
+
parts.push(`### ${tr.toolName ?? "tool"}
|
|
2144
|
+
${text}`);
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
return parts.join("\n\n");
|
|
2148
|
+
}
|
|
2130
2149
|
function extractText(message) {
|
|
2131
2150
|
if (!message || typeof message !== "object") {
|
|
2132
2151
|
return "";
|
|
@@ -2795,6 +2814,7 @@ function saveConfig(config, scope = "local", cwd = process.cwd(), changedKeys) {
|
|
|
2795
2814
|
PI_RESEARCH_MAX_RETRIES: String(config.RESEARCHER_MAX_RETRIES),
|
|
2796
2815
|
PI_RESEARCH_RETRY_DELAY_MS: String(config.RESEARCHER_MAX_RETRY_DELAY_MS),
|
|
2797
2816
|
PI_RESEARCH_MAX_FAILED_RESEARCHERS: String(config.MAX_FAILED_RESEARCHERS ?? DEFAULTS.MAX_FAILED_RESEARCHERS),
|
|
2817
|
+
PI_RESEARCH_SINGLE_RESEARCHER: String(config.SINGLE_RESEARCHER ?? DEFAULTS.SINGLE_RESEARCHER),
|
|
2798
2818
|
PI_RESEARCH_HEALTH_CHECK_TIMEOUT_MS: String(config.HEALTH_CHECK_TIMEOUT_MS ?? DEFAULTS.HEALTH_CHECK_TIMEOUT_MS),
|
|
2799
2819
|
PI_RESEARCH_SEARCH_TIMEOUT_MS: String(config.SEARCH_TIMEOUT_MS),
|
|
2800
2820
|
PI_RESEARCH_TUI_REFRESH_DEBOUNCE_MS: String(config.TUI_REFRESH_DEBOUNCE_MS),
|
|
@@ -2976,6 +2996,7 @@ function createConfig(env, processEnv) {
|
|
|
2976
2996
|
RESEARCHER_MAX_RETRIES: parseEnvNumber(e, "PI_RESEARCH_MAX_RETRIES", DEFAULTS.RESEARCHER_MAX_RETRIES, 0, 5, true),
|
|
2977
2997
|
RESEARCHER_MAX_RETRY_DELAY_MS: parseEnvNumber(e, "PI_RESEARCH_RETRY_DELAY_MS", DEFAULTS.RESEARCHER_MAX_RETRY_DELAY_MS, 100, 1e4),
|
|
2978
2998
|
MAX_FAILED_RESEARCHERS: parseEnvNumber(e, "PI_RESEARCH_MAX_FAILED_RESEARCHERS", DEFAULTS.MAX_FAILED_RESEARCHERS, 1, 10, true),
|
|
2999
|
+
SINGLE_RESEARCHER: parseEnvBool(e, "PI_RESEARCH_SINGLE_RESEARCHER", DEFAULTS.SINGLE_RESEARCHER),
|
|
2979
3000
|
DEFAULT_RESEARCH_DEPTH: parseEnvNumber(e, "PI_RESEARCH_DEFAULT_RESEARCH_DEPTH", DEFAULTS.DEFAULT_RESEARCH_DEPTH, 0, 3, true),
|
|
2980
3001
|
QUICK_RESEARCH: parseEnvBool(e, "PI_RESEARCH_QUICK_RESEARCH", DEFAULTS.QUICK_RESEARCH),
|
|
2981
3002
|
MAX_SCRAPE_BATCHES: parseEnvNumber(e, "PI_RESEARCH_MAX_SCRAPE_BATCHES", DEFAULTS.MAX_SCRAPE_BATCHES, 0, 99, true),
|
|
@@ -3061,7 +3082,7 @@ function resetConfig() {
|
|
|
3061
3082
|
function validateConfig(config) {
|
|
3062
3083
|
const errors = [...Value.Errors(ConfigSchema, config)];
|
|
3063
3084
|
if (errors.length > 0) {
|
|
3064
|
-
throw new Error(`Invalid configuration: ${errors.map((e) => `${e.
|
|
3085
|
+
throw new Error(`Invalid configuration: ${errors.map((e) => `${e.instancePath || ""} ${e.message}`).join(", ")}`);
|
|
3065
3086
|
}
|
|
3066
3087
|
}
|
|
3067
3088
|
function parseEnvNumber(env, key, def, min, max, integer = false) {
|
|
@@ -3118,6 +3139,14 @@ var init_config = __esm({
|
|
|
3118
3139
|
RESEARCHER_MAX_RETRY_DELAY_MS: Type.Number({ minimum: 100, maximum: 1e4, default: 2e3 }),
|
|
3119
3140
|
/** Unique researcher failures that abort the entire run (default: 2, range: 1-10) */
|
|
3120
3141
|
MAX_FAILED_RESEARCHERS: Type.Number({ minimum: 1, maximum: 10, default: 2 }),
|
|
3142
|
+
/**
|
|
3143
|
+
* Run research with a SINGLE sequential researcher that carries all the queries, instead
|
|
3144
|
+
* of a team of parallel researchers. One session doing all the work keeps one growing,
|
|
3145
|
+
* fully-cached context (each turn re-reads the prior context as a cache hit), at the cost
|
|
3146
|
+
* of serial latency and a larger single context. Default: true (single, cache-friendly
|
|
3147
|
+
* researcher at every depth; Level 1 is always single regardless of this flag).
|
|
3148
|
+
*/
|
|
3149
|
+
SINGLE_RESEARCHER: Type.Boolean({ default: true }),
|
|
3121
3150
|
/** Target depth for recursive research (default: 1, range: 0-3; 0 = quick mode, requires QUICK_RESEARCH) */
|
|
3122
3151
|
DEFAULT_RESEARCH_DEPTH: Type.Number({ minimum: 0, maximum: 3, default: 1 }),
|
|
3123
3152
|
/** Opt-in gate for depth-0 (quick mode) research. When false (default), depth 0 is invisible to the agent-facing tool and any depth-0 default resolves to 1 — upstream behavior. When true, agents can pass depth: 0 and DEFAULT_RESEARCH_DEPTH=0 is honored. */
|
|
@@ -4411,13 +4440,14 @@ async function initializeDawnWebGPU() {
|
|
|
4411
4440
|
try {
|
|
4412
4441
|
const adapter = await logger.runCapturingStderr(async () => {
|
|
4413
4442
|
const { create, globals } = await import("webgpu");
|
|
4443
|
+
const gpu = create([]);
|
|
4414
4444
|
Object.assign(globalThis, globals);
|
|
4415
4445
|
Object.defineProperty(globalThis, "navigator", {
|
|
4416
|
-
value: { gpu
|
|
4446
|
+
value: { gpu },
|
|
4417
4447
|
writable: true,
|
|
4418
4448
|
configurable: true
|
|
4419
4449
|
});
|
|
4420
|
-
return await
|
|
4450
|
+
return await gpu.requestAdapter({ powerPreference: "high-performance" });
|
|
4421
4451
|
});
|
|
4422
4452
|
if (!adapter) {
|
|
4423
4453
|
logger.warn("[embedder] No WebGPU adapter available \u2014 using CPU.");
|
|
@@ -4425,7 +4455,7 @@ async function initializeDawnWebGPU() {
|
|
|
4425
4455
|
}
|
|
4426
4456
|
const info = adapter.info ?? {};
|
|
4427
4457
|
const haystack = [info.vendor, info.architecture, info.device, info.description].filter(Boolean).join(" ").toLowerCase();
|
|
4428
|
-
if (adapter.isFallbackAdapter === true || SOFTWARE_ADAPTER_PATTERNS.some((p) => haystack.includes(p))) {
|
|
4458
|
+
if (adapter.info?.isFallbackAdapter === true || SOFTWARE_ADAPTER_PATTERNS.some((p) => haystack.includes(p))) {
|
|
4429
4459
|
logger.warn(
|
|
4430
4460
|
`[embedder] WebGPU adapter is software/paravirtual (${haystack || "fallback"}) \u2014 Dawn would crash on compute; using CPU.`
|
|
4431
4461
|
);
|
|
@@ -4760,7 +4790,8 @@ async function handleWebGPULoadError(loadErr, pipeline, stateManager, gpuLockHel
|
|
|
4760
4790
|
}
|
|
4761
4791
|
if (pipeline) {
|
|
4762
4792
|
try {
|
|
4763
|
-
|
|
4793
|
+
const disposable = pipeline;
|
|
4794
|
+
if (typeof disposable.dispose === "function") await disposable.dispose();
|
|
4764
4795
|
} catch (err) {
|
|
4765
4796
|
logger.warn("[embedder] Error disposing pipeline:", err);
|
|
4766
4797
|
}
|
|
@@ -4784,7 +4815,8 @@ async function handleWebGPUWarmupError(warmupErr, pipeline, stateManager, gpuLoc
|
|
|
4784
4815
|
logger.debug("[embedder] Warmup error details:", warmupErr.message);
|
|
4785
4816
|
if (pipeline) {
|
|
4786
4817
|
try {
|
|
4787
|
-
|
|
4818
|
+
const disposable = pipeline;
|
|
4819
|
+
if (typeof disposable.dispose === "function") await disposable.dispose();
|
|
4788
4820
|
} catch (err) {
|
|
4789
4821
|
logger.warn("[embedder] Error disposing pipeline:", err);
|
|
4790
4822
|
}
|
|
@@ -4798,7 +4830,8 @@ async function handleWebGPUWarmupError(warmupErr, pipeline, stateManager, gpuLoc
|
|
|
4798
4830
|
logger.error("[embedder] CPU fallback pipeline warmup failed:", cpuWarmupErr);
|
|
4799
4831
|
if (cpuPipeline) {
|
|
4800
4832
|
try {
|
|
4801
|
-
|
|
4833
|
+
const cpuDisposable = cpuPipeline;
|
|
4834
|
+
if (typeof cpuDisposable.dispose === "function") await cpuDisposable.dispose();
|
|
4802
4835
|
} catch (err) {
|
|
4803
4836
|
logger.warn("[embedder] Error disposing fallback CPU pipeline:", err);
|
|
4804
4837
|
}
|
|
@@ -5229,11 +5262,14 @@ var init_embedder = __esm({
|
|
|
5229
5262
|
this.pipeline = result.pipeline ?? null;
|
|
5230
5263
|
this.device = "cpu";
|
|
5231
5264
|
this.gpuLockHeld = false;
|
|
5232
|
-
dummy = result.dummy;
|
|
5265
|
+
dummy = result.dummy ?? null;
|
|
5233
5266
|
} else {
|
|
5234
5267
|
throw warmupErr;
|
|
5235
5268
|
}
|
|
5236
5269
|
}
|
|
5270
|
+
if (dummy === null) {
|
|
5271
|
+
throw new Error("[embedder] warmup completed without a dummy tensor; dimension cannot be determined");
|
|
5272
|
+
}
|
|
5237
5273
|
this.dimension = dummy.dims[dummy.dims.length - 1] ?? null;
|
|
5238
5274
|
await releaseGpuLock(this.stateManager, this.gpuLockHeld);
|
|
5239
5275
|
this.gpuLockHeld = false;
|
|
@@ -5243,7 +5279,8 @@ var init_embedder = __esm({
|
|
|
5243
5279
|
this.gpuLockHeld = false;
|
|
5244
5280
|
if (this.pipeline) {
|
|
5245
5281
|
try {
|
|
5246
|
-
|
|
5282
|
+
const disposable = this.pipeline;
|
|
5283
|
+
if (typeof disposable.dispose === "function") await disposable.dispose();
|
|
5247
5284
|
} catch (err2) {
|
|
5248
5285
|
logger.warn("[embedder] Error disposing pipeline:", err2);
|
|
5249
5286
|
}
|
|
@@ -5427,7 +5464,8 @@ var init_embedder = __esm({
|
|
|
5427
5464
|
}
|
|
5428
5465
|
if (this.pipeline) {
|
|
5429
5466
|
try {
|
|
5430
|
-
|
|
5467
|
+
const disposable = this.pipeline;
|
|
5468
|
+
if (typeof disposable.dispose === "function") await disposable.dispose();
|
|
5431
5469
|
} catch (err) {
|
|
5432
5470
|
logger.warn("[embedder] Error disposing pipeline:", err);
|
|
5433
5471
|
}
|
|
@@ -5506,8 +5544,9 @@ var init_embedder = __esm({
|
|
|
5506
5544
|
this.pipeline = null;
|
|
5507
5545
|
} else {
|
|
5508
5546
|
try {
|
|
5509
|
-
|
|
5510
|
-
|
|
5547
|
+
const disposable = this.pipeline;
|
|
5548
|
+
if (typeof disposable.dispose === "function") {
|
|
5549
|
+
await disposable.dispose();
|
|
5511
5550
|
}
|
|
5512
5551
|
} catch (err) {
|
|
5513
5552
|
logger.warn("[embedder] Error during pipeline dispose:", err);
|
|
@@ -8069,9 +8108,10 @@ var init_store = __esm({
|
|
|
8069
8108
|
const isVersionMismatch = storedVersion !== CURRENT_SCHEMA_VERSION;
|
|
8070
8109
|
if (!isModelMismatch) {
|
|
8071
8110
|
const vectorField = schema.fields.find((f) => f.name === "vector");
|
|
8072
|
-
|
|
8073
|
-
|
|
8074
|
-
|
|
8111
|
+
const vectorType = vectorField?.type;
|
|
8112
|
+
if (vectorField && vectorType?.constructor?.name === "FixedSizeList") {
|
|
8113
|
+
const dim = vectorType.listSize;
|
|
8114
|
+
if (typeof dim === "number" && this.embedder.getDimension() === null) {
|
|
8075
8115
|
this.embedder.setDimension(dim);
|
|
8076
8116
|
logger.debug(`[store] Extracted dimension ${dim} from existing table schema`);
|
|
8077
8117
|
}
|
|
@@ -9554,14 +9594,15 @@ var init_knowledge_store_service = __esm({
|
|
|
9554
9594
|
while (this._disposalPromise) {
|
|
9555
9595
|
await this._disposalPromise;
|
|
9556
9596
|
}
|
|
9557
|
-
const
|
|
9597
|
+
const initCtx = ctx;
|
|
9598
|
+
const newCwd = initCtx?.cwd || this._cwd;
|
|
9558
9599
|
if ((this.lifecycle === "initialized" /* INITIALIZED */ || this.lifecycle === "disabled" /* DISABLED */) && this._cwd === newCwd) {
|
|
9559
|
-
const liveConfig =
|
|
9600
|
+
const liveConfig = initCtx?.config || getConfig(this._cwd);
|
|
9560
9601
|
const liveMode = liveConfig.KNOWLEDGE_STORE_MODE;
|
|
9561
9602
|
const liveRetrieval = liveConfig.KNOWLEDGE_STORE_RETRIEVAL;
|
|
9562
9603
|
const reviveFromMode = this.lifecycle === "disabled" /* DISABLED */ && this._disabledReason === "mode" && liveMode !== "none";
|
|
9563
|
-
const modeChanged = this.lifecycle === "initialized" /* INITIALIZED */ &&
|
|
9564
|
-
const retrievalChanged = this.lifecycle === "initialized" /* INITIALIZED */ &&
|
|
9604
|
+
const modeChanged = this.lifecycle === "initialized" /* INITIALIZED */ && initCtx?.config !== void 0 && this._initializedMode !== void 0 && this._initializedMode !== initCtx.config.KNOWLEDGE_STORE_MODE;
|
|
9605
|
+
const retrievalChanged = this.lifecycle === "initialized" /* INITIALIZED */ && initCtx?.config !== void 0 && this._initializedRetrieval !== void 0 && this._initializedRetrieval !== initCtx.config.KNOWLEDGE_STORE_RETRIEVAL;
|
|
9565
9606
|
if (!reviveFromMode && !modeChanged && !retrievalChanged) {
|
|
9566
9607
|
return;
|
|
9567
9608
|
}
|
|
@@ -9597,8 +9638,8 @@ var init_knowledge_store_service = __esm({
|
|
|
9597
9638
|
let initPromise = null;
|
|
9598
9639
|
initPromise = (async () => {
|
|
9599
9640
|
try {
|
|
9600
|
-
this._cwd =
|
|
9601
|
-
const config =
|
|
9641
|
+
this._cwd = initCtx?.cwd || this._cwd;
|
|
9642
|
+
const config = initCtx?.config || getConfig(this._cwd);
|
|
9602
9643
|
this._initializedMode = config.KNOWLEDGE_STORE_MODE;
|
|
9603
9644
|
this._initializedRetrieval = config.KNOWLEDGE_STORE_RETRIEVAL;
|
|
9604
9645
|
const embedderFactory = () => getEmbedder(config);
|
|
@@ -10691,7 +10732,7 @@ function createResearchKnowledgeSearchTool(iface) {
|
|
|
10691
10732
|
// Cache/session-affinity hint only (keeps repeated calls on the same warmed
|
|
10692
10733
|
// replica) — same resolution research-config.ts uses, since this tool has no
|
|
10693
10734
|
// researchId of its own to key on. ctx.sessionId is read defensively: it is
|
|
10694
|
-
// not on every host's ExtensionContext shape, hence the
|
|
10735
|
+
// not on every host's ExtensionContext shape, hence the cast.
|
|
10695
10736
|
ctx.sessionId || ctx.sessionManager?.getSessionId()
|
|
10696
10737
|
);
|
|
10697
10738
|
const durationMs = Date.now() - startTime;
|
|
@@ -10784,6 +10825,10 @@ import * as fs17 from "node:fs";
|
|
|
10784
10825
|
import * as os7 from "node:os";
|
|
10785
10826
|
import * as path19 from "node:path";
|
|
10786
10827
|
import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
10828
|
+
function errDetail(err) {
|
|
10829
|
+
const e = err;
|
|
10830
|
+
return e?.code ?? e?.message ?? String(err);
|
|
10831
|
+
}
|
|
10787
10832
|
function readSkillVersion(sourceDir) {
|
|
10788
10833
|
try {
|
|
10789
10834
|
const md = fs17.readFileSync(path19.join(sourceDir, "SKILL.md"), "utf-8");
|
|
@@ -10958,9 +11003,9 @@ function installSkill(toolIds, opts = {}) {
|
|
|
10958
11003
|
try {
|
|
10959
11004
|
copyDir(source, absSkillPath);
|
|
10960
11005
|
upsertEntry(manifest, { tool: id, path: absSkillPath, type: "copy", source, createdAt: now, ...skillVersion ? { version: skillVersion } : {} });
|
|
10961
|
-
results.push({ tool: id, path: absSkillPath, type: "copy", status: "installed", message: `symlink re-point unavailable (${relinkErr
|
|
11006
|
+
results.push({ tool: id, path: absSkillPath, type: "copy", status: "installed", message: `symlink re-point unavailable (${errDetail(relinkErr)}); copied instead` });
|
|
10962
11007
|
} catch (copyErr) {
|
|
10963
|
-
results.push({ tool: id, path: absSkillPath, type: "symlink", status: "error", message: `symlink re-point failed (${relinkErr
|
|
11008
|
+
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)}` });
|
|
10964
11009
|
}
|
|
10965
11010
|
}
|
|
10966
11011
|
continue;
|
|
@@ -10993,7 +11038,7 @@ function installSkill(toolIds, opts = {}) {
|
|
|
10993
11038
|
} catch (err) {
|
|
10994
11039
|
copyDir(source, absSkillPath);
|
|
10995
11040
|
upsertEntry(manifest, { tool: id, path: absSkillPath, type: "copy", source, createdAt: now, ...skillVersion ? { version: skillVersion } : {} });
|
|
10996
|
-
results.push({ tool: id, path: absSkillPath, type: "copy", status: "installed", message: `symlink unavailable (${err
|
|
11041
|
+
results.push({ tool: id, path: absSkillPath, type: "copy", status: "installed", message: `symlink unavailable (${errDetail(err)}); copied instead` });
|
|
10997
11042
|
continue;
|
|
10998
11043
|
}
|
|
10999
11044
|
} else {
|
|
@@ -11002,7 +11047,7 @@ function installSkill(toolIds, opts = {}) {
|
|
|
11002
11047
|
upsertEntry(manifest, { tool: id, path: absSkillPath, type, source, createdAt: now, ...skillVersion ? { version: skillVersion } : {} });
|
|
11003
11048
|
results.push({ tool: id, path: absSkillPath, type, status: "installed" });
|
|
11004
11049
|
} catch (err) {
|
|
11005
|
-
results.push({ tool: id, path: absSkillPath, type, status: "error", message:
|
|
11050
|
+
results.push({ tool: id, path: absSkillPath, type, status: "error", message: errDetail(err) });
|
|
11006
11051
|
}
|
|
11007
11052
|
}
|
|
11008
11053
|
if (!opts.dryRun) writeManifest(manifest, opts);
|
|
@@ -11048,7 +11093,7 @@ function uninstallSkill(toolIds, opts = {}) {
|
|
|
11048
11093
|
else fs17.rmSync(skillPath, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
|
11049
11094
|
results.push({ tool, path: skillPath, status: "removed" });
|
|
11050
11095
|
} catch (err) {
|
|
11051
|
-
results.push({ tool, path: skillPath, status: "error", message:
|
|
11096
|
+
results.push({ tool, path: skillPath, status: "error", message: errDetail(err) });
|
|
11052
11097
|
const e = manifest.entries.find((x) => x.path === skillPath);
|
|
11053
11098
|
if (e) keep.push(e);
|
|
11054
11099
|
}
|
|
@@ -11681,18 +11726,18 @@ var COVERAGE_DIGEST_TERMINATOR = "END COVERAGE DIGEST";
|
|
|
11681
11726
|
var DIGEST_HEAD_WINDOW_CHARS = 600;
|
|
11682
11727
|
var MAX_DIGEST_CHARS = 2400;
|
|
11683
11728
|
var MAX_DIGEST_BLOCK_CHARS = 8e3;
|
|
11684
|
-
var RESEARCHER_DIGEST_SECTION = `Your
|
|
11729
|
+
var RESEARCHER_DIGEST_SECTION = `Your final message is the COVERAGE DIGEST block. Emit it and stop \u2014 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.
|
|
11685
11730
|
|
|
11686
|
-
###
|
|
11731
|
+
### COVERAGE DIGEST (mandatory)
|
|
11687
11732
|
|
|
11688
|
-
|
|
11733
|
+
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 \u2014 so anything you leave out of it is invisible to every decision after the first.
|
|
11689
11734
|
|
|
11690
11735
|
${COVERAGE_DIGEST_HEADER}
|
|
11691
11736
|
Goal: [your assigned goal, restated in one line]
|
|
11692
11737
|
Covered: [the specific topics you actually established from sources, separated by semicolons \u2014 be concrete, name the things you found out, not the areas you looked at]
|
|
11693
11738
|
Unsubstantiated: [claims you searched for but could not ground in any source; write "none" if there are none]
|
|
11694
11739
|
Gaps: [what a follow-up researcher would still need to investigate on this goal; write "none" if your goal is fully covered]
|
|
11695
|
-
Sources: [the number of
|
|
11740
|
+
Sources: [the number of URLs you scraped]
|
|
11696
11741
|
${COVERAGE_DIGEST_TERMINATOR}
|
|
11697
11742
|
|
|
11698
11743
|
Rules for the digest:
|
|
@@ -11700,8 +11745,6 @@ Rules for the digest:
|
|
|
11700
11745
|
- 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.
|
|
11701
11746
|
- Write both delimiter lines exactly, in capitals, each on its own line.
|
|
11702
11747
|
|
|
11703
|
-
### Part 2 \u2014 Report body
|
|
11704
|
-
|
|
11705
11748
|
`;
|
|
11706
11749
|
function delimiterRegex(word) {
|
|
11707
11750
|
return new RegExp(`(^|\\n)([ \\t]*(?:#{1,6}[ \\t]*|>[ \\t]*|\\*\\*[ \\t]*)?)${word}\\b`, "i");
|
|
@@ -11731,6 +11774,14 @@ function splitCoverageDigest(report) {
|
|
|
11731
11774
|
if (!body) return { digest: "", body: report };
|
|
11732
11775
|
return { digest, body };
|
|
11733
11776
|
}
|
|
11777
|
+
function buildFallbackDigest(goal, scrapeCount) {
|
|
11778
|
+
const topic = goal.trim() || "unknown \u2014 no goal recorded";
|
|
11779
|
+
return [
|
|
11780
|
+
`Covered: ${topic} (no coverage digest emitted; goal restated)`,
|
|
11781
|
+
`Gaps: unknown \u2014 this researcher emitted no coverage digest`,
|
|
11782
|
+
`Sources: ${scrapeCount}`
|
|
11783
|
+
].join("\n");
|
|
11784
|
+
}
|
|
11734
11785
|
function deriveCoverageDigest(body) {
|
|
11735
11786
|
const citationCount = parseCitations(body).length;
|
|
11736
11787
|
const citedIdx = lastCitedLinksHeaderIndex(body);
|
|
@@ -11791,6 +11842,9 @@ init_constants();
|
|
|
11791
11842
|
function getTeamSize(complexity) {
|
|
11792
11843
|
return complexity === 1 ? MAX_TEAM_SIZE_LEVEL_1 : complexity === 2 ? MAX_TEAM_SIZE_LEVEL_2 : MAX_TEAM_SIZE_LEVEL_3;
|
|
11793
11844
|
}
|
|
11845
|
+
function effectiveSingleResearcher(complexity, singleResearcher) {
|
|
11846
|
+
return complexity === 1 ? true : singleResearcher;
|
|
11847
|
+
}
|
|
11794
11848
|
function getQueryBudget(complexity) {
|
|
11795
11849
|
return complexity === 1 ? MAX_QUERIES_PER_RESEARCHER_LEVEL_1 : complexity === 2 ? MAX_QUERIES_PER_RESEARCHER_LEVEL_2 : MAX_QUERIES_PER_RESEARCHER_LEVEL_3;
|
|
11796
11850
|
}
|
|
@@ -11799,7 +11853,7 @@ function getMaxRounds(complexity) {
|
|
|
11799
11853
|
}
|
|
11800
11854
|
function getComplexityGuidance(complexity, maxTeamSize, queryBudget) {
|
|
11801
11855
|
if (complexity === 1) {
|
|
11802
|
-
return "**Complexity: Level 1 (Normal)**. Conduct a thorough, well-rounded investigation of the topic covering the primary angles with adequate citations. **Plan ONLY Round 1** \u2014 a single comprehensive round. **
|
|
11856
|
+
return "**Complexity: Level 1 (Normal)**. Conduct a thorough, well-rounded investigation of the topic covering the primary angles with adequate citations. **Plan ONLY Round 1** \u2014 a single comprehensive round. **Use ONE researcher** \u2014 one focused researcher handles normal-complexity queries. This is a ONE-SHOT effort: plan Round 1 as if it is the only round, because it should be. Only Level 2 or Level 3 research should involve multiple rounds.";
|
|
11803
11857
|
} else if (complexity === 2) {
|
|
11804
11858
|
return `**Complexity: Level 2 (Deep)**. **ONLY for HIGH/EXTREME research needs.** Level 2 should be reserved for topics that clearly require deeper investigation than a single comprehensive round can provide. **Plan ONLY Round 1** \u2014 a thorough, well-structured first round. Subsequent rounds are reactive and only delegated when Round 1 findings reveal clear gaps that warrant deeper or broader coverage. Do not pre-plan multiple rounds; delegate follow-ups only when Round 1 demonstrates genuine need.
|
|
11805
11859
|
|
|
@@ -11821,7 +11875,7 @@ function getEvaluatorComplexityGuidance(complexity, researchRounds) {
|
|
|
11821
11875
|
- **SYNTHESIZE when**: The primary topic is covered from multiple angles with evidence from diverse sources and no significant gaps remain that would prevent a complete answer.
|
|
11822
11876
|
- **DELEGATE when**: Coverage is incomplete, important angles are missing, or additional sources would meaningfully strengthen the findings.
|
|
11823
11877
|
|
|
11824
|
-
**DEFAULT PATH**: Synthesize after Round 1 if the researcher produced solid coverage of the core topic. **Level 1 should almost always be a single round** \u2014 only delegate a second round when Round 1 clearly missed important angles or lacks source diversity.
|
|
11878
|
+
**DEFAULT PATH**: Synthesize after Round 1 if the researcher produced solid coverage of the core topic. **Level 1 should almost always be a single round** \u2014 only delegate a second round when Round 1 clearly missed important angles or lacks source diversity. **Use ONE researcher** for follow-up rounds. Level 2 research escalation should be reserved for truly high/extreme research needs only.`;
|
|
11825
11879
|
} else if (complexity === 2) {
|
|
11826
11880
|
return `**Level 2 (Deep)** - Thorough, multi-phase investigation with comprehensive citations.
|
|
11827
11881
|
|
|
@@ -11965,7 +12019,7 @@ function parseJsonPlan(text) {
|
|
|
11965
12019
|
const coerced = Value3.Convert(ResearchPlanSchema, candidate);
|
|
11966
12020
|
if (!Value3.Check(ResearchPlanSchema, coerced)) {
|
|
11967
12021
|
const errors = [...Value3.Errors(ResearchPlanSchema, coerced)];
|
|
11968
|
-
const errorMsg = errors.map((e) => `${e.
|
|
12022
|
+
const errorMsg = errors.map((e) => `${e.instancePath || ""} ${e.message}`).join(", ");
|
|
11969
12023
|
throw new Error(`Plan validation failed: ${errorMsg}`);
|
|
11970
12024
|
}
|
|
11971
12025
|
const plan = coerced;
|
|
@@ -11996,11 +12050,12 @@ function buildFallbackCoordinatorPlan(serviceName, _rawText, query) {
|
|
|
11996
12050
|
allQueries: queries
|
|
11997
12051
|
};
|
|
11998
12052
|
}
|
|
11999
|
-
function capResearcherQueries(plan, complexity, serviceName) {
|
|
12000
|
-
const
|
|
12053
|
+
function capResearcherQueries(plan, complexity, serviceName, singleResearcher = false) {
|
|
12054
|
+
const perResearcher = getQueryBudget(complexity);
|
|
12055
|
+
const budget = singleResearcher ? getTeamSize(complexity) * perResearcher : perResearcher;
|
|
12001
12056
|
const ROUND_HARD_CAP = complexity === 1 ? 20 : complexity === 2 ? 45 : 100;
|
|
12002
12057
|
if (!plan.researchers) return plan;
|
|
12003
|
-
const maxTeam = getTeamSize(complexity);
|
|
12058
|
+
const maxTeam = singleResearcher ? 1 : getTeamSize(complexity);
|
|
12004
12059
|
plan.researchers = plan.researchers.filter((r) => r && typeof r === "object" && Array.isArray(r.queries) && r.queries.length > 0).slice(0, maxTeam).map((r) => {
|
|
12005
12060
|
const normalized = { ...r, id: String(r.id) };
|
|
12006
12061
|
if (normalized.queries.length > budget) {
|
|
@@ -12227,8 +12282,8 @@ var PlanningService = class {
|
|
|
12227
12282
|
buildFallbackCoordinatorPlan(rawText, query) {
|
|
12228
12283
|
return buildFallbackCoordinatorPlan("PlanningService", rawText, query);
|
|
12229
12284
|
}
|
|
12230
|
-
capResearcherQueries(plan, complexity, serviceName) {
|
|
12231
|
-
return capResearcherQueries(plan, complexity, serviceName);
|
|
12285
|
+
capResearcherQueries(plan, complexity, serviceName, singleResearcher = false) {
|
|
12286
|
+
return capResearcherQueries(plan, complexity, serviceName, singleResearcher);
|
|
12232
12287
|
}
|
|
12233
12288
|
generateResearchers(plan, query, complexity) {
|
|
12234
12289
|
return generateResearchers(plan, query, complexity);
|
|
@@ -12254,7 +12309,9 @@ var PlanningService = class {
|
|
|
12254
12309
|
const promptTemplate = loadPrompt("system-coordinator");
|
|
12255
12310
|
const maxTeamSize = this.getTeamSize(complexity);
|
|
12256
12311
|
const queryBudget = this.getQueryBudget(complexity);
|
|
12257
|
-
const
|
|
12312
|
+
const singleResearcher = effectiveSingleResearcher(complexity, config.SINGLE_RESEARCHER);
|
|
12313
|
+
const teamSizeGuidance = singleResearcher ? "Plan **exactly ONE researcher** that covers the entire scope, carrying all the queries. Do NOT split the work across multiple researchers \u2014 one agent doing all the work keeps a single growing, fully-cached context." : `**Team size**: Plan between **1 and ${maxTeamSize} researchers**. A **single researcher is a complete, valid plan** \u2014 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.)`;
|
|
12314
|
+
const complexityGuidance = singleResearcher ? `**Complexity: ${complexity === 1 ? "Level 1 (Normal)" : complexity === 2 ? "Level 2 (Deep)" : "Level 3 (Ultra)"}** \u2014 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.` : this.getComplexityGuidance(complexity, maxTeamSize, queryBudget);
|
|
12258
12315
|
let steeringSection = "";
|
|
12259
12316
|
if (steeringMessages && steeringMessages.length > 0) {
|
|
12260
12317
|
steeringSection = "\n\n### ADDITIONAL USER GUIDANCE (Apply these rules and instructions to your plan and decisions)\n" + steeringMessages.map((m) => `- ${m}`).join("\n");
|
|
@@ -12268,6 +12325,7 @@ The following tools are DISABLED for this session: ${options.excludeTools.join("
|
|
|
12268
12325
|
root_query: query,
|
|
12269
12326
|
additional_considerations: steeringSection,
|
|
12270
12327
|
complexity_label: complexity === 1 ? "Level 1 (Normal)" : complexity === 2 ? "Level 2 (Deep)" : "Level 3 (Ultra)",
|
|
12328
|
+
team_size_guidance: teamSizeGuidance,
|
|
12271
12329
|
max_team_size: maxTeamSize,
|
|
12272
12330
|
query_budget: queryBudget,
|
|
12273
12331
|
complexity_guidance: complexityGuidance,
|
|
@@ -12366,10 +12424,10 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
|
|
|
12366
12424
|
logger.warn("[PlanningService] Failed to generate valid plan, building fallback");
|
|
12367
12425
|
plan = this.buildFallbackCoordinatorPlan(responseText, query);
|
|
12368
12426
|
}
|
|
12369
|
-
plan = this.capResearcherQueries(plan, complexity, this.name);
|
|
12427
|
+
plan = this.capResearcherQueries(plan, complexity, this.name, singleResearcher);
|
|
12370
12428
|
if (!plan.researchers || plan.researchers.length === 0) {
|
|
12371
12429
|
logger.warn("[PlanningService] Coordinator produced no runnable researchers (empty queries); using single-researcher fallback");
|
|
12372
|
-
plan = this.capResearcherQueries(this.buildFallbackCoordinatorPlan(responseText, query), complexity, this.name);
|
|
12430
|
+
plan = this.capResearcherQueries(this.buildFallbackCoordinatorPlan(responseText, query), complexity, this.name, singleResearcher);
|
|
12373
12431
|
}
|
|
12374
12432
|
plan.action = "delegate";
|
|
12375
12433
|
this.currentPlans.set(sessionId, plan);
|
|
@@ -12386,7 +12444,7 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
|
|
|
12386
12444
|
}
|
|
12387
12445
|
logger.warn("[PlanningService] Coordinator call failed transiently; building fallback plan so the run can proceed");
|
|
12388
12446
|
let plan = this.buildFallbackCoordinatorPlan("", query);
|
|
12389
|
-
plan = this.capResearcherQueries(plan, complexity, this.name);
|
|
12447
|
+
plan = this.capResearcherQueries(plan, complexity, this.name, singleResearcher);
|
|
12390
12448
|
if (plan.action !== "synthesize") {
|
|
12391
12449
|
plan.action = "delegate";
|
|
12392
12450
|
}
|
|
@@ -12421,7 +12479,8 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
|
|
|
12421
12479
|
logger.log(`[PlanningService] ${isRouter ? "Routing after" : "Synthesizing at"} Round ${round} for: "${query}"`);
|
|
12422
12480
|
const config = options.config ?? getConfig(options.cwd);
|
|
12423
12481
|
const promptTemplate = loadPrompt(isRouter ? "system-lead-router" : "system-lead-synthesizer");
|
|
12424
|
-
const
|
|
12482
|
+
const singleResearcher = effectiveSingleResearcher(complexity, config.SINGLE_RESEARCHER);
|
|
12483
|
+
const maxTeamSize = singleResearcher ? 1 : this.getTeamSize(complexity);
|
|
12425
12484
|
const queryBudget = this.getQueryBudget(complexity);
|
|
12426
12485
|
const maxRounds = options.maxRounds ?? getMaxRounds(complexity);
|
|
12427
12486
|
const researchRounds = Math.max(1, maxRounds - 1);
|
|
@@ -12576,13 +12635,14 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
|
|
|
12576
12635
|
finalPlan.action = "delegate";
|
|
12577
12636
|
}
|
|
12578
12637
|
if (finalPlan.action === "delegate") {
|
|
12579
|
-
const capped = this.capResearcherQueries(finalPlan, complexity, this.name);
|
|
12638
|
+
const capped = this.capResearcherQueries(finalPlan, complexity, this.name, singleResearcher);
|
|
12580
12639
|
if (!capped.researchers || capped.researchers.length === 0) {
|
|
12581
12640
|
if (previousPlan?.researchers && previousPlan.researchers.length > 0) {
|
|
12582
12641
|
const fallback2 = this.capResearcherQueries(
|
|
12583
12642
|
{ action: "delegate", content: "", researchers: previousPlan.researchers },
|
|
12584
12643
|
complexity,
|
|
12585
|
-
this.name
|
|
12644
|
+
this.name,
|
|
12645
|
+
singleResearcher
|
|
12586
12646
|
);
|
|
12587
12647
|
if (fallback2.researchers && fallback2.researchers.length > 0) {
|
|
12588
12648
|
logger.warn("[PlanningService] Evaluator delegated zero runnable researchers; continuing the prior agenda rather than synthesizing early");
|
|
@@ -12611,7 +12671,8 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
|
|
|
12611
12671
|
const fallback2 = this.capResearcherQueries(
|
|
12612
12672
|
{ action: "delegate", content: "", researchers: previousPlan.researchers },
|
|
12613
12673
|
complexity,
|
|
12614
|
-
this.name
|
|
12674
|
+
this.name,
|
|
12675
|
+
singleResearcher
|
|
12615
12676
|
);
|
|
12616
12677
|
this.currentPlans.set(sessionId, fallback2);
|
|
12617
12678
|
return fallback2;
|
|
@@ -14588,6 +14649,8 @@ var BrowserTaskScheduler = class {
|
|
|
14588
14649
|
}
|
|
14589
14650
|
try {
|
|
14590
14651
|
return await executePoolTaskWithDeathBackstop(
|
|
14652
|
+
// poolifier pools are Response = unknown by default; the worker
|
|
14653
|
+
// settles search tasks with this in-band shape.
|
|
14591
14654
|
() => pool.execute({ type: "search", query, queuedAt: startTime, taskTimeoutMs: timeoutMs }),
|
|
14592
14655
|
timeoutMs,
|
|
14593
14656
|
"Search"
|
|
@@ -14676,6 +14739,8 @@ var BrowserTaskScheduler = class {
|
|
|
14676
14739
|
}
|
|
14677
14740
|
try {
|
|
14678
14741
|
return await executePoolTaskWithDeathBackstop(
|
|
14742
|
+
// poolifier pools are Response = unknown by default; the worker
|
|
14743
|
+
// settles scrape tasks with the in-band ScrapeResult shape.
|
|
14679
14744
|
() => pool.execute({ type: "scrape", url, queuedAt: startTime, taskTimeoutMs: timeoutMs }),
|
|
14680
14745
|
timeoutMs,
|
|
14681
14746
|
"Scrape"
|
|
@@ -14867,7 +14932,7 @@ var BrowserTaskScheduler = class {
|
|
|
14867
14932
|
if (this.workerPoolManager) {
|
|
14868
14933
|
const pool = this.workerPoolManager.getPool();
|
|
14869
14934
|
if (pool && pool.workerNodes) {
|
|
14870
|
-
const workerPids = pool.workerNodes.map((n) => n.worker?.process?.pid).filter(
|
|
14935
|
+
const workerPids = pool.workerNodes.map((n) => n.worker?.process?.pid).filter((pid) => pid !== void 0);
|
|
14871
14936
|
if (workerPids.length > 0) {
|
|
14872
14937
|
targetBrowserPids = await getBrowserPidsForWorkers(workerPids);
|
|
14873
14938
|
}
|
|
@@ -15173,8 +15238,9 @@ var SchedulerFactoryService = class {
|
|
|
15173
15238
|
lifecycle = "uninitialized" /* UNINITIALIZED */;
|
|
15174
15239
|
container = getServiceContainer();
|
|
15175
15240
|
async initialize(ctx) {
|
|
15176
|
-
|
|
15177
|
-
|
|
15241
|
+
const initCtx = ctx;
|
|
15242
|
+
if (initCtx?.container) {
|
|
15243
|
+
this.container = initCtx.container;
|
|
15178
15244
|
}
|
|
15179
15245
|
this.lifecycle = "initialized" /* INITIALIZED */;
|
|
15180
15246
|
}
|
|
@@ -15218,7 +15284,7 @@ import * as path12 from "node:path";
|
|
|
15218
15284
|
import * as crypto7 from "node:crypto";
|
|
15219
15285
|
import process2 from "node:process";
|
|
15220
15286
|
|
|
15221
|
-
// src/
|
|
15287
|
+
// src/types/state-types.ts
|
|
15222
15288
|
import { Type as Type3 } from "typebox";
|
|
15223
15289
|
var CURRENT_STATE_VERSION = 1;
|
|
15224
15290
|
var SessionInfoSchema = Type3.Object({
|
|
@@ -16720,8 +16786,9 @@ var StateValidator = class {
|
|
|
16720
16786
|
if (!Value4.Check(SingletonStateSchema, coerced)) {
|
|
16721
16787
|
const errors = [...Value4.Errors(SingletonStateSchema, coerced)];
|
|
16722
16788
|
const errorMsg = errors.map((e) => {
|
|
16723
|
-
const path21 = String(e.
|
|
16724
|
-
|
|
16789
|
+
const path21 = String(e.instancePath || "root");
|
|
16790
|
+
const value = e.value;
|
|
16791
|
+
return `${path21}: ${e.message} (${JSON.stringify(value)})`;
|
|
16725
16792
|
}).join(", ");
|
|
16726
16793
|
throw new Error(`Invalid state: ${errorMsg}`);
|
|
16727
16794
|
}
|
|
@@ -17062,8 +17129,9 @@ var workerId = "";
|
|
|
17062
17129
|
var BENIGN_IPC_CODES = /* @__PURE__ */ new Set(["EPIPE", "ERR_IPC_CHANNEL_CLOSED", "ECONNRESET"]);
|
|
17063
17130
|
function isBenignClusterIpcError(err) {
|
|
17064
17131
|
if (!err) return false;
|
|
17065
|
-
|
|
17066
|
-
|
|
17132
|
+
const e = err;
|
|
17133
|
+
if (typeof e.code === "string" && BENIGN_IPC_CODES.has(e.code)) return true;
|
|
17134
|
+
const msg2 = String(e.message || err);
|
|
17067
17135
|
return /\b(EPIPE|ECONNRESET)\b/.test(msg2) || /channel closed/i.test(msg2);
|
|
17068
17136
|
}
|
|
17069
17137
|
var masterIpcGuardInstalled = false;
|
|
@@ -17073,7 +17141,7 @@ function setupMasterIpcErrorHandler() {
|
|
|
17073
17141
|
masterIpcGuardInstalled = true;
|
|
17074
17142
|
cluster.on("fork", (worker) => guardClusterWorker(worker));
|
|
17075
17143
|
for (const id of Object.keys(cluster.workers ?? {})) {
|
|
17076
|
-
const w = cluster.workers
|
|
17144
|
+
const w = (cluster.workers ?? {})[id];
|
|
17077
17145
|
if (w) guardClusterWorker(w);
|
|
17078
17146
|
}
|
|
17079
17147
|
guardWorkerEmitReemit();
|
|
@@ -17091,11 +17159,12 @@ function guardWorkerEmitReemit() {
|
|
|
17091
17159
|
Worker2.prototype.emit = function(event, ...args) {
|
|
17092
17160
|
if (event === "error" && typeof this.listenerCount === "function" && this.listenerCount("error") === 0) {
|
|
17093
17161
|
this.on("error", (err) => {
|
|
17162
|
+
const e = err;
|
|
17094
17163
|
if (isBenignClusterIpcError(err)) {
|
|
17095
|
-
logToDebugFile("DEBUG", `[Master] Last-resort guard swallowed listener-less IPC error: ${
|
|
17164
|
+
logToDebugFile("DEBUG", `[Master] Last-resort guard swallowed listener-less IPC error: ${e?.code || e?.message}`);
|
|
17096
17165
|
return;
|
|
17097
17166
|
}
|
|
17098
|
-
logToDebugFile("WARN", `[Master] Last-resort guard handled listener-less worker error: ${
|
|
17167
|
+
logToDebugFile("WARN", `[Master] Last-resort guard handled listener-less worker error: ${e?.stack || e?.message || err}`);
|
|
17099
17168
|
});
|
|
17100
17169
|
}
|
|
17101
17170
|
return origEmit.apply(this, [event, ...args]);
|
|
@@ -17105,11 +17174,12 @@ function guardClusterWorker(worker) {
|
|
|
17105
17174
|
if (!worker || worker.__piIpcGuarded) return;
|
|
17106
17175
|
worker.__piIpcGuarded = true;
|
|
17107
17176
|
const guard = (err) => {
|
|
17177
|
+
const e = err;
|
|
17108
17178
|
if (isBenignClusterIpcError(err)) {
|
|
17109
|
-
logToDebugFile("DEBUG", `[Master] Swallowed benign worker IPC error: ${
|
|
17179
|
+
logToDebugFile("DEBUG", `[Master] Swallowed benign worker IPC error: ${e?.code || e?.message}`);
|
|
17110
17180
|
return;
|
|
17111
17181
|
}
|
|
17112
|
-
logToDebugFile("WARN", `[Master] Worker error (non-IPC): ${
|
|
17182
|
+
logToDebugFile("WARN", `[Master] Worker error (non-IPC): ${e?.stack || e?.message || err}`);
|
|
17113
17183
|
};
|
|
17114
17184
|
worker.on("error", guard);
|
|
17115
17185
|
if (worker.process && typeof worker.process.on === "function") {
|
|
@@ -19268,7 +19338,7 @@ async function runHealthCheck(options) {
|
|
|
19268
19338
|
success: result.status !== "unhealthy",
|
|
19269
19339
|
status: result.status,
|
|
19270
19340
|
components: result.components,
|
|
19271
|
-
error: result.status === "unhealthy" ? result.components.find((c) => !c.healthy && registry.isCritical(c.component))?.error : void 0
|
|
19341
|
+
error: result.status === "unhealthy" ? result.components.find((c) => !c.healthy && registry.isCritical(c.component ?? ""))?.error : void 0
|
|
19272
19342
|
};
|
|
19273
19343
|
}
|
|
19274
19344
|
|
|
@@ -19280,80 +19350,6 @@ init_config();
|
|
|
19280
19350
|
// src/orchestration/researcher.ts
|
|
19281
19351
|
import { createAgentSession, SessionManager, SettingsManager as SettingsManagerClass } from "@earendil-works/pi-coding-agent";
|
|
19282
19352
|
|
|
19283
|
-
// src/tools/read-guard.ts
|
|
19284
|
-
import { constants as constants2 } from "node:fs";
|
|
19285
|
-
import { access as access3, open as open5, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
|
|
19286
|
-
import { homedir as homedir7 } from "node:os";
|
|
19287
|
-
import { basename as basename5, dirname as dirname13, relative, isAbsolute as isAbsolute3, parse, sep as sep2 } from "node:path";
|
|
19288
|
-
var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud", ".terraform"]);
|
|
19289
|
-
var DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.dockerconfigjson|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)([._-].*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars|key)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
|
|
19290
|
-
var ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
|
|
19291
|
-
function normalizeName(name) {
|
|
19292
|
-
return name.toLowerCase().replace(/:.*$/, "").replace(/[. ]+$/, "");
|
|
19293
|
-
}
|
|
19294
|
-
var ReadDeniedError = class extends Error {
|
|
19295
|
-
constructor(reason) {
|
|
19296
|
-
super(`read denied: ${reason}`);
|
|
19297
|
-
this.name = "ReadDeniedError";
|
|
19298
|
-
}
|
|
19299
|
-
};
|
|
19300
|
-
async function resolveReal(p) {
|
|
19301
|
-
try {
|
|
19302
|
-
return await realpath2(p);
|
|
19303
|
-
} catch {
|
|
19304
|
-
const parent = dirname13(p);
|
|
19305
|
-
if (parent === p) return p;
|
|
19306
|
-
return `${await resolveReal(parent)}${sep2}${basename5(p)}`;
|
|
19307
|
-
}
|
|
19308
|
-
}
|
|
19309
|
-
function isWithin(root, target) {
|
|
19310
|
-
const rel = relative(root, target);
|
|
19311
|
-
return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute3(rel);
|
|
19312
|
-
}
|
|
19313
|
-
async function assertReadAllowed(cwd, absolutePath) {
|
|
19314
|
-
const root = await resolveReal(cwd);
|
|
19315
|
-
const home = await resolveReal(homedir7());
|
|
19316
|
-
if (root === parse(root).root || isWithin(root, home)) {
|
|
19317
|
-
throw new ReadDeniedError("the working directory is a home or filesystem root, not a project directory");
|
|
19318
|
-
}
|
|
19319
|
-
const target = await resolveReal(absolutePath);
|
|
19320
|
-
if (!isWithin(root, target)) {
|
|
19321
|
-
throw new ReadDeniedError("path is outside the project directory");
|
|
19322
|
-
}
|
|
19323
|
-
const segments = relative(root, target).split(sep2);
|
|
19324
|
-
if (segments.some((s) => DENIED_SEGMENTS.has(s.toLowerCase()))) {
|
|
19325
|
-
throw new ReadDeniedError("path is inside a credential or VCS-internals directory");
|
|
19326
|
-
}
|
|
19327
|
-
const name = normalizeName(basename5(target));
|
|
19328
|
-
if (!ALLOWED_ENV_TEMPLATE.test(name) && DENIED_BASENAME.test(name)) {
|
|
19329
|
-
throw new ReadDeniedError("file looks like a credential or secret");
|
|
19330
|
-
}
|
|
19331
|
-
}
|
|
19332
|
-
function createGuardedReadOperations(cwd) {
|
|
19333
|
-
return {
|
|
19334
|
-
access: async (p) => {
|
|
19335
|
-
await assertReadAllowed(cwd, p);
|
|
19336
|
-
await access3(p, constants2.R_OK);
|
|
19337
|
-
},
|
|
19338
|
-
readFile: async (p) => {
|
|
19339
|
-
await assertReadAllowed(cwd, p);
|
|
19340
|
-
const handle = await open5(p, constants2.O_RDONLY | constants2.O_NOFOLLOW);
|
|
19341
|
-
try {
|
|
19342
|
-
const stat6 = await handle.stat();
|
|
19343
|
-
if (!stat6.isFile()) {
|
|
19344
|
-
throw new ReadDeniedError("path is not a regular file");
|
|
19345
|
-
}
|
|
19346
|
-
return await readFile7(handle);
|
|
19347
|
-
} finally {
|
|
19348
|
-
await handle.close();
|
|
19349
|
-
}
|
|
19350
|
-
}
|
|
19351
|
-
};
|
|
19352
|
-
}
|
|
19353
|
-
|
|
19354
|
-
// src/tools/index.ts
|
|
19355
|
-
import { createReadToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
19356
|
-
|
|
19357
19353
|
// src/tools/search.ts
|
|
19358
19354
|
import { Type as Type4 } from "typebox";
|
|
19359
19355
|
import { Value as Value5 } from "typebox/value";
|
|
@@ -19714,6 +19710,9 @@ function getSsrfSafeFetcher() {
|
|
|
19714
19710
|
const { Agent: Agent2, fetch: undiciFetch } = await import("undici");
|
|
19715
19711
|
return {
|
|
19716
19712
|
fetch: undiciFetch,
|
|
19713
|
+
// node:net's LookupFunction pins the callback to `string | LookupAddress[]`
|
|
19714
|
+
// (no undefined); the wrapper's callback allows undefined for the single
|
|
19715
|
+
// resolution, so the two signatures differ by exactly that — a double cast.
|
|
19717
19716
|
dispatcher: new Agent2({ connect: { lookup: ssrfSafeLookup } })
|
|
19718
19717
|
};
|
|
19719
19718
|
} catch (e) {
|
|
@@ -19944,10 +19943,10 @@ init_logger();
|
|
|
19944
19943
|
init_metrics();
|
|
19945
19944
|
init_error_tracker();
|
|
19946
19945
|
import { existsSync as existsSync13 } from "node:fs";
|
|
19947
|
-
import { dirname as
|
|
19946
|
+
import { dirname as dirname13, join as join21 } from "node:path";
|
|
19948
19947
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
19949
19948
|
import { Worker } from "node:worker_threads";
|
|
19950
|
-
var MODULE_DIR =
|
|
19949
|
+
var MODULE_DIR = dirname13(fileURLToPath4(import.meta.url));
|
|
19951
19950
|
var PdfExtractError = class extends Error {
|
|
19952
19951
|
kind;
|
|
19953
19952
|
constructor(kind, message, options) {
|
|
@@ -20385,7 +20384,16 @@ async function scrapeWithStealthBrowser(_url, config, signal, sessionId, contain
|
|
|
20385
20384
|
const result = await runBrowserTask({ url: _url, sessionId }, "scrape", config, signal, 1, container);
|
|
20386
20385
|
const browserDuration = Date.now() - browserStart;
|
|
20387
20386
|
const legacyBuffer = result.buffer;
|
|
20388
|
-
|
|
20387
|
+
let pdfBytes;
|
|
20388
|
+
if (typeof result.bufferB64 === "string") {
|
|
20389
|
+
pdfBytes = Buffer.from(result.bufferB64, "base64");
|
|
20390
|
+
} else if (legacyBuffer && !(legacyBuffer instanceof Uint8Array) && Array.isArray(legacyBuffer.data)) {
|
|
20391
|
+
pdfBytes = Buffer.from(legacyBuffer.data);
|
|
20392
|
+
} else if (legacyBuffer instanceof Uint8Array) {
|
|
20393
|
+
pdfBytes = Buffer.from(legacyBuffer);
|
|
20394
|
+
} else {
|
|
20395
|
+
pdfBytes = null;
|
|
20396
|
+
}
|
|
20389
20397
|
if (pdfBytes !== null) {
|
|
20390
20398
|
const markdown2 = await extractPdfToMarkdown(pdfBytes);
|
|
20391
20399
|
validateContent("", markdown2, _url);
|
|
@@ -23600,6 +23608,75 @@ Failed to query Stack Exchange. This may be due to API rate limiting (300/day an
|
|
|
23600
23608
|
init_constants();
|
|
23601
23609
|
import { createGrepToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
23602
23610
|
import { Value as Value9 } from "typebox/value";
|
|
23611
|
+
import { resolve as resolvePath, isAbsolute as isAbsolute4 } from "node:path";
|
|
23612
|
+
|
|
23613
|
+
// src/tools/read-guard.ts
|
|
23614
|
+
import { access as access3, open as open5, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
|
|
23615
|
+
import { homedir as homedir7 } from "node:os";
|
|
23616
|
+
import { basename as basename5, dirname as dirname14, relative, isAbsolute as isAbsolute3, parse, sep as sep2 } from "node:path";
|
|
23617
|
+
var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud", ".terraform"]);
|
|
23618
|
+
var DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.dockerconfigjson|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)([._-].*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars|key)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
|
|
23619
|
+
var ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
|
|
23620
|
+
function normalizeName(name) {
|
|
23621
|
+
return name.toLowerCase().replace(/:.*$/, "").replace(/[. ]+$/, "");
|
|
23622
|
+
}
|
|
23623
|
+
var ReadDeniedError = class extends Error {
|
|
23624
|
+
constructor(reason) {
|
|
23625
|
+
super(`read denied: ${reason}`);
|
|
23626
|
+
this.name = "ReadDeniedError";
|
|
23627
|
+
}
|
|
23628
|
+
};
|
|
23629
|
+
async function resolveReal(p) {
|
|
23630
|
+
try {
|
|
23631
|
+
return await realpath2(p);
|
|
23632
|
+
} catch {
|
|
23633
|
+
const parent = dirname14(p);
|
|
23634
|
+
if (parent === p) return p;
|
|
23635
|
+
return `${await resolveReal(parent)}${sep2}${basename5(p)}`;
|
|
23636
|
+
}
|
|
23637
|
+
}
|
|
23638
|
+
function isWithin(root, target) {
|
|
23639
|
+
const rel = relative(root, target);
|
|
23640
|
+
return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute3(rel);
|
|
23641
|
+
}
|
|
23642
|
+
async function assertReadAllowed(cwd, absolutePath) {
|
|
23643
|
+
const root = await resolveReal(cwd);
|
|
23644
|
+
const home = await resolveReal(homedir7());
|
|
23645
|
+
if (root === parse(root).root || isWithin(root, home)) {
|
|
23646
|
+
throw new ReadDeniedError("the working directory is a home or filesystem root, not a project directory");
|
|
23647
|
+
}
|
|
23648
|
+
const target = await resolveReal(absolutePath);
|
|
23649
|
+
if (!isWithin(root, target)) {
|
|
23650
|
+
throw new ReadDeniedError("path is outside the project directory");
|
|
23651
|
+
}
|
|
23652
|
+
const segments = relative(root, target).split(sep2);
|
|
23653
|
+
if (segments.some((s) => DENIED_SEGMENTS.has(s.toLowerCase()))) {
|
|
23654
|
+
throw new ReadDeniedError("path is inside a credential or VCS-internals directory");
|
|
23655
|
+
}
|
|
23656
|
+
const name = normalizeName(basename5(target));
|
|
23657
|
+
if (!ALLOWED_ENV_TEMPLATE.test(name) && DENIED_BASENAME.test(name)) {
|
|
23658
|
+
throw new ReadDeniedError("file looks like a credential or secret");
|
|
23659
|
+
}
|
|
23660
|
+
}
|
|
23661
|
+
function isDeniedPathName(name) {
|
|
23662
|
+
const segments = name.split(sep2);
|
|
23663
|
+
if (segments.some((s) => DENIED_SEGMENTS.has(s.toLowerCase()))) return true;
|
|
23664
|
+
const base = normalizeName(basename5(name));
|
|
23665
|
+
return !ALLOWED_ENV_TEMPLATE.test(base) && DENIED_BASENAME.test(base);
|
|
23666
|
+
}
|
|
23667
|
+
|
|
23668
|
+
// src/tools/grep.ts
|
|
23669
|
+
function filterDeniedLines(text) {
|
|
23670
|
+
const lines = text.split("\n");
|
|
23671
|
+
const kept = [];
|
|
23672
|
+
for (const line of lines) {
|
|
23673
|
+
const m = line.match(/^(.+?):\d+: /) ?? line.match(/^(.+?)-\d+- /);
|
|
23674
|
+
const prefix = m?.[1];
|
|
23675
|
+
if (prefix && isDeniedPathName(prefix)) continue;
|
|
23676
|
+
kept.push(line);
|
|
23677
|
+
}
|
|
23678
|
+
return kept.join("\n");
|
|
23679
|
+
}
|
|
23603
23680
|
function createGrepTool(options) {
|
|
23604
23681
|
const cwd = options.cwd ?? process.cwd();
|
|
23605
23682
|
const sdkGrep = createGrepToolDefinition(cwd);
|
|
@@ -23608,7 +23685,7 @@ function createGrepTool(options) {
|
|
|
23608
23685
|
...sdkGrep,
|
|
23609
23686
|
label: "Code Search",
|
|
23610
23687
|
promptGuidelines: [
|
|
23611
|
-
"Available for fast recursive text search in
|
|
23688
|
+
"Available for fast recursive text search in the local project directory (nothing outside it; credential files and directories are refused).",
|
|
23612
23689
|
'Pattern supports regex. Use glob to scope to file types (e.g., "**/*.ts").',
|
|
23613
23690
|
"Options: ignoreCase, literal (disable regex), context (lines around match), limit (max matches).",
|
|
23614
23691
|
`Local code search \u2014 it does NOT consume your web-gathering budget (limit: ${MAX_GREP_CALLS} calls).`
|
|
@@ -23626,8 +23703,24 @@ function createGrepTool(options) {
|
|
|
23626
23703
|
details: { blocked: true, reason: "limit_reached" }
|
|
23627
23704
|
};
|
|
23628
23705
|
}
|
|
23706
|
+
const searchDir = params.path ?? ".";
|
|
23707
|
+
const searchPath = isAbsolute4(searchDir) ? searchDir : resolvePath(cwd, searchDir);
|
|
23629
23708
|
try {
|
|
23630
|
-
|
|
23709
|
+
await assertReadAllowed(cwd, searchPath);
|
|
23710
|
+
} catch (err) {
|
|
23711
|
+
const msg2 = err instanceof ReadDeniedError ? err.message : `read denied: ${String(err)}`;
|
|
23712
|
+
return {
|
|
23713
|
+
content: [{ type: "text", text: `Grep refused: ${msg2}` }],
|
|
23714
|
+
details: { error: "denied_path" }
|
|
23715
|
+
};
|
|
23716
|
+
}
|
|
23717
|
+
try {
|
|
23718
|
+
const result = await sdkExecute(toolCallId, params, signal, onUpdate, ctx);
|
|
23719
|
+
const content = result.content;
|
|
23720
|
+
for (const block of content) {
|
|
23721
|
+
if (block.type === "text") block.text = filterDeniedLines(block.text);
|
|
23722
|
+
}
|
|
23723
|
+
return result;
|
|
23631
23724
|
} catch (err) {
|
|
23632
23725
|
const msg2 = err instanceof Error ? err.message : String(err);
|
|
23633
23726
|
return {
|
|
@@ -24344,7 +24437,6 @@ function createResearchTools(options) {
|
|
|
24344
24437
|
})
|
|
24345
24438
|
};
|
|
24346
24439
|
return [
|
|
24347
|
-
createReadToolDefinition(options.cwd, { operations: createGuardedReadOperations(options.cwd) }),
|
|
24348
24440
|
createSearchTool({
|
|
24349
24441
|
...resolvedOptions,
|
|
24350
24442
|
onProgress: options.onSearchProgress,
|
|
@@ -24609,12 +24701,13 @@ async function createResearcherSession(options) {
|
|
|
24609
24701
|
maxScrapeUrls,
|
|
24610
24702
|
getTokensUsed: () => {
|
|
24611
24703
|
if (!sessionRef.session) return 0;
|
|
24612
|
-
|
|
24613
|
-
|
|
24704
|
+
const usageSession = sessionRef.session;
|
|
24705
|
+
if (typeof usageSession?.getContextUsage === "function") {
|
|
24706
|
+
const usage = usageSession.getContextUsage();
|
|
24614
24707
|
if (usage && typeof usage.tokens === "number") return usage.tokens;
|
|
24615
24708
|
}
|
|
24616
|
-
if (typeof
|
|
24617
|
-
const usage =
|
|
24709
|
+
if (typeof usageSession?.getUsage === "function") {
|
|
24710
|
+
const usage = usageSession.getUsage();
|
|
24618
24711
|
return (usage.input || 0) + (usage.output || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
|
|
24619
24712
|
}
|
|
24620
24713
|
return 0;
|
|
@@ -25282,7 +25375,10 @@ ${responseText}`);
|
|
|
25282
25375
|
continue;
|
|
25283
25376
|
}
|
|
25284
25377
|
const synthesisService = await getService(ServiceNames.RESEARCH_SYNTHESIS_SERVICE, ctx, container);
|
|
25285
|
-
|
|
25378
|
+
const report = extractToolResults(session);
|
|
25379
|
+
const { digest: rawDigest } = splitCoverageDigest(responseText);
|
|
25380
|
+
const digest = rawDigest || buildFallbackDigest(researcherConfig.goal, successfulScrapeCount);
|
|
25381
|
+
synthesisService.storeReport(researchId, `${round}.${id}`, report, digest);
|
|
25286
25382
|
observer?.onResearcherComplete?.(id, synthesisService.getReport(researchId, `${round}.${id}`) ?? responseText);
|
|
25287
25383
|
return;
|
|
25288
25384
|
} catch (err) {
|
|
@@ -25299,7 +25395,10 @@ ${responseText}`);
|
|
|
25299
25395
|
const ungrounded = scrapeEnabled && successfulScrapeCount === 0 && nonScrapeGroundingHits === 0 && historicalUrls.length === 0;
|
|
25300
25396
|
if (partialResponse && partialResponse.trim().length > 50 && !ungrounded) {
|
|
25301
25397
|
const synthesisService = await getService(ServiceNames.RESEARCH_SYNTHESIS_SERVICE, ctx, container);
|
|
25302
|
-
|
|
25398
|
+
const report = extractToolResults(session) + "\n\n---\n*WARNING: This report was truncated due to a timeout/error. Content may be incomplete.*";
|
|
25399
|
+
const { digest: rawDigest } = splitCoverageDigest(partialResponse);
|
|
25400
|
+
const digest = rawDigest || buildFallbackDigest(researcherConfig.goal, successfulScrapeCount);
|
|
25401
|
+
synthesisService.storeReport(researchId, `${round}.${id}`, report, digest);
|
|
25303
25402
|
logger.log(`[ResearcherExecutor] Researcher ${id} salvaged partial content (${partialResponse.length} chars) after error: ${errMsg}`);
|
|
25304
25403
|
observer?.onResearcherComplete?.(id, synthesisService.getReport(researchId, `${round}.${id}`) ?? partialResponse);
|
|
25305
25404
|
return;
|
|
@@ -26260,6 +26359,9 @@ var DeepResearchOrchestrator = class {
|
|
|
26260
26359
|
const hasReports = synthesisCheckService.hasReports(researchId);
|
|
26261
26360
|
const failedIds = getFailedResearchers(this.options.sessionId, researchId);
|
|
26262
26361
|
if (!hasReports && failedIds.length > 0) {
|
|
26362
|
+
if (hasOnlyCapacityFailures(this.options.sessionId, researchId)) {
|
|
26363
|
+
throw createResearchStopError(this.options.sessionId, researchId);
|
|
26364
|
+
}
|
|
26263
26365
|
const reasons = getResearcherFailureReasons(this.options.sessionId, researchId);
|
|
26264
26366
|
const causes = failedIds.map((id) => `researcher ${id}: ${reasons[id] ?? "no usable report"}`).join("; ");
|
|
26265
26367
|
throw new Error(
|
|
@@ -27109,16 +27211,18 @@ var ResearchSynthesisService = class _ResearchSynthesisService {
|
|
|
27109
27211
|
* @param id - Report identifier (typically "round.researcherId")
|
|
27110
27212
|
* @param report - The researcher's report content
|
|
27111
27213
|
*/
|
|
27112
|
-
storeReport(sessionId, id, report) {
|
|
27113
|
-
const
|
|
27214
|
+
storeReport(sessionId, id, report, digest) {
|
|
27215
|
+
const explicit = digest?.trim();
|
|
27216
|
+
const { digest: splitDigest, body } = explicit ? { digest: "", body: report } : splitCoverageDigest(report);
|
|
27217
|
+
const finalDigest = explicit || splitDigest;
|
|
27114
27218
|
this.getSessionReports(sessionId).set(id, body);
|
|
27115
27219
|
let sessionDigests = this.digests.get(sessionId);
|
|
27116
|
-
if (
|
|
27220
|
+
if (finalDigest) {
|
|
27117
27221
|
if (!sessionDigests) {
|
|
27118
27222
|
sessionDigests = /* @__PURE__ */ new Map();
|
|
27119
27223
|
this.digests.set(sessionId, sessionDigests);
|
|
27120
27224
|
}
|
|
27121
|
-
sessionDigests.set(id,
|
|
27225
|
+
sessionDigests.set(id, finalDigest);
|
|
27122
27226
|
} else if (sessionDigests) {
|
|
27123
27227
|
sessionDigests.delete(id);
|
|
27124
27228
|
if (sessionDigests.size === 0) this.digests.delete(sessionId);
|
|
@@ -28327,40 +28431,41 @@ function makeProgressObserver() {
|
|
|
28327
28431
|
return {
|
|
28328
28432
|
enableLogging: false,
|
|
28329
28433
|
onProgress: (event, data) => {
|
|
28434
|
+
const d = data;
|
|
28330
28435
|
switch (event) {
|
|
28331
28436
|
case "planning_success":
|
|
28332
|
-
toStderr(` \u2022 plan: ${
|
|
28437
|
+
toStderr(` \u2022 plan: ${d?.plan?.researchers?.length ?? "?"} researcher(s)
|
|
28333
28438
|
`);
|
|
28334
28439
|
break;
|
|
28335
28440
|
case "run_queued":
|
|
28336
28441
|
toStderr(
|
|
28337
|
-
` \u2022 queued: ${
|
|
28442
|
+
` \u2022 queued: ${d?.slots ?? "?"} concurrent run(s) already active \u2014 waiting up to ${Math.round((d?.maxWaitMs ?? 0) / 1e3)}s for a slot\u2026
|
|
28338
28443
|
`
|
|
28339
28444
|
);
|
|
28340
28445
|
break;
|
|
28341
28446
|
case "round_start":
|
|
28342
|
-
toStderr(` \u2022 round ${
|
|
28447
|
+
toStderr(` \u2022 round ${d?.round}
|
|
28343
28448
|
`);
|
|
28344
28449
|
break;
|
|
28345
28450
|
case "search_start":
|
|
28346
|
-
toStderr(` \u2022 search burst: ${
|
|
28451
|
+
toStderr(` \u2022 search burst: ${d?.queries?.length ?? 0} ${(d?.queries?.length ?? 0) === 1 ? "query" : "queries"}
|
|
28347
28452
|
`);
|
|
28348
28453
|
break;
|
|
28349
28454
|
case "researcher_start":
|
|
28350
|
-
toStderr(` \u2022 researcher ${
|
|
28455
|
+
toStderr(` \u2022 researcher ${d?.id}: ${d?.name}
|
|
28351
28456
|
`);
|
|
28352
28457
|
break;
|
|
28353
28458
|
case "researcher_failure":
|
|
28354
|
-
toStderr(` \u2022 researcher ${
|
|
28459
|
+
toStderr(` \u2022 researcher ${d?.id} failed: ${d?.error}
|
|
28355
28460
|
`);
|
|
28356
28461
|
break;
|
|
28357
28462
|
case "evaluation_decision":
|
|
28358
|
-
toStderr(` \u2022 evaluator: ${
|
|
28463
|
+
toStderr(` \u2022 evaluator: ${d?.action}
|
|
28359
28464
|
`);
|
|
28360
28465
|
break;
|
|
28361
28466
|
case "tokens_consumed": {
|
|
28362
|
-
const consumed = Number(
|
|
28363
|
-
const costVal = typeof
|
|
28467
|
+
const consumed = Number(d?.tokens ?? 0);
|
|
28468
|
+
const costVal = typeof d?.cost === "number" ? d.cost : void 0;
|
|
28364
28469
|
if (consumed > 0 || costVal !== void 0) {
|
|
28365
28470
|
const costPart = costVal === void 0 ? "" : ` ($${costVal.toFixed(4)})`;
|
|
28366
28471
|
toStderr(` \u2022 tokens: ${consumed}${costPart}
|
|
@@ -28369,9 +28474,9 @@ function makeProgressObserver() {
|
|
|
28369
28474
|
break;
|
|
28370
28475
|
}
|
|
28371
28476
|
case "complete": {
|
|
28372
|
-
toStderr(` \u2022 complete (${
|
|
28477
|
+
toStderr(` \u2022 complete (${d?.result?.length ?? 0} chars)
|
|
28373
28478
|
`);
|
|
28374
|
-
const reportText = typeof
|
|
28479
|
+
const reportText = typeof d?.result === "string" ? d.result : "";
|
|
28375
28480
|
if (reportText.includes("No web sources were successfully retrieved") || reportText.includes("None of the links above could be verified")) {
|
|
28376
28481
|
toStderr(" \u2022 WARNING: no web sources could be retrieved \u2014 the report is unverified\n");
|
|
28377
28482
|
} else if (reportText.includes("Grounding notice: only")) {
|
|
@@ -28380,7 +28485,7 @@ function makeProgressObserver() {
|
|
|
28380
28485
|
break;
|
|
28381
28486
|
}
|
|
28382
28487
|
case "error":
|
|
28383
|
-
toStderr(` \u2022 error: ${
|
|
28488
|
+
toStderr(` \u2022 error: ${d?.message}
|
|
28384
28489
|
`);
|
|
28385
28490
|
break;
|
|
28386
28491
|
default:
|