@apmantza/greedysearch-pi 1.8.0 → 1.8.2

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.
@@ -1,131 +1,131 @@
1
- /**
2
- * Shared types, utilities, and runSearch for Pi tool handlers
3
- */
4
-
5
- import { spawn } from "node:child_process";
6
- import { existsSync } from "node:fs";
7
- import { join } from "node:path";
8
- import type { ProgressUpdate, ToolResult } from "../types.js";
9
-
10
- export type { ProgressUpdate, ToolResult } from "../types.js";
11
-
12
- // Canonical source is src/search/constants.mjs — keep in sync
13
- const ALL_ENGINES = ["perplexity", "bing", "google"] as const;
14
- export { ALL_ENGINES };
15
-
16
- /**
17
- * Check if the CDP module is available in the package directory
18
- */
19
- export function cdpAvailable(baseDir: string): boolean {
20
- return existsSync(join(baseDir, "bin", "cdp.mjs"));
21
- }
22
-
23
- /**
24
- * Create a "cdp missing" error result
25
- */
26
- export function cdpMissingResult(): ToolResult {
27
- return {
28
- content: [
29
- {
30
- type: "text",
31
- text: "cdp.mjs missing — try reinstalling: pi install git:github.com/apmantza/GreedySearch-pi",
32
- },
33
- ],
34
- details: {} as Record<string, unknown>,
35
- };
36
- }
37
-
38
- /**
39
- * Create an error result with a message
40
- */
41
- export function errorResult(prefix: string, e: unknown): ToolResult {
42
- const msg = e instanceof Error ? e.message : String(e);
43
- return {
44
- content: [{ type: "text", text: `${prefix}: ${msg}` }],
45
- details: {} as Record<string, unknown>,
46
- };
47
- }
48
-
49
- /**
50
- * Spawn search.mjs and collect JSON results, with progress streaming via stderr.
51
- * Shared by greedy_search and deep_research tool handlers.
52
- */
53
- export function runSearch(
54
- engine: string,
55
- query: string,
56
- flags: string[],
57
- searchBin: string,
58
- signal?: AbortSignal,
59
- onProgress?: (engine: string, status: "done" | "error") => void,
60
- ): Promise<Record<string, unknown>> {
61
- return new Promise((resolve, reject) => {
62
- const proc = spawn(
63
- "node",
64
- [searchBin, engine, "--inline", ...flags, query],
65
- { stdio: ["ignore", "pipe", "pipe"] },
66
- );
67
- let out = "";
68
- let err = "";
69
-
70
- const onAbort = () => {
71
- proc.kill("SIGTERM");
72
- reject(new Error("Aborted"));
73
- };
74
- signal?.addEventListener("abort", onAbort, { once: true });
75
-
76
- proc.stderr.on("data", (d: Buffer) => {
77
- err += d;
78
- for (const line of d.toString().split("\n")) {
79
- const match = line.match(/^PROGRESS:(\w+):(done|error)$/);
80
- if (match && onProgress) {
81
- onProgress(match[1], match[2] as "done" | "error");
82
- }
83
- }
84
- });
85
-
86
- proc.stdout.on("data", (d: Buffer) => (out += d));
87
- proc.on("close", (code: number) => {
88
- signal?.removeEventListener("abort", onAbort);
89
- if (code !== 0) {
90
- reject(new Error(err.trim() || `search.mjs exited with code ${code}`));
91
- } else {
92
- try {
93
- resolve(JSON.parse(out.trim()));
94
- } catch {
95
- reject(new Error(`Invalid JSON from search.mjs: ${out.slice(0, 200)}`));
96
- }
97
- }
98
- });
99
- });
100
- }
101
-
102
- /**
103
- * Build a progress callback that tracks completed engines.
104
- * Returns an onProgress function suitable for runSearch.
105
- */
106
- export function makeProgressTracker(
107
- engines: readonly string[],
108
- onUpdate: ((update: ProgressUpdate) => void) | undefined,
109
- suffix: "Searching" | "Researching",
110
- depth: string,
111
- ) {
112
- const completed = new Set<string>();
113
-
114
- return (eng: string, _status: "done" | "error") => {
115
- completed.add(eng);
116
- const parts: string[] = [];
117
- for (const e of engines) {
118
- if (completed.has(e)) parts.push(`✅ ${e} done`);
119
- else parts.push(`⏳ ${e}`);
120
- }
121
- if (depth !== "fast" && completed.size >= 3)
122
- parts.push("🔄 synthesizing");
123
-
124
- onUpdate?.({
125
- content: [
126
- { type: "text", text: `**${suffix}...** ${parts.join(" · ")}` },
127
- ],
128
- details: { _progress: true },
129
- } satisfies ProgressUpdate);
130
- };
1
+ /**
2
+ * Shared types, utilities, and runSearch for Pi tool handlers
3
+ */
4
+
5
+ import { spawn } from "node:child_process";
6
+ import { existsSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import type { ProgressUpdate, ToolResult } from "../types.js";
9
+
10
+ export type { ProgressUpdate, ToolResult } from "../types.js";
11
+
12
+ // Canonical source is src/search/constants.mjs — keep in sync
13
+ const ALL_ENGINES = ["perplexity", "bing", "google"] as const;
14
+ export { ALL_ENGINES };
15
+
16
+ /**
17
+ * Check if the CDP module is available in the package directory
18
+ */
19
+ export function cdpAvailable(baseDir: string): boolean {
20
+ return existsSync(join(baseDir, "bin", "cdp.mjs"));
21
+ }
22
+
23
+ /**
24
+ * Create a "cdp missing" error result
25
+ */
26
+ export function cdpMissingResult(): ToolResult {
27
+ return {
28
+ content: [
29
+ {
30
+ type: "text",
31
+ text: "cdp.mjs missing — try reinstalling: pi install git:github.com/apmantza/GreedySearch-pi",
32
+ },
33
+ ],
34
+ details: {} as Record<string, unknown>,
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Create an error result with a message
40
+ */
41
+ export function errorResult(prefix: string, e: unknown): ToolResult {
42
+ const msg = e instanceof Error ? e.message : String(e);
43
+ return {
44
+ content: [{ type: "text", text: `${prefix}: ${msg}` }],
45
+ details: {} as Record<string, unknown>,
46
+ };
47
+ }
48
+
49
+ /**
50
+ * Spawn search.mjs and collect JSON results, with progress streaming via stderr.
51
+ * Shared by greedy_search and deep_research tool handlers.
52
+ */
53
+ export function runSearch(
54
+ engine: string,
55
+ query: string,
56
+ flags: string[],
57
+ searchBin: string,
58
+ signal?: AbortSignal,
59
+ onProgress?: (engine: string, status: "done" | "error") => void,
60
+ ): Promise<Record<string, unknown>> {
61
+ return new Promise((resolve, reject) => {
62
+ const proc = spawn(
63
+ "node",
64
+ [searchBin, engine, "--inline", ...flags, query],
65
+ { stdio: ["ignore", "pipe", "pipe"] },
66
+ );
67
+ let out = "";
68
+ let err = "";
69
+
70
+ const onAbort = () => {
71
+ proc.kill("SIGTERM");
72
+ reject(new Error("Aborted"));
73
+ };
74
+ signal?.addEventListener("abort", onAbort, { once: true });
75
+
76
+ proc.stderr.on("data", (d: Buffer) => {
77
+ err += d;
78
+ for (const line of d.toString().split("\n")) {
79
+ const match = line.match(/^PROGRESS:(\w+):(done|error)$/);
80
+ if (match && onProgress) {
81
+ onProgress(match[1], match[2] as "done" | "error");
82
+ }
83
+ }
84
+ });
85
+
86
+ proc.stdout.on("data", (d: Buffer) => (out += d));
87
+ proc.on("close", (code: number) => {
88
+ signal?.removeEventListener("abort", onAbort);
89
+ if (code !== 0) {
90
+ reject(new Error(err.trim() || `search.mjs exited with code ${code}`));
91
+ } else {
92
+ try {
93
+ resolve(JSON.parse(out.trim()));
94
+ } catch {
95
+ reject(new Error(`Invalid JSON from search.mjs: ${out.slice(0, 200)}`));
96
+ }
97
+ }
98
+ });
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Build a progress callback that tracks completed engines.
104
+ * Returns an onProgress function suitable for runSearch.
105
+ */
106
+ export function makeProgressTracker(
107
+ engines: readonly string[],
108
+ onUpdate: ((update: ProgressUpdate) => void) | undefined,
109
+ suffix: "Searching" | "Researching",
110
+ depth: string,
111
+ ) {
112
+ const completed = new Set<string>();
113
+
114
+ return (eng: string, _status: "done" | "error") => {
115
+ completed.add(eng);
116
+ const parts: string[] = [];
117
+ for (const e of engines) {
118
+ if (completed.has(e)) parts.push(`✅ ${e} done`);
119
+ else parts.push(`⏳ ${e}`);
120
+ }
121
+ if (depth !== "fast" && completed.size >= 3)
122
+ parts.push("🔄 synthesizing");
123
+
124
+ onUpdate?.({
125
+ content: [
126
+ { type: "text", text: `**${suffix}...** ${parts.join(" · ")}` },
127
+ ],
128
+ details: { _progress: true },
129
+ } satisfies ProgressUpdate);
130
+ };
131
131
  }
package/src/types.ts CHANGED
@@ -1,104 +1,104 @@
1
- /**
2
- * TypeScript interfaces for GreedySearch data structures
3
- *
4
- * These types document the shape of data flowing between modules.
5
- * They can be imported by TypeScript files (index.ts, tool handlers, formatters)
6
- * and used for type safety without runtime overhead.
7
- */
8
-
9
- // ============================================================================
10
- // Search Result Types
11
- // ============================================================================
12
-
13
- /** A single source extracted from search results */
14
- export interface Source {
15
- url: string;
16
- title: string;
17
- type?: "official-docs" | "maintainer-blog" | "repo" | "community" | "website";
18
- domain?: string;
19
- snippet?: string;
20
- }
21
-
22
- /** Result from a single search engine */
23
- export interface SearchResult {
24
- engine: string;
25
- answer: string;
26
- sources: Source[];
27
- url?: string;
28
- query?: string;
29
- error?: string;
30
- }
31
-
32
- /** Synthesis result combining multiple engine results */
33
- export interface SynthesisResult {
34
- answer: string;
35
- agreementLevel?: "consensus" | "majority" | "mixed" | "conflicting";
36
- claims?: Claim[];
37
- sourceIds?: string[];
38
- confidence?: ConfidenceMetrics;
39
- }
40
-
41
- /** A single claim within a synthesis */
42
- export interface Claim {
43
- text: string;
44
- sourceIds: string[];
45
- confidence?: "high" | "medium" | "low";
46
- }
47
-
48
- /** Confidence metrics for a synthesis */
49
- export interface ConfidenceMetrics {
50
- overall: number; // 0-1
51
- consensus: number; // fraction of engines agreeing
52
- sourceCount: number;
53
- engineCount: number;
54
- }
55
-
56
- // ============================================================================
57
- // Source Registry Types
58
- // ============================================================================
59
-
60
- /** A classified source in the registry */
61
- export interface ClassifiedSource extends Source {
62
- engineOrigin: string[];
63
- isOfficial: boolean;
64
- consensus: number; // fraction of engines citing this source
65
- }
66
-
67
- // ============================================================================
68
- // Tool Result Types
69
- // ============================================================================
70
-
71
- /** Progress update sent via onUpdate during long-running searches */
72
- export interface ProgressUpdate {
73
- content: Array<{ type: "text"; text: string }>;
74
- details: { _progress: true };
75
- }
76
-
77
- /** Pi tool result format */
78
- export interface ToolResult {
79
- content: Array<{ type: "text"; text: string }>;
80
- details: Record<string, unknown>;
81
- }
82
-
83
- // ============================================================================
84
- // Engine Configuration Types
85
- // ============================================================================
86
-
87
- /** Engine definition for the ENGINES map */
88
- export interface EngineConfig {
89
- /** Extractor script filename (e.g. "perplexity.mjs") */
90
- script: string;
91
- /** Human-readable label for progress messages */
92
- label: string;
93
- /** Domain pattern for source matching */
94
- domain: string;
95
- /** URL pattern for the engine */
96
- url: string;
97
- }
98
-
99
- // ============================================================================
100
- // Constants
101
- // ============================================================================
102
-
103
- // Runtime defaults are in src/search/defaults.mjs (since .ts files can't be
1
+ /**
2
+ * TypeScript interfaces for GreedySearch data structures
3
+ *
4
+ * These types document the shape of data flowing between modules.
5
+ * They can be imported by TypeScript files (index.ts, tool handlers, formatters)
6
+ * and used for type safety without runtime overhead.
7
+ */
8
+
9
+ // ============================================================================
10
+ // Search Result Types
11
+ // ============================================================================
12
+
13
+ /** A single source extracted from search results */
14
+ export interface Source {
15
+ url: string;
16
+ title: string;
17
+ type?: "official-docs" | "maintainer-blog" | "repo" | "community" | "website";
18
+ domain?: string;
19
+ snippet?: string;
20
+ }
21
+
22
+ /** Result from a single search engine */
23
+ export interface SearchResult {
24
+ engine: string;
25
+ answer: string;
26
+ sources: Source[];
27
+ url?: string;
28
+ query?: string;
29
+ error?: string;
30
+ }
31
+
32
+ /** Synthesis result combining multiple engine results */
33
+ export interface SynthesisResult {
34
+ answer: string;
35
+ agreementLevel?: "consensus" | "majority" | "mixed" | "conflicting";
36
+ claims?: Claim[];
37
+ sourceIds?: string[];
38
+ confidence?: ConfidenceMetrics;
39
+ }
40
+
41
+ /** A single claim within a synthesis */
42
+ export interface Claim {
43
+ text: string;
44
+ sourceIds: string[];
45
+ confidence?: "high" | "medium" | "low";
46
+ }
47
+
48
+ /** Confidence metrics for a synthesis */
49
+ export interface ConfidenceMetrics {
50
+ overall: number; // 0-1
51
+ consensus: number; // fraction of engines agreeing
52
+ sourceCount: number;
53
+ engineCount: number;
54
+ }
55
+
56
+ // ============================================================================
57
+ // Source Registry Types
58
+ // ============================================================================
59
+
60
+ /** A classified source in the registry */
61
+ export interface ClassifiedSource extends Source {
62
+ engineOrigin: string[];
63
+ isOfficial: boolean;
64
+ consensus: number; // fraction of engines citing this source
65
+ }
66
+
67
+ // ============================================================================
68
+ // Tool Result Types
69
+ // ============================================================================
70
+
71
+ /** Progress update sent via onUpdate during long-running searches */
72
+ export interface ProgressUpdate {
73
+ content: Array<{ type: "text"; text: string }>;
74
+ details: { _progress: true };
75
+ }
76
+
77
+ /** Pi tool result format */
78
+ export interface ToolResult {
79
+ content: Array<{ type: "text"; text: string }>;
80
+ details: Record<string, unknown>;
81
+ }
82
+
83
+ // ============================================================================
84
+ // Engine Configuration Types
85
+ // ============================================================================
86
+
87
+ /** Engine definition for the ENGINES map */
88
+ export interface EngineConfig {
89
+ /** Extractor script filename (e.g. "perplexity.mjs") */
90
+ script: string;
91
+ /** Human-readable label for progress messages */
92
+ label: string;
93
+ /** Domain pattern for source matching */
94
+ domain: string;
95
+ /** URL pattern for the engine */
96
+ url: string;
97
+ }
98
+
99
+ // ============================================================================
100
+ // Constants
101
+ // ============================================================================
102
+
103
+ // Runtime defaults are in src/search/defaults.mjs (since .ts files can't be
104
104
  // imported directly by Node.js). Import DEFAULTS from there for runtime values.