Skip to content

Commit 95d7d95

Browse files
authored
feat(tools): support batched tool search queries (#118623)
* feat(tools): support batched tool search queries * fix(tools): harden batched tool search * fix(tools): preserve batch search contracts * fix(tools): bound batch search processing * fix(tools): bound batch candidate metadata * fix(tools): preserve callable batch candidates * docs(tools): align batch search QA proof * refactor(tools): isolate search request parsing * test(qa): strengthen structured search proof * test(qa): align structured directory proof * fix(tools): preserve scalar search compatibility * test(qa): disable batch scenario retries * test(qa): allow direct-only tools in structured proof * test(qa): verify nested catalog call result * test(qa): remove obsolete result scanner
1 parent f3186b0 commit 95d7d95

14 files changed

Lines changed: 1551 additions & 129 deletions

‎docs/tools/tool-search.md‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,40 @@ The structured fallback mode exposes the same operations as tools:
214214
- `tool_describe`
215215
- `tool_call`
216216

217+
`tool_search` accepts either the existing single-query shape or a batch of
218+
independent queries:
219+
220+
```json
221+
{
222+
"query": "today's calendar events",
223+
"limit": 3
224+
}
225+
```
226+
227+
```json
228+
{
229+
"queries": [
230+
{ "query": "today's calendar events", "limit": 3 },
231+
{ "query": "Slack messages needing attention", "limit": 3 }
232+
]
233+
}
234+
```
235+
236+
Single-query calls continue to return the compact candidate array directly.
237+
Batch calls return `{ results: [{ query, candidates }] }` in request order. Each
238+
query uses the same effective catalog, ranking, filtering, and per-query limit
239+
as an ordinary search; a candidate may appear in more than one result group.
240+
Descriptions are compacted before output. If the complete batch would exceed
241+
the 4,000-character response budget, lower-ranked candidates are removed and
242+
the response includes `truncated: true`. A result group that lost candidates
243+
also includes `truncated: true`, so an empty truncated group cannot be mistaken
244+
for a query that had no matches.
245+
Omitted per-query limits use `searchDefaultLimit`. The effective limits in one
246+
batch may request at most 50 candidates in total. A batch accepts at most 16
247+
queries, with at most 512 characters per query and 512 UTF-8 bytes across the
248+
serialized query list. Invalid batches fail as one request, while a valid query
249+
with no matches returns an empty `candidates` array.
250+
217251
Directory mode exposes:
218252

219253
- `tool_search`
@@ -355,15 +389,16 @@ answer:
355389

356390
## E2E validation
357391

358-
The QA Lab gateway scenario proves both paths with the OpenClaw runtime:
392+
The QA Lab gateway scenario proves all three paths with the OpenClaw runtime:
359393

360394
```bash
361395
pnpm openclaw qa suite --provider-mode mock-openai --scenario tool-search-gateway-e2e
362396
```
363397

364398
It creates a temporary fake plugin with a large tool catalog, starts the mock
365-
OpenAI provider, starts a Gateway once in direct mode and once with Tool Search
366-
enabled, then compares provider request payloads and session logs.
399+
OpenAI provider, then runs the Gateway in direct, code-mode Tool Search, and
400+
structured Tool Search modes. It compares provider request payloads for direct
401+
and code mode, then verifies session logs and tool flow across all three lanes.
367402

368403
The regression proves:
369404

@@ -373,6 +408,8 @@ The regression proves:
373408
4. Tool Search exposes only the compact bridge plus any direct-only tools.
374409
5. The Tool Search request payload is smaller for the large fake catalog.
375410
6. Session logs show the expected tool-call counts and bridged call telemetry.
411+
7. Structured mode resolves two queries with one `tool_search` call before the
412+
selected plugin tool runs through `tool_call`.
376413

377414
## Failure behavior
378415

‎extensions/qa-lab/src/fixture-utils.ts‎

Lines changed: 30 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -303,107 +303,68 @@ function sessionLogScanText(line: string): string | null {
303303
}
304304
}
305305

306-
async function countNeedlesInFile(filePath: string, needles: Record<string, string>) {
307-
const text = await fs.readFile(filePath, "utf8").catch(() => "");
308-
const counts = createCounts(needles);
309-
for (const line of text.split(/\r?\n/u)) {
310-
const scanText = sessionLogScanText(line);
311-
if (scanText === null) {
312-
continue;
313-
}
314-
for (const [key, needle] of Object.entries(needles)) {
315-
counts[key] = (counts[key] ?? 0) + countOccurrences(scanText, needle);
316-
}
317-
}
318-
return counts;
319-
}
320-
321306
function resolveAgentSqlitePathFromSessionsDir(sessionsDir: string): string | null {
322307
if (path.basename(sessionsDir) !== "sessions") {
323308
return null;
324309
}
325310
return path.join(path.dirname(sessionsDir), "agent", "openclaw-agent.sqlite");
326311
}
327312

328-
function countNeedlesInSqliteTranscriptEvents(
329-
sqlitePath: string,
330-
needles: Record<string, string>,
331-
): Record<string, number> {
332-
const counts = createCounts(needles);
313+
async function visitSessionLogEvents(
314+
sessionsDir: string,
315+
visit: (eventJson: string) => void,
316+
): Promise<void> {
317+
const files = await fs.readdir(sessionsDir, { recursive: true }).catch(() => []);
318+
for (const file of files) {
319+
if (typeof file !== "string" || !file.endsWith(".jsonl")) {
320+
continue;
321+
}
322+
const text = await fs.readFile(path.join(sessionsDir, file), "utf8").catch(() => "");
323+
for (const line of text.split(/\r?\n/u)) {
324+
visit(line);
325+
}
326+
}
327+
328+
const sqlitePath = resolveAgentSqlitePathFromSessionsDir(sessionsDir);
329+
if (!sqlitePath) {
330+
return;
331+
}
333332
let db: DatabaseSync | null = null;
334333
try {
335334
db = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
336335
const hasTranscriptEvents = db
337336
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'transcript_events'")
338337
.get();
339338
if (!hasTranscriptEvents) {
340-
return counts;
339+
return;
341340
}
342341
const rows = db.prepare("SELECT event_json FROM transcript_events ORDER BY session_id, seq");
343342
for (const row of rows.iterate() as Iterable<{ event_json?: unknown }>) {
344-
if (typeof row.event_json !== "string") {
345-
continue;
346-
}
347-
const scanText = sessionLogScanText(row.event_json);
348-
if (scanText === null) {
349-
continue;
350-
}
351-
for (const [key, needle] of Object.entries(needles)) {
352-
counts[key] = (counts[key] ?? 0) + countOccurrences(scanText, needle);
343+
if (typeof row.event_json === "string") {
344+
visit(row.event_json);
353345
}
354346
}
355-
return counts;
356347
} catch {
357-
return counts;
348+
// Missing or unreadable stores contribute no events.
358349
} finally {
359350
db?.close();
360351
}
361352
}
362353

363-
async function countNeedlesInSqliteTranscriptStore(
364-
sessionsDir: string,
365-
needles: Record<string, string>,
366-
): Promise<Record<string, number>> {
367-
const sqlitePath = resolveAgentSqlitePathFromSessionsDir(sessionsDir);
368-
if (!sqlitePath) {
369-
return createCounts(needles);
370-
}
371-
try {
372-
const stat = await fs.stat(sqlitePath);
373-
if (!stat.isFile()) {
374-
return createCounts(needles);
375-
}
376-
} catch {
377-
return createCounts(needles);
378-
}
379-
return countNeedlesInSqliteTranscriptEvents(sqlitePath, needles);
380-
}
381-
382354
export async function countSessionLogMentions(params: {
383355
sessionsDir: string;
384356
needles: Record<string, string>;
385357
}): Promise<Record<string, number>> {
386358
const counts = createCounts(params.needles);
387-
const files = await fs.readdir(params.sessionsDir, { recursive: true }).catch(() => []);
388-
for (const file of files) {
389-
if (typeof file !== "string" || !file.endsWith(".jsonl")) {
390-
continue;
359+
await visitSessionLogEvents(params.sessionsDir, (eventJson) => {
360+
const scanText = sessionLogScanText(eventJson);
361+
if (scanText === null) {
362+
return;
391363
}
392-
const fileCounts = await countNeedlesInFile(
393-
path.join(params.sessionsDir, file),
394-
params.needles,
395-
);
396-
for (const [key, count] of Object.entries(fileCounts)) {
397-
counts[key] = (counts[key] ?? 0) + count;
364+
for (const [key, needle] of Object.entries(params.needles)) {
365+
counts[key] = (counts[key] ?? 0) + countOccurrences(scanText, needle);
398366
}
399-
}
400-
const sqliteCounts = await countNeedlesInSqliteTranscriptStore(
401-
params.sessionsDir,
402-
params.needles,
403-
);
404-
for (const [key, count] of Object.entries(sqliteCounts)) {
405-
counts[key] = (counts[key] ?? 0) + count;
406-
}
367+
});
407368
return counts;
408369
}
409370

‎extensions/qa-lab/src/providers/mock-openai/mock-openai-tooling.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
// QA Lab mock provider tool planning and memory fixtures.
22
import { createHash } from "node:crypto";
3+
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
34
import { QA_LAB_WEB_SEARCH_DENIED_INPUT_QUERY } from "../../qa-web-search-provider.js";
45
import type { StreamEvent } from "./mock-openai-contracts.js";
56

67
let mockFunctionCallSequence = 0;
78

9+
export const QA_TOOL_SEARCH_SECONDARY_TARGET = "fake_plugin_tool_01";
10+
811
function normalizePromptPathCandidate(candidate: string) {
912
const trimmed = candidate.trim().replace(/^`+|`+$/g, "");
1013
if (!trimmed) {
@@ -216,6 +219,21 @@ export function extractToolSearchTarget(text: string): string | null {
216219
return match?.[1]?.trim() || null;
217220
}
218221

222+
export function toolSearchOutputHasCandidate(output: unknown, targetTool: string): boolean {
223+
if (!isRecord(output) || !Array.isArray(output.results)) {
224+
return false;
225+
}
226+
return output.results.some(
227+
(result) =>
228+
isRecord(result) &&
229+
Array.isArray(result.candidates) &&
230+
result.candidates.some(
231+
(candidate) =>
232+
isRecord(candidate) && (candidate.name === targetTool || candidate.id === targetTool),
233+
),
234+
);
235+
}
236+
219237
export function buildQaToolSearchArgs(
220238
targetTool: string,
221239
failureMode: boolean,

0 commit comments

Comments
 (0)