pi-querit 1.1.0 → 1.1.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.
- package/LICENSE +21 -21
- package/README.md +186 -186
- package/index.ts +2 -0
- package/package.json +64 -63
- package/src/client.ts +385 -385
- package/src/config.ts +200 -200
- package/src/format.ts +101 -105
- package/src/index.ts +378 -378
- package/src/output.ts +138 -138
- package/src/sanitize.ts +97 -97
- package/src/setup.ts +330 -330
package/src/config.ts
CHANGED
|
@@ -1,200 +1,200 @@
|
|
|
1
|
-
import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
3
|
-
import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
|
|
5
|
-
export const QUERIT_CONFIG_FILE = "querit-search.json";
|
|
6
|
-
|
|
7
|
-
export const COUNTRY_VALUES = [
|
|
8
|
-
"argentina",
|
|
9
|
-
"australia",
|
|
10
|
-
"brazil",
|
|
11
|
-
"canada",
|
|
12
|
-
"colombia",
|
|
13
|
-
"france",
|
|
14
|
-
"germany",
|
|
15
|
-
"india",
|
|
16
|
-
"indonesia",
|
|
17
|
-
"japan",
|
|
18
|
-
"mexico",
|
|
19
|
-
"nigeria",
|
|
20
|
-
"philippines",
|
|
21
|
-
"south korea",
|
|
22
|
-
"spain",
|
|
23
|
-
"united kingdom",
|
|
24
|
-
"united states",
|
|
25
|
-
] as const;
|
|
26
|
-
|
|
27
|
-
export const LANGUAGE_VALUES = [
|
|
28
|
-
"english",
|
|
29
|
-
"japanese",
|
|
30
|
-
"korean",
|
|
31
|
-
"german",
|
|
32
|
-
"french",
|
|
33
|
-
"spanish",
|
|
34
|
-
"portuguese",
|
|
35
|
-
] as const;
|
|
36
|
-
|
|
37
|
-
export type QueritCountry = (typeof COUNTRY_VALUES)[number];
|
|
38
|
-
export type QueritLanguage = (typeof LANGUAGE_VALUES)[number];
|
|
39
|
-
|
|
40
|
-
export interface QueritSearchDefaults {
|
|
41
|
-
count?: number;
|
|
42
|
-
includeDomains?: string[];
|
|
43
|
-
excludeDomains?: string[];
|
|
44
|
-
timeRange?: string;
|
|
45
|
-
countries?: QueritCountry[];
|
|
46
|
-
languages?: QueritLanguage[];
|
|
47
|
-
includeContent?: boolean;
|
|
48
|
-
chunksPerDoc?: number;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export interface QueritConfig {
|
|
52
|
-
apiKey: string;
|
|
53
|
-
search?: QueritSearchDefaults;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export interface QueritConfigSettings {
|
|
57
|
-
search?: QueritSearchDefaults;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export interface ApiKeyResolutionOptions {
|
|
61
|
-
configPath?: string;
|
|
62
|
-
env?: NodeJS.ProcessEnv;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export function getQueritConfigPath(agentDir = getAgentDir()): string {
|
|
66
|
-
return join(agentDir, QUERIT_CONFIG_FILE);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export async function loadQueritConfig(configPath = getQueritConfigPath()): Promise<QueritConfig | undefined> {
|
|
70
|
-
let text: string;
|
|
71
|
-
try {
|
|
72
|
-
text = await readFile(configPath, "utf8");
|
|
73
|
-
} catch (error) {
|
|
74
|
-
if (isNodeError(error) && error.code === "ENOENT") return undefined;
|
|
75
|
-
throw new Error(`Could not read Querit configuration at ${configPath}: ${errorMessage(error)}`, {
|
|
76
|
-
cause: error,
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
let parsed: unknown;
|
|
81
|
-
try {
|
|
82
|
-
parsed = JSON.parse(text);
|
|
83
|
-
} catch (error) {
|
|
84
|
-
throw new Error(`Querit configuration at ${configPath} is not valid JSON.`, { cause: error });
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
if (!isRecord(parsed) || typeof parsed.apiKey !== "string" || !parsed.apiKey.trim()) {
|
|
88
|
-
throw new Error(`Querit configuration at ${configPath} must contain a non-empty "apiKey" string.`);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const search = parseSearchDefaults(parsed.search);
|
|
92
|
-
|
|
93
|
-
return {
|
|
94
|
-
apiKey: parsed.apiKey.trim(),
|
|
95
|
-
...(search === undefined ? {} : { search }),
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export async function resolveQueritApiKey(options: ApiKeyResolutionOptions = {}): Promise<string | undefined> {
|
|
100
|
-
const environmentKey = (options.env ?? process.env).QUERIT_API_KEY?.trim();
|
|
101
|
-
if (environmentKey) return environmentKey;
|
|
102
|
-
|
|
103
|
-
const config = await loadQueritConfig(options.configPath ?? getQueritConfigPath());
|
|
104
|
-
return config?.apiKey || undefined;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
export async function saveQueritConfig(
|
|
108
|
-
apiKey: string,
|
|
109
|
-
configPath = getQueritConfigPath(),
|
|
110
|
-
settings: QueritConfigSettings = {},
|
|
111
|
-
): Promise<void> {
|
|
112
|
-
const normalizedKey = apiKey.trim();
|
|
113
|
-
if (!normalizedKey) throw new Error("Cannot save an empty Querit API key.");
|
|
114
|
-
const search = settings.search === undefined ? undefined : parseSearchDefaults(settings.search);
|
|
115
|
-
const serializedConfig: QueritConfig = {
|
|
116
|
-
apiKey: normalizedKey,
|
|
117
|
-
...(search === undefined ? {} : { search }),
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
await mkdir(dirname(configPath), { recursive: true });
|
|
121
|
-
await withFileMutationQueue(configPath, async () => {
|
|
122
|
-
const temporaryPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
|
123
|
-
try {
|
|
124
|
-
await writeFile(temporaryPath, `${JSON.stringify(serializedConfig, null, 2)}\n`, {
|
|
125
|
-
encoding: "utf8",
|
|
126
|
-
mode: 0o600,
|
|
127
|
-
});
|
|
128
|
-
await rename(temporaryPath, configPath);
|
|
129
|
-
if (process.platform !== "win32") {
|
|
130
|
-
await chmod(configPath, 0o600);
|
|
131
|
-
}
|
|
132
|
-
} finally {
|
|
133
|
-
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
134
|
-
}
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
export function parseSearchDefaults(value: unknown): QueritSearchDefaults | undefined {
|
|
139
|
-
if (!isRecord(value)) return undefined;
|
|
140
|
-
const defaults: QueritSearchDefaults = {};
|
|
141
|
-
|
|
142
|
-
if (isIntegerInRange(value.count, 1, 20)) defaults.count = value.count;
|
|
143
|
-
if (isIntegerInRange(value.chunksPerDoc, 1, 3)) defaults.chunksPerDoc = value.chunksPerDoc;
|
|
144
|
-
if (typeof value.includeContent === "boolean") defaults.includeContent = value.includeContent;
|
|
145
|
-
if (typeof value.timeRange === "string" && value.timeRange.trim()) {
|
|
146
|
-
defaults.timeRange = value.timeRange.trim().slice(0, 64);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
const includeDomains = parseDomainList(value.includeDomains);
|
|
150
|
-
if (includeDomains !== undefined) defaults.includeDomains = includeDomains;
|
|
151
|
-
const excludeDomains = parseDomainList(value.excludeDomains);
|
|
152
|
-
if (excludeDomains !== undefined) defaults.excludeDomains = excludeDomains;
|
|
153
|
-
const countries = parseEnumList(value.countries, COUNTRY_VALUES);
|
|
154
|
-
if (countries !== undefined) defaults.countries = countries;
|
|
155
|
-
const languages = parseEnumList(value.languages, LANGUAGE_VALUES);
|
|
156
|
-
if (languages !== undefined) defaults.languages = languages;
|
|
157
|
-
|
|
158
|
-
return Object.keys(defaults).length > 0 ? defaults : undefined;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
function isIntegerInRange(value: unknown, min: number, max: number): value is number {
|
|
162
|
-
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
function parseDomainList(value: unknown): string[] | undefined {
|
|
166
|
-
if (!Array.isArray(value)) return undefined;
|
|
167
|
-
const domains = new Set<string>();
|
|
168
|
-
for (const entry of value) {
|
|
169
|
-
if (typeof entry !== "string") continue;
|
|
170
|
-
const domain = entry.trim().toLowerCase();
|
|
171
|
-
if (!domain || domain.length > 253 || /\s/u.test(domain) || !domain.includes(".")) continue;
|
|
172
|
-
domains.add(domain);
|
|
173
|
-
if (domains.size >= 20) break;
|
|
174
|
-
}
|
|
175
|
-
return domains.size > 0 ? [...domains] : undefined;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
function parseEnumList<T extends string>(value: unknown, allowed: readonly T[]): T[] | undefined {
|
|
179
|
-
if (!Array.isArray(value)) return undefined;
|
|
180
|
-
const allowedSet = new Set<string>(allowed);
|
|
181
|
-
const matched = new Set<T>();
|
|
182
|
-
for (const entry of value) {
|
|
183
|
-
if (typeof entry !== "string") continue;
|
|
184
|
-
const normalized = entry.trim().toLowerCase();
|
|
185
|
-
if (allowedSet.has(normalized)) matched.add(normalized as T);
|
|
186
|
-
}
|
|
187
|
-
return matched.size > 0 ? [...matched] : undefined;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
191
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
195
|
-
return error instanceof Error && "code" in error;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
function errorMessage(error: unknown): string {
|
|
199
|
-
return error instanceof Error ? error.message : String(error);
|
|
200
|
-
}
|
|
1
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
|
|
5
|
+
export const QUERIT_CONFIG_FILE = "querit-search.json";
|
|
6
|
+
|
|
7
|
+
export const COUNTRY_VALUES = [
|
|
8
|
+
"argentina",
|
|
9
|
+
"australia",
|
|
10
|
+
"brazil",
|
|
11
|
+
"canada",
|
|
12
|
+
"colombia",
|
|
13
|
+
"france",
|
|
14
|
+
"germany",
|
|
15
|
+
"india",
|
|
16
|
+
"indonesia",
|
|
17
|
+
"japan",
|
|
18
|
+
"mexico",
|
|
19
|
+
"nigeria",
|
|
20
|
+
"philippines",
|
|
21
|
+
"south korea",
|
|
22
|
+
"spain",
|
|
23
|
+
"united kingdom",
|
|
24
|
+
"united states",
|
|
25
|
+
] as const;
|
|
26
|
+
|
|
27
|
+
export const LANGUAGE_VALUES = [
|
|
28
|
+
"english",
|
|
29
|
+
"japanese",
|
|
30
|
+
"korean",
|
|
31
|
+
"german",
|
|
32
|
+
"french",
|
|
33
|
+
"spanish",
|
|
34
|
+
"portuguese",
|
|
35
|
+
] as const;
|
|
36
|
+
|
|
37
|
+
export type QueritCountry = (typeof COUNTRY_VALUES)[number];
|
|
38
|
+
export type QueritLanguage = (typeof LANGUAGE_VALUES)[number];
|
|
39
|
+
|
|
40
|
+
export interface QueritSearchDefaults {
|
|
41
|
+
count?: number;
|
|
42
|
+
includeDomains?: string[];
|
|
43
|
+
excludeDomains?: string[];
|
|
44
|
+
timeRange?: string;
|
|
45
|
+
countries?: QueritCountry[];
|
|
46
|
+
languages?: QueritLanguage[];
|
|
47
|
+
includeContent?: boolean;
|
|
48
|
+
chunksPerDoc?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface QueritConfig {
|
|
52
|
+
apiKey: string;
|
|
53
|
+
search?: QueritSearchDefaults;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface QueritConfigSettings {
|
|
57
|
+
search?: QueritSearchDefaults;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface ApiKeyResolutionOptions {
|
|
61
|
+
configPath?: string;
|
|
62
|
+
env?: NodeJS.ProcessEnv;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function getQueritConfigPath(agentDir = getAgentDir()): string {
|
|
66
|
+
return join(agentDir, QUERIT_CONFIG_FILE);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function loadQueritConfig(configPath = getQueritConfigPath()): Promise<QueritConfig | undefined> {
|
|
70
|
+
let text: string;
|
|
71
|
+
try {
|
|
72
|
+
text = await readFile(configPath, "utf8");
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (isNodeError(error) && error.code === "ENOENT") return undefined;
|
|
75
|
+
throw new Error(`Could not read Querit configuration at ${configPath}: ${errorMessage(error)}`, {
|
|
76
|
+
cause: error,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let parsed: unknown;
|
|
81
|
+
try {
|
|
82
|
+
parsed = JSON.parse(text);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
throw new Error(`Querit configuration at ${configPath} is not valid JSON.`, { cause: error });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (!isRecord(parsed) || typeof parsed.apiKey !== "string" || !parsed.apiKey.trim()) {
|
|
88
|
+
throw new Error(`Querit configuration at ${configPath} must contain a non-empty "apiKey" string.`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const search = parseSearchDefaults(parsed.search);
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
apiKey: parsed.apiKey.trim(),
|
|
95
|
+
...(search === undefined ? {} : { search }),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function resolveQueritApiKey(options: ApiKeyResolutionOptions = {}): Promise<string | undefined> {
|
|
100
|
+
const environmentKey = (options.env ?? process.env).QUERIT_API_KEY?.trim();
|
|
101
|
+
if (environmentKey) return environmentKey;
|
|
102
|
+
|
|
103
|
+
const config = await loadQueritConfig(options.configPath ?? getQueritConfigPath());
|
|
104
|
+
return config?.apiKey || undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function saveQueritConfig(
|
|
108
|
+
apiKey: string,
|
|
109
|
+
configPath = getQueritConfigPath(),
|
|
110
|
+
settings: QueritConfigSettings = {},
|
|
111
|
+
): Promise<void> {
|
|
112
|
+
const normalizedKey = apiKey.trim();
|
|
113
|
+
if (!normalizedKey) throw new Error("Cannot save an empty Querit API key.");
|
|
114
|
+
const search = settings.search === undefined ? undefined : parseSearchDefaults(settings.search);
|
|
115
|
+
const serializedConfig: QueritConfig = {
|
|
116
|
+
apiKey: normalizedKey,
|
|
117
|
+
...(search === undefined ? {} : { search }),
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
await mkdir(dirname(configPath), { recursive: true });
|
|
121
|
+
await withFileMutationQueue(configPath, async () => {
|
|
122
|
+
const temporaryPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
|
123
|
+
try {
|
|
124
|
+
await writeFile(temporaryPath, `${JSON.stringify(serializedConfig, null, 2)}\n`, {
|
|
125
|
+
encoding: "utf8",
|
|
126
|
+
mode: 0o600,
|
|
127
|
+
});
|
|
128
|
+
await rename(temporaryPath, configPath);
|
|
129
|
+
if (process.platform !== "win32") {
|
|
130
|
+
await chmod(configPath, 0o600);
|
|
131
|
+
}
|
|
132
|
+
} finally {
|
|
133
|
+
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function parseSearchDefaults(value: unknown): QueritSearchDefaults | undefined {
|
|
139
|
+
if (!isRecord(value)) return undefined;
|
|
140
|
+
const defaults: QueritSearchDefaults = {};
|
|
141
|
+
|
|
142
|
+
if (isIntegerInRange(value.count, 1, 20)) defaults.count = value.count;
|
|
143
|
+
if (isIntegerInRange(value.chunksPerDoc, 1, 3)) defaults.chunksPerDoc = value.chunksPerDoc;
|
|
144
|
+
if (typeof value.includeContent === "boolean") defaults.includeContent = value.includeContent;
|
|
145
|
+
if (typeof value.timeRange === "string" && value.timeRange.trim()) {
|
|
146
|
+
defaults.timeRange = value.timeRange.trim().slice(0, 64);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const includeDomains = parseDomainList(value.includeDomains);
|
|
150
|
+
if (includeDomains !== undefined) defaults.includeDomains = includeDomains;
|
|
151
|
+
const excludeDomains = parseDomainList(value.excludeDomains);
|
|
152
|
+
if (excludeDomains !== undefined) defaults.excludeDomains = excludeDomains;
|
|
153
|
+
const countries = parseEnumList(value.countries, COUNTRY_VALUES);
|
|
154
|
+
if (countries !== undefined) defaults.countries = countries;
|
|
155
|
+
const languages = parseEnumList(value.languages, LANGUAGE_VALUES);
|
|
156
|
+
if (languages !== undefined) defaults.languages = languages;
|
|
157
|
+
|
|
158
|
+
return Object.keys(defaults).length > 0 ? defaults : undefined;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function isIntegerInRange(value: unknown, min: number, max: number): value is number {
|
|
162
|
+
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function parseDomainList(value: unknown): string[] | undefined {
|
|
166
|
+
if (!Array.isArray(value)) return undefined;
|
|
167
|
+
const domains = new Set<string>();
|
|
168
|
+
for (const entry of value) {
|
|
169
|
+
if (typeof entry !== "string") continue;
|
|
170
|
+
const domain = entry.trim().toLowerCase();
|
|
171
|
+
if (!domain || domain.length > 253 || /\s/u.test(domain) || !domain.includes(".")) continue;
|
|
172
|
+
domains.add(domain);
|
|
173
|
+
if (domains.size >= 20) break;
|
|
174
|
+
}
|
|
175
|
+
return domains.size > 0 ? [...domains] : undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function parseEnumList<T extends string>(value: unknown, allowed: readonly T[]): T[] | undefined {
|
|
179
|
+
if (!Array.isArray(value)) return undefined;
|
|
180
|
+
const allowedSet = new Set<string>(allowed);
|
|
181
|
+
const matched = new Set<T>();
|
|
182
|
+
for (const entry of value) {
|
|
183
|
+
if (typeof entry !== "string") continue;
|
|
184
|
+
const normalized = entry.trim().toLowerCase();
|
|
185
|
+
if (allowedSet.has(normalized)) matched.add(normalized as T);
|
|
186
|
+
}
|
|
187
|
+
return matched.size > 0 ? [...matched] : undefined;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
191
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
195
|
+
return error instanceof Error && "code" in error;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function errorMessage(error: unknown): string {
|
|
199
|
+
return error instanceof Error ? error.message : String(error);
|
|
200
|
+
}
|
package/src/format.ts
CHANGED
|
@@ -1,105 +1,101 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
QueritContentsResponse,
|
|
3
|
-
QueritSearchResponse,
|
|
4
|
-
} from "./client.js";
|
|
5
|
-
import { sanitizeTerminalText } from "./sanitize.js";
|
|
6
|
-
|
|
7
|
-
const encoder = new TextEncoder();
|
|
8
|
-
const decoder = new TextDecoder();
|
|
9
|
-
|
|
10
|
-
export function formatSearchResponse(response: QueritSearchResponse): string {
|
|
11
|
-
const lines: string[] = [
|
|
12
|
-
|
|
13
|
-
"",
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
if (result.
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
)
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
lines.push("",
|
|
63
|
-
lines.push(
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
return
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function singleLine(value: string, maxBytes: number): string {
|
|
104
|
-
return truncateUtf8(sanitizeTerminalText(value).replace(/\s+/g, " ").trim(), maxBytes);
|
|
105
|
-
}
|
|
1
|
+
import type {
|
|
2
|
+
QueritContentsResponse,
|
|
3
|
+
QueritSearchResponse,
|
|
4
|
+
} from "./client.js";
|
|
5
|
+
import { sanitizeTerminalText } from "./sanitize.js";
|
|
6
|
+
|
|
7
|
+
const encoder = new TextEncoder();
|
|
8
|
+
const decoder = new TextDecoder();
|
|
9
|
+
|
|
10
|
+
export function formatSearchResponse(response: QueritSearchResponse): string {
|
|
11
|
+
const lines: string[] = [
|
|
12
|
+
`# Querit search results for: ${singleLine(response.query, 1_000)}`,
|
|
13
|
+
`Results: ${response.results.length}${response.took ? ` | Server time: ${singleLine(response.took, 128)}` : ""}${response.searchId ? ` | Search ID: ${singleLine(response.searchId, 128)}` : ""}`,
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
if (response.results.length === 0) {
|
|
17
|
+
lines.push("", "No results found.");
|
|
18
|
+
return lines.join("\n");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
for (const [index, result] of response.results.entries()) {
|
|
22
|
+
lines.push("", `## ${index + 1}. ${singleLine(result.title || result.url, 512)}`);
|
|
23
|
+
lines.push(`URL: ${truncateUtf8(sanitizeTerminalText(result.url), 4_096)}`);
|
|
24
|
+
|
|
25
|
+
const sourceParts = [result.siteName, result.pageAge]
|
|
26
|
+
.filter((value): value is string => Boolean(value))
|
|
27
|
+
.map((value) => singleLine(value, 512));
|
|
28
|
+
if (sourceParts.length > 0) lines.push(`Source: ${sourceParts.join(" | ")}`);
|
|
29
|
+
if (result.snippet) lines.push(`Snippet: ${singleLine(result.snippet, 2_048)}`);
|
|
30
|
+
|
|
31
|
+
if (result.sentences.length > 0) {
|
|
32
|
+
lines.push("Content excerpts:");
|
|
33
|
+
for (const sentence of result.sentences) {
|
|
34
|
+
lines.push(`- ${truncateUtf8(sanitizeTerminalText(sentence), 4_096)}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return lines.join("\n");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function formatContentsResponse(
|
|
43
|
+
response: QueritContentsResponse,
|
|
44
|
+
requestedUrls: string[],
|
|
45
|
+
format: "text" | "markdown" | "html",
|
|
46
|
+
): string {
|
|
47
|
+
const successfulStatuses = response.statuses.filter((status) => status.status === "success").length;
|
|
48
|
+
const failedStatuses = response.statuses.filter((status) => status.status === "failed").length;
|
|
49
|
+
const lines: string[] = [
|
|
50
|
+
"# Querit fetched contents",
|
|
51
|
+
`Requested: ${requestedUrls.length} | Returned: ${response.results.length} | Successful: ${successfulStatuses} | Failed: ${failedStatuses}${response.searchTime === undefined ? "" : ` | Server time: ${response.searchTime}s`}${response.searchId ? ` | Search ID: ${singleLine(response.searchId, 128)}` : ""}`,
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
const returnedKeys = new Set<string>();
|
|
55
|
+
for (const [index, result] of response.results.entries()) {
|
|
56
|
+
returnedKeys.add(urlMatchKey(result.url));
|
|
57
|
+
const title = result.metadata?.title || result.url;
|
|
58
|
+
lines.push("", `## ${index + 1}. ${singleLine(title, 512)}`);
|
|
59
|
+
lines.push(`URL: ${truncateUtf8(sanitizeTerminalText(result.url), 4_096)}`);
|
|
60
|
+
if (result.metadata?.siteName) lines.push(`Site: ${singleLine(result.metadata.siteName, 512)}`);
|
|
61
|
+
if (result.metadata?.publishTime) lines.push(`Published: ${singleLine(result.metadata.publishTime, 128)}`);
|
|
62
|
+
lines.push(`Format: ${format}`, "", "--- BEGIN PAGE CONTENT ---");
|
|
63
|
+
lines.push(result.content ? sanitizeTerminalText(result.content) : "[No content returned]");
|
|
64
|
+
lines.push("--- END PAGE CONTENT ---");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const unavailable = requestedUrls.filter((url) => !returnedKeys.has(urlMatchKey(url)));
|
|
68
|
+
if (unavailable.length > 0) {
|
|
69
|
+
lines.push("", "## URLs without returned content");
|
|
70
|
+
for (const url of unavailable) lines.push(`- ${truncateUtf8(sanitizeTerminalText(url), 4_096)}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return lines.join("\n");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Relaxed URL key for matching requested vs returned URLs.
|
|
78
|
+
* Ignores protocol and trailing slashes so that redirects
|
|
79
|
+
* (e.g. http://a.com → https://a.com/) are not reported as unavailable.
|
|
80
|
+
*/
|
|
81
|
+
function urlMatchKey(raw: string): string {
|
|
82
|
+
try {
|
|
83
|
+
const parsed = new URL(raw);
|
|
84
|
+
return `${parsed.hostname}${parsed.pathname.replace(/\/+$/u, "")}`;
|
|
85
|
+
} catch {
|
|
86
|
+
return raw;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function truncateUtf8(value: string, maxBytes: number): string {
|
|
91
|
+
const bytes = encoder.encode(value);
|
|
92
|
+
if (bytes.byteLength <= maxBytes) return value;
|
|
93
|
+
if (maxBytes <= 3) return ".".repeat(Math.max(0, maxBytes));
|
|
94
|
+
|
|
95
|
+
const prefix = decoder.decode(bytes.slice(0, maxBytes - 3)).replace(/\uFFFD+$/u, "");
|
|
96
|
+
return `${prefix}...`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function singleLine(value: string, maxBytes: number): string {
|
|
100
|
+
return truncateUtf8(sanitizeTerminalText(value).replace(/\s+/g, " ").trim(), maxBytes);
|
|
101
|
+
}
|