@lincoln504/pi-research 1.7.24 → 1.7.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +276 -171
  3. package/dist/prompts/research-tool-usage.md +4 -5
  4. package/dist/prompts/researcher.md +6 -36
  5. package/dist/prompts/system-coordinator.md +1 -1
  6. package/dist/prompts/system-lead-synthesizer.md +5 -5
  7. package/dist/thread-worker.mjs +22 -9
  8. package/docs/CHANGELOG.md +49 -0
  9. package/docs/CONFIGURATION.md +1 -0
  10. package/package.json +9 -9
  11. package/src/cli.ts +32 -14
  12. package/src/config.ts +20 -7
  13. package/src/core/interfaces/health-check-interfaces.ts +23 -2
  14. package/src/core/interfaces/knowledge-interfaces.ts +7 -4
  15. package/src/core/interfaces/observer-interfaces.ts +1 -1
  16. package/src/core/interfaces/orchestration-interfaces.ts +17 -12
  17. package/src/core/interfaces/planning-interfaces.ts +5 -5
  18. package/src/core/interfaces/process-interfaces.ts +2 -2
  19. package/src/core/interfaces/state-manager-interfaces.ts +6 -5
  20. package/src/core/llm/agentic-repair.ts +6 -6
  21. package/src/core/llm/llm-utils.ts +7 -4
  22. package/src/core/llm/model-registry-factory.ts +11 -11
  23. package/src/core/llm/research-model-resolver.ts +11 -11
  24. package/src/core/pi-version.ts +10 -1
  25. package/src/core/planning-service.ts +33 -13
  26. package/src/core/planning-utils.ts +33 -7
  27. package/src/core/service-initialization.ts +1 -1
  28. package/src/core/service-registry.ts +18 -11
  29. package/src/healthcheck/index.ts +5 -4
  30. package/src/healthcheck/registry.ts +5 -18
  31. package/src/index.ts +12 -16
  32. package/src/infrastructure/browser/browser-client.ts +4 -4
  33. package/src/infrastructure/browser/browser-error-utils.ts +6 -1
  34. package/src/infrastructure/browser/browser-lifecycle.ts +8 -3
  35. package/src/infrastructure/browser/browser-server.ts +3 -3
  36. package/src/infrastructure/browser/browser-task-scheduler.ts +13 -9
  37. package/src/infrastructure/browser/priority-task-queue.ts +13 -10
  38. package/src/infrastructure/browser/thread-worker-browser.ts +14 -11
  39. package/src/infrastructure/browser/thread-worker-lifecycle.ts +21 -15
  40. package/src/infrastructure/browser/thread-worker-messaging.ts +39 -31
  41. package/src/infrastructure/browser/thread-worker-types.ts +3 -1
  42. package/src/infrastructure/browser/thread-worker.mjs +22 -9
  43. package/src/infrastructure/browser/thread-worker.ts +3 -2
  44. package/src/infrastructure/browser/worker-pool-manager.ts +5 -5
  45. package/src/infrastructure/gpu-resource-service.ts +16 -9
  46. package/src/infrastructure/knowledge-store-service.ts +13 -10
  47. package/src/infrastructure/scheduler-factory-service.ts +4 -3
  48. package/src/infrastructure/service-initialization.ts +1 -1
  49. package/src/infrastructure/state/state-manager-service.ts +2 -2
  50. package/src/infrastructure/state/state-manager.ts +3 -3
  51. package/src/infrastructure/state/state-validator.ts +9 -3
  52. package/src/infrastructure/types/state-types.ts +12 -91
  53. package/src/knowledge/embedder-init.ts +8 -8
  54. package/src/knowledge/embedder-utils.ts +7 -3
  55. package/src/knowledge/embedder.ts +14 -10
  56. package/src/knowledge/onnx-env.ts +2 -2
  57. package/src/knowledge/store.ts +12 -11
  58. package/src/logger.ts +1 -1
  59. package/src/orchestration/deep-research-orchestrator.ts +15 -7
  60. package/src/orchestration/headless-observer.ts +1 -1
  61. package/src/orchestration/orchestration-types.ts +2 -2
  62. package/src/orchestration/quick-research-orchestrator.ts +4 -4
  63. package/src/orchestration/research-orchestration-service.ts +13 -13
  64. package/src/orchestration/research-synthesis-service.ts +15 -8
  65. package/src/orchestration/researcher-executor.ts +23 -7
  66. package/src/orchestration/researcher.ts +19 -7
  67. package/src/orchestration/service-initialization.ts +1 -1
  68. package/src/prompts/research-tool-usage.md +4 -5
  69. package/src/prompts/researcher.md +6 -36
  70. package/src/prompts/system-coordinator.md +1 -1
  71. package/src/prompts/system-lead-synthesizer.md +5 -5
  72. package/src/research-config.ts +11 -9
  73. package/src/sdk.ts +10 -10
  74. package/src/skill-install/skill-installer.ts +19 -10
  75. package/src/tools/grep.ts +57 -5
  76. package/src/tools/index.ts +0 -3
  77. package/src/tools/read-guard.ts +12 -0
  78. package/src/tools/research-knowledge-search.ts +15 -13
  79. package/src/tools/research-tool-definition.ts +15 -10
  80. package/src/tools/scrape.ts +3 -2
  81. package/src/tui/research-panel.ts +1 -1
  82. package/src/types/extension-context.ts +2 -2
  83. package/src/types/llm.ts +8 -7
  84. package/src/types/research-panel-types.ts +3 -1
  85. package/src/types/state-types.ts +98 -0
  86. package/src/utils/coverage-digest.ts +27 -6
  87. package/src/utils/llm-usage.ts +3 -3
  88. package/src/utils/safe-unref.ts +2 -2
  89. package/src/utils/shutdown-manager.ts +6 -6
  90. package/src/utils/stdio-capture.ts +25 -10
  91. package/src/utils/text-utils.ts +35 -0
  92. package/src/web-research/scraper-utils.ts +9 -3
  93. package/src/web-research/web-scraper.ts +25 -10
@@ -0,0 +1,98 @@
1
+ /**
2
+ * State Types
3
+ *
4
+ * Shared types for state management. These live in the foundation `types/` layer
5
+ * (not `infrastructure/`) so that `core/interfaces/` — which defines the
6
+ * `IStateManager` contract — can name the state shape without depending on
7
+ * `infrastructure/` (a layer above it in the dependency order). The TypeBox
8
+ * schemas are runtime values, so this file is imported (not `import type`) by the
9
+ * infrastructure that validates and migrates the on-disk state.
10
+ */
11
+
12
+ import { Type, type Static } from 'typebox';
13
+
14
+ /**
15
+ * Current on-disk state schema version. Bump this (and add a migration step in
16
+ * state-migration.ts) whenever the persisted shape changes incompatibly. The
17
+ * schema's `version` literal is pinned to this value so a reader only accepts a
18
+ * state it actually understands; older/newer files are routed through migration
19
+ * or future-version quarantine rather than being silently overwritten.
20
+ */
21
+ export const CURRENT_STATE_VERSION = 1 as const;
22
+
23
+ /**
24
+ * State metrics interface
25
+ */
26
+ export interface StateMetrics {
27
+ totalSessions: number;
28
+ activeSessions: number;
29
+ oldestSession: number | null;
30
+ newestSession: number | null;
31
+ containerUptime: number | null;
32
+ lastHeartbeatAge: number | null;
33
+ }
34
+
35
+ /**
36
+ * Session information interface
37
+ */
38
+ export const SessionInfoSchema = Type.Object({
39
+ pid: Type.Number(),
40
+ startTime: Type.Optional(Type.Number()),
41
+ lastSeen: Type.Number(),
42
+ connectedAt: Type.Number(),
43
+ });
44
+
45
+ /**
46
+ * Main state structure interface
47
+ */
48
+ export const SingletonStateSchema = Type.Object({
49
+ version: Type.Literal(CURRENT_STATE_VERSION),
50
+ containerId: Type.String(),
51
+ containerName: Type.String(),
52
+ port: Type.Number(),
53
+ sessions: Type.Record(Type.String(), SessionInfoSchema),
54
+ lastUpdated: Type.Number(),
55
+ browserServer: Type.Optional(Type.Object({
56
+ port: Type.Number(),
57
+ pid: Type.Number(),
58
+ startTime: Type.Optional(Type.Number()),
59
+ schedulerId: Type.Optional(Type.String()),
60
+ authSecret: Type.Optional(Type.String()),
61
+ })),
62
+ schedulerVersion: Type.Optional(Type.String()),
63
+ gpuOwner: Type.Optional(Type.Object({
64
+ pid: Type.Number(),
65
+ startTime: Type.Optional(Type.Number()),
66
+ startedAt: Type.Number(),
67
+ sessionId: Type.Optional(Type.String()),
68
+ // Re-entrant hold count for the owning process. The lock is shared by N
69
+ // concurrent in-process embedding calls (activeEmbeddings is designed > 1);
70
+ // each re-entrant acquire increments and each release decrements, so the
71
+ // cross-process owner record is only cleared when the last in-process hold
72
+ // is released. Absent on state written before refcounting — treated as 1.
73
+ holds: Type.Optional(Type.Number()),
74
+ })),
75
+ embeddingServer: Type.Optional(Type.Object({
76
+ port: Type.Number(),
77
+ pid: Type.Number(),
78
+ startTime: Type.Optional(Type.Number()),
79
+ serverId: Type.String(),
80
+ // EMBEDDING_MODEL the leader serves. A follower configured with a DIFFERENT
81
+ // model must not adopt this leader (same-dimension models would silently
82
+ // cross-embed and corrupt the vector space) — it falls back to a local
83
+ // in-process embedder instead. Optional for entries written by older
84
+ // processes, which are tolerated as matching.
85
+ model: Type.Optional(Type.String()),
86
+ // Shared secret a follower must present on every embed request. Mirrors
87
+ // browserServer.authSecret: the server listens on loopback, but loopback is
88
+ // not an authorization boundary — any local process could otherwise enqueue
89
+ // embedding work, and because the serial queue steps the leader down when
90
+ // poisoned, sustained abuse denies the knowledge store rather than merely
91
+ // burning GPU. Optional so an entry written by an older leader still parses;
92
+ // a client that finds none simply sends no header, and such a leader does not
93
+ // check one either.
94
+ authSecret: Type.Optional(Type.String()),
95
+ })),
96
+ });
97
+
98
+ export type SingletonState = Static<typeof SingletonStateSchema>;
@@ -65,18 +65,18 @@ const MAX_DIGEST_BLOCK_CHARS = 8000;
65
65
  * a reader that does not exist — while telling the model about a "research lead" that is
66
66
  * not part of its run.
67
67
  */
68
- export const RESEARCHER_DIGEST_SECTION = `Your report has three parts in this exact order: a COVERAGE DIGEST block, the report body, and the CITED LINKS list.
68
+ export const RESEARCHER_DIGEST_SECTION = `Your final message is the COVERAGE DIGEST block. Emit it and stop — do NOT write a report. The raw content you scraped is what the synthesis step reads; your job is to scrape, then account for what you covered.
69
69
 
70
- ### Part 1 — COVERAGE DIGEST (first, mandatory)
70
+ ### COVERAGE DIGEST (mandatory)
71
71
 
72
- Open the report with this block, exactly as shown. The research lead reads it to decide what still needs investigating. On the round your report arrives the lead reads the digest alongside the full report and checks one against the other; on every later round it sees ONLY this digest — so anything you leave out of it is invisible to every decision after the first.
72
+ The research lead reads this to decide what still needs investigating. On the round your work arrives the lead reads the digest alongside the raw content and checks one against the other; on every later round it sees ONLY this digest — so anything you leave out of it is invisible to every decision after the first.
73
73
 
74
74
  ${COVERAGE_DIGEST_HEADER}
75
75
  Goal: [your assigned goal, restated in one line]
76
76
  Covered: [the specific topics you actually established from sources, separated by semicolons — be concrete, name the things you found out, not the areas you looked at]
77
77
  Unsubstantiated: [claims you searched for but could not ground in any source; write "none" if there are none]
78
78
  Gaps: [what a follow-up researcher would still need to investigate on this goal; write "none" if your goal is fully covered]
79
- Sources: [the number of entries in your CITED LINKS list]
79
+ Sources: [the number of URLs you scraped]
80
80
  ${COVERAGE_DIGEST_TERMINATOR}
81
81
 
82
82
  Rules for the digest:
@@ -84,8 +84,6 @@ Rules for the digest:
84
84
  - Be honest about \`Gaps\` and \`Unsubstantiated\`. Claiming full coverage you do not have is the single most damaging thing you can write here: it argues for ending the research on this topic, and after the round it arrives there is no report left for the lead to check the claim against.
85
85
  - Write both delimiter lines exactly, in capitals, each on its own line.
86
86
 
87
- ### Part 2 — Report body
88
-
89
87
  `;
90
88
 
91
89
  /** Line-leading delimiter matcher, tolerating the markdown decoration models add. */
@@ -168,6 +166,29 @@ export function splitCoverageDigest(report: string): SplitReport {
168
166
  * many sources it cited — and says plainly that the rest is unknown. A router told
169
167
  * "coverage unknown" delegates; a router told nothing assumes the gap was filled.
170
168
  */
169
+ /**
170
+ * Build a clean fallback digest for a raw-scrape researcher that emitted no digest of its
171
+ * own.
172
+ *
173
+ * In the raw-scrape flow the report body is the researcher's raw tool results, which carry
174
+ * no [N] citations and open with a tool-name header — so `deriveCoverageDigest` reads the
175
+ * body as `Covered: <tool name>` and `Sources: 0`, actively misleading the router (it reads
176
+ * "0 sources" as "nothing grounded" and "covered: scrape" as the topic). This fallback
177
+ * instead states the two facts the executor knows directly: the researcher's assigned goal
178
+ * (what it was sent to cover) and how many URLs it actually scraped (its real source count).
179
+ *
180
+ * @param goal - The researcher's assigned goal
181
+ * @param scrapeCount - The researcher's successful-scrape count
182
+ */
183
+ export function buildFallbackDigest(goal: string, scrapeCount: number): string {
184
+ const topic = goal.trim() || 'unknown — no goal recorded';
185
+ return [
186
+ `Covered: ${topic} (no coverage digest emitted; goal restated)`,
187
+ `Gaps: unknown — this researcher emitted no coverage digest`,
188
+ `Sources: ${scrapeCount}`,
189
+ ].join('\n');
190
+ }
191
+
171
192
  export function deriveCoverageDigest(body: string): string {
172
193
  const citationCount = parseCitations(body).length;
173
194
 
@@ -11,7 +11,7 @@
11
11
  * counted nothing at all) silently under-reported cost. Route every call site here.
12
12
  */
13
13
 
14
- import type { Model } from '@earendil-works/pi-ai';
14
+ import type { Api, Model } from '@earendil-works/pi-ai';
15
15
  import { extractUsage, type TokenUsage } from '../types/llm.ts';
16
16
  import { logger } from '../logger.ts';
17
17
  import { metrics } from './metrics.ts';
@@ -31,7 +31,7 @@ const unpricedModelsWarned = new Set<string>();
31
31
  * suppressed a zero cost. The message deliberately does not assert a fault — it
32
32
  * states the condition and names the usual cause.
33
33
  */
34
- function warnIfUnpriced(model: Model<any>, tokens: number, cost: number): void {
34
+ function warnIfUnpriced(model: Model<Api>, tokens: number, cost: number): void {
35
35
  if (tokens <= 0 || cost > 0) return;
36
36
  const m = model as unknown as { provider?: string; id?: string; cost?: Record<string, number> };
37
37
  const key = `${m.provider ?? 'unknown'}/${m.id ?? 'unknown'}`;
@@ -112,7 +112,7 @@ export interface RecordUsageOptions {
112
112
  * Returns the extracted { tokens, cost } for callers that also need the value.
113
113
  */
114
114
  export function recordLlmUsage(
115
- model: Model<any>,
115
+ model: Model<Api>,
116
116
  rawUsage: unknown,
117
117
  opts: RecordUsageOptions
118
118
  ): { tokens: number; cost: number } {
@@ -6,8 +6,8 @@
6
6
  * repeated `(timer as any).unref()` pattern.
7
7
  */
8
8
  export function safeUnref(timer: NodeJS.Timeout | null | undefined): void {
9
- if (timer && typeof (timer as any).unref === 'function') {
10
- (timer as any).unref();
9
+ if (timer && typeof timer.unref === 'function') {
10
+ timer.unref();
11
11
  }
12
12
  }
13
13
 
@@ -5,15 +5,15 @@ export type CleanupTask = () => Promise<void> | void;
5
5
 
6
6
  // Minimal interface matching Node.js EventEmitter and process
7
7
  interface EventEmitterLike {
8
- on(event: string | symbol, listener: (...args: any[]) => void): any;
9
- off?(event: string | symbol, listener: (...args: any[]) => void): any;
10
- removeListener?(event: string | symbol, listener: (...args: any[]) => void): any;
8
+ on(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
9
+ off?(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
10
+ removeListener?(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
11
11
  }
12
12
 
13
13
  interface EventListenerCleanup {
14
14
  target: EventEmitterLike;
15
15
  event: string;
16
- listener: (...args: any[]) => void;
16
+ listener: (...args: unknown[]) => void;
17
17
  }
18
18
 
19
19
  export class ShutdownManager {
@@ -32,7 +32,7 @@ export class ShutdownManager {
32
32
  registerEventListener<T extends EventEmitterLike>(
33
33
  target: T,
34
34
  event: string,
35
- listener: (...args: any[]) => void
35
+ listener: (...args: unknown[]) => void
36
36
  ) {
37
37
  target.on(event, listener);
38
38
  this.eventListeners.push({ target, event, listener });
@@ -41,7 +41,7 @@ export class ShutdownManager {
41
41
  unregisterEventListener<T extends EventEmitterLike>(
42
42
  target: T,
43
43
  event: string,
44
- listener: (...args: any[]) => void
44
+ listener: (...args: unknown[]) => void
45
45
  ) {
46
46
  if (target.off) {
47
47
  target.off(event, listener);
@@ -233,10 +233,25 @@ export async function captureStdio<T>(
233
233
  const fd1SyncDecoder = new TextDecoder();
234
234
  const fd2SyncDecoder = new TextDecoder();
235
235
 
236
- // Save originals
237
- const originalStderrWrite = process.stderr.write;
238
- const originalStdoutWrite = process.stdout.write;
236
+ // Save originals. Node types the stock write() as an overload whose callback
237
+ // position is a plain callback (no BufferEncoding union), so a direct
238
+ // assignment to StdioWriteFn fails; the structural cast is the honest shape.
239
+ const originalStderrWrite = process.stderr.write as unknown as StdioWriteFn;
240
+ const originalStdoutWrite = process.stdout.write as unknown as StdioWriteFn;
239
241
  const originalFsWriteSync = fs.writeSync;
242
+
243
+ // The shapes of the write functions installed below. Node types the stock
244
+ // write() with `any` chunk/encoding/callback, so these are directly
245
+ // assignable to process.stdout/stderr.write and fs.writeSync.
246
+ type StdioWriteFn = (
247
+ chunk: string | Uint8Array,
248
+ // `string` rather than BufferEncoding: the global encoding union is not
249
+ // importable from 'node:buffer' in this @types/node, and a wider parameter
250
+ // keeps the replacement assignable to the original write signature.
251
+ encodingOrCb?: string | ((err?: Error | null) => void),
252
+ callback?: (err?: Error | null) => void,
253
+ ) => boolean;
254
+ type FsWriteSyncFn = (fd: number, chunk: string | Uint8Array, ...args: unknown[]) => number;
240
255
  const originalConsole = {
241
256
  log: console.log,
242
257
  info: console.info,
@@ -281,7 +296,7 @@ export async function captureStdio<T>(
281
296
  console.debug = createConsolePatch('debug', logFile, hasSufficientDiskSpace);
282
297
 
283
298
  // Patch stderr.write
284
- (process.stderr.write as any) = (chunk: string | Uint8Array, encodingOrCb?: any, callback?: any) => {
299
+ (process.stderr.write as StdioWriteFn) = (chunk: string | Uint8Array, encodingOrCb?: string | ((err?: Error | null) => void), callback?: (err?: Error | null) => void) => {
285
300
  const cb = typeof encodingOrCb === 'function' ? encodingOrCb : callback;
286
301
  const message = typeof chunk === 'string' ? chunk : stderrDecoder.decode(chunk, { stream: true });
287
302
 
@@ -318,7 +333,7 @@ export async function captureStdio<T>(
318
333
  };
319
334
 
320
335
  // Patch stdout.write
321
- (process.stdout.write as any) = (chunk: string | Uint8Array, encodingOrCb?: any, callback?: any) => {
336
+ (process.stdout.write as StdioWriteFn) = (chunk: string | Uint8Array, encodingOrCb?: string | ((err?: Error | null) => void), callback?: (err?: Error | null) => void) => {
322
337
  const message = typeof chunk === 'string' ? chunk : stdoutDecoder.decode(chunk, { stream: true });
323
338
 
324
339
  // Native log patterns or plain text that we want to divert from TUI
@@ -382,7 +397,7 @@ export async function captureStdio<T>(
382
397
  try {
383
398
  const descriptor = Object.getOwnPropertyDescriptor(fs, 'writeSync');
384
399
  if (!descriptor || (descriptor.writable || descriptor.set)) {
385
- fs.writeSync = (fd: number, chunk: any, ...args: any[]) => {
400
+ (fs.writeSync as FsWriteSyncFn) = (fd: number, chunk: string | Uint8Array, ...args: unknown[]) => {
386
401
  if (fd === 1 || fd === 2) {
387
402
  const fdDecoder = fd === 1 ? fd1SyncDecoder : fd2SyncDecoder;
388
403
  const message = typeof chunk === 'string' ? chunk : fdDecoder.decode(chunk, { stream: true });
@@ -395,7 +410,7 @@ export async function captureStdio<T>(
395
410
  // fdDecoder for the completing chunk) must be skipped explicitly to
396
411
  // avoid writing an empty log entry on every mid-character split.
397
412
  if (fd === 2 && message.length === 0) {
398
- return (typeof chunk === 'string' ? Buffer.from(chunk).length : (chunk as any).length);
413
+ return (typeof chunk === 'string' ? Buffer.from(chunk).length : chunk.length);
399
414
  }
400
415
 
401
416
  const isNative = isNativeLog(message);
@@ -409,7 +424,7 @@ export async function captureStdio<T>(
409
424
 
410
425
  if (shouldDivert) {
411
426
  if (!hasSufficientDiskSpace()) {
412
- return (typeof chunk === 'string' ? Buffer.from(chunk).length : (chunk as any).length);
427
+ return (typeof chunk === 'string' ? Buffer.from(chunk).length : chunk.length);
413
428
  }
414
429
 
415
430
  const timestamp = new Date().toISOString();
@@ -422,10 +437,10 @@ export async function captureStdio<T>(
422
437
  try {
423
438
  fs.appendFileSync(logFile, `${safeJsonStringify(entry)}\n`);
424
439
  } catch { /* ignore */ }
425
- return (typeof chunk === 'string' ? Buffer.from(chunk).length : (chunk as any).length);
440
+ return (typeof chunk === 'string' ? Buffer.from(chunk).length : chunk.length);
426
441
  }
427
442
  }
428
- return (originalFsWriteSync as any).apply(fs, [fd, chunk, ...args]);
443
+ return (originalFsWriteSync as FsWriteSyncFn).apply(fs, [fd, chunk, ...args]);
429
444
  };
430
445
  }
431
446
  } catch (_e) { /* ignore */ }
@@ -3,6 +3,41 @@ import type { AssistantMessage } from '@earendil-works/pi-ai';
3
3
  import { logger } from '../logger.ts';
4
4
  import { stripTrailingLlmPunctuation } from './url-utils.ts';
5
5
 
6
+ /**
7
+ * Extract the raw tool results (the content a researcher gathered) from a session.
8
+ *
9
+ * In the raw-scrape synthesis flow the researcher's report-writing turn is skipped: the
10
+ * synthesis corpus is the raw content the researcher gathered (its tool results), not a
11
+ * written report. This collects every non-error tool result's text content, labelled by
12
+ * tool name, in conversation order, so the synthesizer reads the source material directly.
13
+ *
14
+ * @param session - The agent session to read
15
+ * @returns The concatenated tool-result text, empty when there are none
16
+ */
17
+ export function extractToolResults(session: AgentSession): string {
18
+ const parts: string[] = [];
19
+ for (const msg of session.messages) {
20
+ if (msg.role !== 'toolResult') continue;
21
+ const tr = msg as unknown as {
22
+ toolName?: string;
23
+ content?: Array<{ type?: string; text?: string }>;
24
+ isError?: boolean;
25
+ };
26
+ if (tr.isError) continue;
27
+ let text = (tr.content ?? [])
28
+ .map((c) => (c && c.type === 'text' ? String(c.text ?? '') : ''))
29
+ .join('');
30
+ // Strip the "Session URL Pool" footer: it is per-scrape sibling-routing metadata
31
+ // (URLs other researchers scraped), not content, and would be noise in the
32
+ // synthesis corpus. It is appended as `\n---\n## Session URL Pool\n...`.
33
+ text = text.replace(/\n-{3,}\n## Session URL Pool\n[\s\S]*$/, '').trimEnd();
34
+ if (text.trim()) {
35
+ parts.push(`### ${tr.toolName ?? 'tool'}\n${text}`);
36
+ }
37
+ }
38
+ return parts.join('\n\n');
39
+ }
40
+
6
41
  /**
7
42
  * Text Utilities
8
43
  *
@@ -4,6 +4,7 @@
4
4
 
5
5
  import * as dns from 'node:dns/promises';
6
6
  import * as dnsCb from 'node:dns';
7
+ import type { LookupFunction } from 'node:net';
7
8
  import * as net from 'node:net';
8
9
  import crypto from 'node:crypto';
9
10
  import { NodeHtmlMarkdown } from 'node-html-markdown';
@@ -190,9 +191,11 @@ export async function validateUrlForSSRF(url: string): Promise<void> {
190
191
  export function ssrfSafeLookup(
191
192
  hostname: string,
192
193
  options: dnsCb.LookupAllOptions | dnsCb.LookupOneOptions | number | undefined,
193
- callback: (err: NodeJS.ErrnoException | null, address?: any, family?: number) => void,
194
+ callback: (err: NodeJS.ErrnoException | null, address?: string | dnsCb.LookupAddress[], family?: number) => void,
194
195
  // Resolver is injectable for tests; undici calls with the standard 3 args.
195
- resolveImpl: (hostname: string, opts: dnsCb.LookupAllOptions, cb: (err: NodeJS.ErrnoException | null, addresses: dnsCb.LookupAddress[]) => void) => void = dnsCb.lookup as any,
196
+ // `dnsCb.lookup` is an overload set; pin the all-lookup signature this
197
+ // wrapper always invokes.
198
+ resolveImpl: (hostname: string, opts: dnsCb.LookupAllOptions, cb: (err: NodeJS.ErrnoException | null, addresses: dnsCb.LookupAddress[]) => void) => void = dnsCb.lookup as (hostname: string, opts: dnsCb.LookupAllOptions, cb: (err: NodeJS.ErrnoException | null, addresses: dnsCb.LookupAddress[]) => void) => void,
196
199
  ): void {
197
200
  const family = typeof options === 'number' ? options : (options?.family ?? 0);
198
201
  const wantsAll = typeof options === 'object' && options?.all === true;
@@ -293,7 +296,10 @@ export function getSsrfSafeFetcher(): Promise<SsrfSafeFetcher | null> {
293
296
  const { Agent, fetch: undiciFetch } = await import('undici');
294
297
  return {
295
298
  fetch: undiciFetch as unknown as SsrfSafeFetcher['fetch'],
296
- dispatcher: new Agent({ connect: { lookup: ssrfSafeLookup } }),
299
+ // node:net's LookupFunction pins the callback to `string | LookupAddress[]`
300
+ // (no undefined); the wrapper's callback allows undefined for the single
301
+ // resolution, so the two signatures differ by exactly that — a double cast.
302
+ dispatcher: new Agent({ connect: { lookup: ssrfSafeLookup as unknown as LookupFunction } }),
297
303
  };
298
304
  } catch (e) {
299
305
  logger.warn(`[Scrapers] undici unavailable; connect-time SSRF pinning disabled (request-time validation still active): ${e instanceof Error ? e.message : String(e)}`);
@@ -34,6 +34,17 @@ import { cacheScrapedContent } from '../utils/shared-links.ts';
34
34
  // identical in-process fallback); same export name and contract as before.
35
35
  import { extractPdfToMarkdown } from './pdf-extraction.ts';
36
36
 
37
+ /**
38
+ * The browser worker's scrape result shape. `buffer` is the pre-bufferB64
39
+ * legacy shape (a raw Uint8Array, or the JSON-roundtripped {type:'Buffer',
40
+ * data:[...]}), kept so a mixed-version leader/follower pair keeps working.
41
+ */
42
+ type BrowserScrapeResult = {
43
+ buffer?: unknown;
44
+ bufferB64?: string;
45
+ html?: string;
46
+ };
47
+
37
48
  /** Backoff before the fetch layer's single transient retry. */
38
49
  const FETCH_RETRY_DELAY_MS = 250;
39
50
 
@@ -321,7 +332,7 @@ async function scrapeWithFetch(url: string, signal?: AbortSignal): Promise<Scrap
321
332
  async function scrapeWithStealthBrowser(_url: string, config?: Config, signal?: AbortSignal, sessionId?: string, container: ServiceContainer = getServiceContainer()): Promise<ScrapeLayerResult> {
322
333
  const browserStart = Date.now();
323
334
  try {
324
- const result = await runBrowserTask<any>({ url: _url, sessionId }, 'scrape', config, signal, 1, container);
335
+ const result = await runBrowserTask<BrowserScrapeResult>({ url: _url, sessionId }, 'scrape', config, signal, 1, container);
325
336
  const browserDuration = Date.now() - browserStart;
326
337
 
327
338
  // PDF bytes travel base64-encoded (bufferB64): the worker result crosses the
@@ -331,15 +342,19 @@ async function scrapeWithStealthBrowser(_url: string, config?: Config, signal?:
331
342
  // extraction ran on nothing and its error string was cached as a "success".
332
343
  // The JSON-roundtripped legacy shape is still decoded so a mixed-version
333
344
  // leader/follower pair keeps working.
334
- const legacyBuffer = result.buffer;
335
- const pdfBytes: Buffer | null =
336
- typeof result.bufferB64 === 'string'
337
- ? Buffer.from(result.bufferB64, 'base64')
338
- : Array.isArray(legacyBuffer?.data)
339
- ? Buffer.from(legacyBuffer.data)
340
- : legacyBuffer instanceof Uint8Array
341
- ? Buffer.from(legacyBuffer)
342
- : null;
345
+ // `buffer` is the pre-bufferB64 legacy shape (a raw Uint8Array, or the
346
+ // JSON-roundtripped {type:'Buffer',data:[...]}); narrow it for the decodes below.
347
+ const legacyBuffer = result.buffer as { data?: number[] } | Uint8Array | null | undefined;
348
+ let pdfBytes: Buffer | null;
349
+ if (typeof result.bufferB64 === 'string') {
350
+ pdfBytes = Buffer.from(result.bufferB64, 'base64');
351
+ } else if (legacyBuffer && !(legacyBuffer instanceof Uint8Array) && Array.isArray(legacyBuffer.data)) {
352
+ pdfBytes = Buffer.from(legacyBuffer.data);
353
+ } else if (legacyBuffer instanceof Uint8Array) {
354
+ pdfBytes = Buffer.from(legacyBuffer);
355
+ } else {
356
+ pdfBytes = null;
357
+ }
343
358
 
344
359
  if (pdfBytes !== null) {
345
360
  const markdown = await extractPdfToMarkdown(pdfBytes);