mirror of
https://github.com/Orkas-AI/Orkas.git
synced 2026-12-03 18:51:21 +08:00
Preserve search evidence and provider cache identity across sessions
This commit is contained in:
@@ -8,6 +8,50 @@
|
||||
|
||||
## 自动化覆盖
|
||||
|
||||
## Shared research and social-analysis scenarios
|
||||
|
||||
### SocialResearcher consolidation and investigation boundary
|
||||
|
||||
The requester confirmed merging SocialResearcher into DeepResearcher and keeping
|
||||
DeepResearcher focused on investigation, not every search. Version 1.0.67
|
||||
advertises evidence synthesis and sample analysis in both selection descriptions;
|
||||
ordinary fact lookup and link finding are explicitly outside the role. Scope is
|
||||
determined by the requested work and deliverable, not by a keyword matcher or a
|
||||
minimum number of searches. A focused brand or social brief remains valid research
|
||||
without requiring a long report.
|
||||
|
||||
| Request / evidence state | Intended result | Failure guarded against |
|
||||
|---|---|---|
|
||||
| Ordinary fact lookup or finding a link | Shared capability-boundary handback if misdirected to this Agent | Turning every search into a research project |
|
||||
| Public social reputation investigation | `social-data` primary route, bounded platforms/keywords/period/sample plan, traceable themes and next experiments | Losing the retired Agent's collection boundaries or treating public samples as complete platform coverage |
|
||||
| Supplied campaign data sufficient for analysis | Validate fields and analyze supported metrics without public collection | Unnecessary fetches, replacing missing denominators with guesses, or forcing deep-report ledgers |
|
||||
| Platform failure or zero results | Preserve completed scope and disclose gaps; do not expand the frozen scope | Inventing discussion, concluding no discussion exists, or trying unrelated platforms |
|
||||
| Social findings need brand context | Only a decision-changing brand extension | Unbounded cross-domain research |
|
||||
| Brand brief or broader/durable investigation | Existing brand chat/file contract or deep-research evidence/resume/report route respectively | Replacing established research paths with a social template |
|
||||
|
||||
### Revenue and cost inputs
|
||||
|
||||
| Input / scenario | Independent expected result |
|
||||
|---|---|
|
||||
| Spend 100, revenue 1,000, matching non-marketing costs 600 | ROAS 10; ROI 300%, with its cost basis |
|
||||
| Revenue 0 versus missing revenue | With explicit zero other costs: ROI -100%; missing revenue: return unavailable |
|
||||
| Revenue known, matching costs unavailable | ROAS computable; profit ROI unavailable |
|
||||
| Spend missing or zero | Return ratios unavailable; explicit zero spend can still produce zero CPC when clicks are positive |
|
||||
| Declared conversion value or explicit interaction value | Separate scenario fields and basis; no substitute for observed revenue/profit and no automatic budget-scaling advice |
|
||||
| Campaign totals plus post amounts | Campaign fields win, including zero/null; only complete post columns are summed when the campaign field is absent |
|
||||
| Partial counters or invalid input | Preserve independently supported metrics; reject invalid numeric/corpus/JSON input with a structured error, not a partial report or traceback |
|
||||
|
||||
### Brand investigation
|
||||
|
||||
| Request / evidence state | Intended result | Failure guarded against |
|
||||
|---|---|---|
|
||||
| Focused company/product profile or Brand DNA | Bounded requested-field brief via `brand-research`, with frozen source/competitor scope and at most one relevant social extension | Forcing deep-research ledgers and a published long report onto a simple brand request |
|
||||
| Positioning, audience, competitors, voice, pricing, proof or content gaps | Sourced facts, company statements, third-party evidence and labeled interpretation; requested fields only | Treating marketing claims as independent proof, or filling optional fields from guesses |
|
||||
| Weak, blocked or missing sources | Disclosed source caveats and missing fields | Declaring no discussion from empty social results, or implying diligence conclusions |
|
||||
| Broader or complex investigation, literature review, market comparison or durable resume | Existing `deep-research` normal/resume/compact route, budget/state retention, claim checks and canonical report delivery | Replacing existing deep investigations with a shallow brand template or losing saved accounting |
|
||||
| Focused brief with / without requested file | Existing `brand-research` chat/file output contract | Unsolicited saved brand files, or suppressing the canonical file on a deep-research route |
|
||||
|
||||
|
||||
Production quality evidence identifies attached outputs from persisted host
|
||||
delivery records and places their contents before working files. Earlier drafts
|
||||
and verification attempts remain available as execution evidence, explicitly
|
||||
@@ -233,8 +277,8 @@ on a live model run is not yet measured.
|
||||
|
||||
## 能力边界与转交
|
||||
|
||||
1. 任务实为知识库沉淀(写入笔记/Notion/Obsidian)、社媒抓取/指标、办公文档成品时,应转交对应入口(知识库/社媒/办公),而非在本 agent 内越权处理。
|
||||
2. 跨 agent 转交应写能力型边界(如「转给知识库管理入口」),不硬编码其他 agent 的显示名。
|
||||
1. Ordinary fact lookup, link finding, knowledge-base writes and final Office artifacts remain outside this research role. Social sampling and campaign analysis now belong to its `social-data` route; they no longer require a separate social Agent.
|
||||
2. Use the shared capability-boundary handback for unsupported work, preserving progress and continuation facts; do not hard-code another Agent's display name or add a transfer protocol.
|
||||
|
||||
## 失败模式与降级
|
||||
|
||||
|
||||
@@ -174,7 +174,7 @@ isolation and rename cases; a TTL-only cache would return stale matches.
|
||||
5. An aborted startup slice must resume automatically when the runtime is idle. A failed batch must retain old files and retry; neither cancellation nor failure may publish a completed index.
|
||||
6. Replace or delete conversations through sync during migration, including replacement after a source read and before its last batch settles. Completion must wait for a stable source; replaced/deleted text must not survive catch-up.
|
||||
|
||||
`test/main/features/search/migration.test.ts` owns these migration, interruption, restart, concurrent-append and sync-race scenarios using isolated temporary workspaces and real SQLite. `search/search_e2e_rebuild.test.ts` adds real-worker SQL failure/recovery, concurrent-writer exclusion, and a 9-million-character performance negative control. Rebuild work must run outside main; during that workload the main timer gap stays below 300 ms and existing-hit query P95 below 200 ms. Full execution-record content, including its final term, remains indexed; private reasoning stays excluded.
|
||||
`test/main/features/search/migration.test.ts` owns these migration, interruption, restart, concurrent-append and sync-race scenarios using isolated temporary workspaces and real SQLite. `search/search_e2e_rebuild.test.ts` adds real-worker SQL failure/recovery, concurrent-writer exclusion, and a 9-million-character performance negative control. Rebuild work must run outside main; the main timer gap and existing-hit query P95 use the shared device-tier limits in `test/helpers/latency-budget.ts`. Hardware defaults and explicit `ORKAS_TEST_PERFORMANCE_TIER=standard|low` select fixed limits before measurement. The main timer gap must also remain below half of the same-work synchronous control; that control need not exceed the absolute allowance on a fast host. Earlier-limit failures remain in the verification history. Full execution-record content, including its final term, remains indexed; private reasoning stays excluded.
|
||||
|
||||
## Query recovery
|
||||
|
||||
|
||||
@@ -4,12 +4,19 @@ import type { ProviderRequestFailure } from './request-diagnostics.js';
|
||||
|
||||
type ModelKey = { api: string; provider: string; id: string };
|
||||
type Row = Record<string, string | number | boolean>;
|
||||
type Origin = { status: string; response: string; sequence: number; ref?: string; model: ModelKey; ambiguous?: boolean };
|
||||
type Origin = { status: string; response: string; sequence: number; model: ModelKey; ambiguous?: boolean };
|
||||
const origins = new WeakMap<object, Map<string, Origin>>();
|
||||
const STATES = new Set(['completed', 'in_progress', 'incomplete', 'failed', 'cancelled', 'queued']);
|
||||
const KINDS = new Set(['reasoning', 'message', 'function_call', 'function_call_output',
|
||||
'custom_tool_call', 'custom_tool_call_output', 'tool_search_call', 'tool_search_output', 'additional_tools']);
|
||||
const APIS = new Set(['openai-responses', 'azure-openai-responses', 'openai-codex-responses']);
|
||||
export type ResponsesRejectedInput = { index: number; field: 'id' | 'status' };
|
||||
/** Closed protocol positions only; never retain arbitrary property names. */
|
||||
export function responsesRejectedInput(value: unknown): ResponsesRejectedInput | undefined {
|
||||
if (typeof value !== 'string' || value.length > 32) return;
|
||||
const match = /^input\[(\d{1,6})\]\.(id|status)$/.exec(value);
|
||||
if (match) return { index: Number(match[1]), field: match[2] as 'id' | 'status' };
|
||||
}
|
||||
const object = (v: unknown): Record<string, unknown> | undefined => v && typeof v === 'object' && !Array.isArray(v)
|
||||
? v as Record<string, unknown> : undefined;
|
||||
function status(value: unknown, present = true): string {
|
||||
@@ -24,7 +31,6 @@ export function createResponsesStatusDiagnostics(
|
||||
owner: ((failure: ProviderRequestFailure) => void) | undefined,
|
||||
model: ModelKey,
|
||||
sequence: number | undefined,
|
||||
requestRef: unknown,
|
||||
) {
|
||||
if (!owner || !APIS.has(model.api)) return undefined;
|
||||
let source = origins.get(owner);
|
||||
@@ -68,17 +74,17 @@ export function createResponsesStatusDiagnostics(
|
||||
}
|
||||
if (!previous && records.size >= 256) records.delete(records.keys().next().value!);
|
||||
records.set(key, { status: status(item.status, 'status' in item), response: status(responseStatus, responseStatus !== undefined),
|
||||
sequence: sequence ?? 0, model: { api: model.api, provider: model.provider, id: model.id },
|
||||
...(typeof requestRef === 'string' && /^(?:[a-f0-9]{12}|[a-f0-9]{32})$/.test(requestRef) ? { ref: requestRef } : {}) });
|
||||
sequence: sequence ?? 0, model: { api: model.api, provider: model.provider, id: model.id } });
|
||||
}
|
||||
} catch { /* Metadata never changes the response result. */ }
|
||||
},
|
||||
failure(rejectedIndex?: number): Record<string, unknown> | undefined {
|
||||
failure(rejectedIndex?: number, rejectedField?: 'id' | 'status'): Record<string, unknown> | undefined {
|
||||
try {
|
||||
const input = payload?.input;
|
||||
if (!Array.isArray(input)) return undefined;
|
||||
const indices: number[] = [];
|
||||
if (rejectedIndex !== undefined && Number.isInteger(rejectedIndex) && rejectedIndex >= 0 && rejectedIndex < input.length) indices.push(rejectedIndex);
|
||||
const rejectedInRange = rejectedIndex !== undefined && Number.isInteger(rejectedIndex) && rejectedIndex >= 0 && rejectedIndex < input.length;
|
||||
if (rejectedInRange) indices.push(rejectedIndex!);
|
||||
for (let i = 0; i < Math.min(input.length, 48) && indices.length < 4; i++) {
|
||||
if (object(input[i])?.type === 'reasoning' && !indices.includes(i)) indices.push(i);
|
||||
}
|
||||
@@ -93,13 +99,13 @@ export function createResponsesStatusDiagnostics(
|
||||
if (origin && !origin.ambiguous) {
|
||||
Object.assign(row, { source_status: origin.status, source_response_status: origin.response,
|
||||
source_sequence: origin.sequence,
|
||||
same_model: origin.model.api === model.api && origin.model.provider === model.provider && origin.model.id === model.id,
|
||||
...(origin.ref ? { source_request_ref: origin.ref } : {}) });
|
||||
same_model: origin.model.api === model.api && origin.model.provider === model.provider && origin.model.id === model.id });
|
||||
}
|
||||
return row;
|
||||
});
|
||||
return { version: 1, input_count: input.length, prefix_limit: 48,
|
||||
...(rejectedIndex === undefined ? {} : { rejected_index: rejectedIndex }), rows };
|
||||
...(rejectedIndex === undefined ? {} : { rejected_index: rejectedIndex }),
|
||||
...(rejectedInRange && (rejectedField === 'id' || rejectedField === 'status') ? { rejected_field: rejectedField } : {}), rows };
|
||||
} catch { return undefined; }
|
||||
},
|
||||
};
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
* recovery inside one tool call instead of asking the model to retry.
|
||||
*/
|
||||
import * as fs from "node:fs";
|
||||
import { parameterError } from '../../../../bin/tool-parameter-errors.cjs';
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { defineTool, type AgentTool, type ToolResult } from "./base.js";
|
||||
@@ -519,8 +520,36 @@ function saveCache(state: CacheState): void {
|
||||
|
||||
// ─── Search execution ─────────────────────────────────────────────────────
|
||||
|
||||
type ProviderRunSuccess = { ok: true; results: SearchResult[] };
|
||||
type ProviderRunFailure = { ok: false; reason: "unreachable" | "http"; detail: string };
|
||||
type ResponseContentType = "text/html" | "application/xhtml+xml" | "text/plain"
|
||||
| "application/json" | "application/xml" | "text/xml" | "application/rss+xml"
|
||||
| "other" | "unknown";
|
||||
|
||||
// Host-only facts. Never include queries, URLs, response text, statusText or raw errors.
|
||||
type ProviderDiagnostics = {
|
||||
failure_stage: "transport" | "http" | "body_read" | "parse" | "empty_results" | null;
|
||||
attempts: number;
|
||||
http_status: number | null;
|
||||
content_type: ResponseContentType;
|
||||
decoded_body_bytes: number | null;
|
||||
parsed_results: number | null;
|
||||
elapsed_ms: number;
|
||||
};
|
||||
|
||||
function responseContentType(response: Response): ResponseContentType {
|
||||
const header = response.headers.get("content-type");
|
||||
if (!header) return "unknown";
|
||||
// Inspect only a bounded prefix and emit only known MIME types, never header values.
|
||||
const mime = header.slice(0, 128).split(";", 1)[0].trim().toLowerCase();
|
||||
switch (mime) {
|
||||
case "text/html": case "application/xhtml+xml": case "text/plain":
|
||||
case "application/json": case "application/xml": case "text/xml": case "application/rss+xml":
|
||||
return mime;
|
||||
default: return "other";
|
||||
}
|
||||
}
|
||||
|
||||
type ProviderRunSuccess = { ok: true; results: SearchResult[]; diagnostics: ProviderDiagnostics };
|
||||
type ProviderRunFailure = { ok: false; reason: "unreachable" | "http"; detail: string; diagnostics: ProviderDiagnostics };
|
||||
type ProviderRunResult = ProviderRunSuccess | ProviderRunFailure;
|
||||
|
||||
type SearchRuntimeState = {
|
||||
@@ -573,11 +602,21 @@ async function runProviderSearch(
|
||||
config: ProviderConfig,
|
||||
query: string,
|
||||
): Promise<ProviderRunResult> {
|
||||
const started = performance.now();
|
||||
const diagnostics: ProviderDiagnostics = {
|
||||
failure_stage: "transport", attempts: 0, http_status: null, content_type: "unknown",
|
||||
decoded_body_bytes: null, parsed_results: null, elapsed_ms: 0,
|
||||
};
|
||||
let html: string | undefined;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
|
||||
try {
|
||||
const maxAttempts = config.id === "yahoo" ? 2 : 1;
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
||||
diagnostics.attempts = attempt + 1;
|
||||
diagnostics.failure_stage = "transport";
|
||||
diagnostics.http_status = null;
|
||||
diagnostics.content_type = "unknown";
|
||||
const resp = await fetch(config.buildSearchUrl(query), {
|
||||
method: "GET",
|
||||
headers: {
|
||||
@@ -588,31 +627,51 @@ async function runProviderSearch(
|
||||
signal: controller.signal,
|
||||
redirect: "follow",
|
||||
});
|
||||
diagnostics.http_status = resp.status;
|
||||
diagnostics.content_type = responseContentType(resp);
|
||||
if (!resp.ok) {
|
||||
diagnostics.failure_stage = "http";
|
||||
if (config.id === "yahoo" && resp.status === 500 && attempt === 0) {
|
||||
log.warn("provider request retry", {
|
||||
provider: config.id, next_provider: config.id, ...diagnostics,
|
||||
elapsed_ms: Math.round(performance.now() - started),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
reason: "http",
|
||||
detail: `HTTP ${resp.status} ${resp.statusText}`,
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
const html = await resp.text();
|
||||
return { ok: true, results: config.parse(html) };
|
||||
diagnostics.failure_stage = "body_read";
|
||||
html = await resp.text();
|
||||
diagnostics.failure_stage = "parse";
|
||||
const results = config.parse(html);
|
||||
diagnostics.parsed_results = results.length;
|
||||
diagnostics.failure_stage = results.length ? null : "empty_results";
|
||||
// Size the already-read decoded body only on failure; do not read error bodies
|
||||
// or add another full-body scan to successful searches. This is not wire size.
|
||||
if (!results.length) diagnostics.decoded_body_bytes = Buffer.byteLength(html, "utf8");
|
||||
return { ok: true, results, diagnostics };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
reason: "http",
|
||||
detail: "HTTP 500 after retry",
|
||||
diagnostics,
|
||||
};
|
||||
} catch (err) {
|
||||
if (html !== undefined) diagnostics.decoded_body_bytes = Buffer.byteLength(html, "utf8");
|
||||
return {
|
||||
ok: false,
|
||||
reason: "unreachable",
|
||||
detail: err instanceof Error ? err.message : String(err),
|
||||
diagnostics,
|
||||
};
|
||||
} finally {
|
||||
diagnostics.elapsed_ms = Math.round(performance.now() - started);
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
@@ -653,7 +712,7 @@ export async function runBuiltinWebSearch(
|
||||
): Promise<ToolResult> {
|
||||
const q = (query || "").trim();
|
||||
const n = Math.min(count, MAX_COUNT);
|
||||
if (!q) return { content: "Error: query is required", isError: true };
|
||||
if (!q) return parameterError("Error: query is required", ['query'], 'required');
|
||||
return runWebSearchInternal(q, n);
|
||||
}
|
||||
|
||||
@@ -679,7 +738,7 @@ export const webSearchTool: AgentTool = defineTool({
|
||||
(input.count as number | undefined) ?? DEFAULT_COUNT,
|
||||
MAX_COUNT,
|
||||
);
|
||||
if (!query) return { content: "Error: query is required", isError: true };
|
||||
if (!query) return parameterError("Error: query is required", ['query'], 'required');
|
||||
return runWebSearchInternal(query, count);
|
||||
},
|
||||
});
|
||||
@@ -733,11 +792,11 @@ async function runSerializedWebSearch(
|
||||
failures.push({ provider, detail });
|
||||
markProviderFailure(state, provider);
|
||||
const next = order[failures.length];
|
||||
if (next) {
|
||||
log.warn(
|
||||
`provider request failed: ${provider} (${detail}); trying ${next}`,
|
||||
);
|
||||
}
|
||||
// One bounded record per failed provider, including the last one. Yahoo's
|
||||
// existing single 500 retry adds at most one record: seven per tool call.
|
||||
log.warn("provider request failed", {
|
||||
provider, next_provider: next ?? null, ...result.diagnostics,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -232,9 +232,26 @@ describe('Codex cache affinity without shared conversation state', () => {
|
||||
}
|
||||
expect(payloads.map(p => p.prompt_cache_key)).toEqual(['opaque-user-a', 'opaque-user-a']);
|
||||
expect(headers.map(h => h.get('session_id'))).toEqual(['login-credential', 'login-credential']);
|
||||
expect(headers.map(h => h.get('session-id'))).toEqual(['opaque-user-a', 'opaque-user-a']);
|
||||
expect(headers.map(h => h.get('x-client-request-id'))).toEqual(['chat-a', 'chat-b']);
|
||||
});
|
||||
|
||||
it.each(['complete', 'stream'] as const)('preserves explicit Responses affinity headers while keeping the user body key (%s)', async method => {
|
||||
const headers: Headers[] = [], bodies: any[] = [];
|
||||
vi.stubGlobal('fetch', vi.fn(async (input, init) => {
|
||||
headers.push(new Headers(init?.headers)); bodies.push(await wirePayload(input, init)); return response();
|
||||
}));
|
||||
const p = createPiProvider({ provider: 'openai', model: 'gpt-6.1-sol', apiKey: 'fixture',
|
||||
userCacheKey: 'opaque-user-a', headers: { 'SeSsIoN-Id': 'caller-owned', 'session_id': 'login-credential' },
|
||||
});
|
||||
const params = request('chat-a');
|
||||
if (method === 'complete') await p.complete(params);
|
||||
else for await (const event of p.stream(params)) if (event.type === 'error') throw event.error;
|
||||
expect(headers[0].get('session-id')).toBe('caller-owned');
|
||||
expect(headers[0].get('session_id')).toBe('login-credential');
|
||||
expect(bodies[0].prompt_cache_key).toBe('opaque-user-a');
|
||||
});
|
||||
|
||||
it('preserves other protocols and their caller-supplied headers', async () => {
|
||||
const headers: Headers[] = [];
|
||||
vi.stubGlobal('fetch', vi.fn(async (_input, init) => { headers.push(new Headers(init.headers)); return response(); }));
|
||||
|
||||
@@ -41,6 +41,7 @@ afterEach(() => vi.unstubAllGlobals());
|
||||
it.each([
|
||||
{ label: 'completed tool response control', truncated: false, hasCall: true, reasonDone: true, wireReasoning: 1, executions: 1 },
|
||||
{ label: 'truncated tool response', truncated: true, hasCall: true, reasonDone: true, wireReasoning: 1, executions: 0 },
|
||||
{ label: 'truncated malformed tool response', truncated: true, hasCall: true, reasonDone: true, wireReasoning: 1, executions: 0, malformed: true },
|
||||
{ label: 'truncated text response control', truncated: true, hasCall: false, reasonDone: true, wireReasoning: 1, executions: 0 },
|
||||
{ label: 'truncated tool response without public text', truncated: true, hasCall: true, reasonDone: true, wireReasoning: 1, executions: 0, noText: true },
|
||||
{ label: 'plaintext item with protocol-null encrypted content', truncated: true, hasCall: true, reasonDone: true, wireReasoning: 1, executions: 0, nullCipher: true },
|
||||
@@ -54,7 +55,7 @@ it.each([
|
||||
expect(bodies.length).toBeLessThanOrEqual(2);
|
||||
return bodies.length === 1
|
||||
? response([sourceReason, ...('noText' in scenario ? [] : [message('Ready to save.')]),
|
||||
...(scenario.hasCall ? [toolCall] : [])], scenario.truncated, scenario.reasonDone)
|
||||
...(scenario.hasCall ? [{ ...toolCall, ...('malformed' in scenario ? { arguments: '{"value":' } : {}) }] : [])], scenario.truncated, scenario.reasonDone)
|
||||
: response([message('Seven.')]);
|
||||
}));
|
||||
const native = createPiProvider({ provider: 'fixture-provider', apiKey: 'synthetic', customModel: model });
|
||||
@@ -141,6 +142,7 @@ it.each([
|
||||
{ label: 'reasoning only', text: '', proposal: false, field: 'reasoning_content' },
|
||||
{ label: 'whitespace body', text: ' \n ', proposal: false, field: 'reasoning_content' },
|
||||
{ label: 'discarded tool without text', text: '', proposal: true, field: 'reasoning_content' },
|
||||
{ label: 'malformed discarded tool without text', text: '', proposal: true, field: 'reasoning_content', malformed: true },
|
||||
{ label: 'portable reasoning field', text: '', proposal: false, field: 'reasoning' },
|
||||
{ label: 'portable reasoning_text field', text: '', proposal: false, field: 'reasoning_text' },
|
||||
])('replays original Chat reasoning without a placeholder: $label', async scenario => {
|
||||
@@ -151,7 +153,7 @@ it.each([
|
||||
expect(bodies.length).toBeLessThanOrEqual(2);
|
||||
const first = bodies.length === 1;
|
||||
const delta = first ? { role: 'assistant', content: scenario.text, [scenario.field]: originalReason,
|
||||
...(scenario.proposal ? { tool_calls: [{ index: 0, id: 'discard', type: 'function', function: { name: 'write_file', arguments: '{}' } }] } : {}) }
|
||||
...(scenario.proposal ? { tool_calls: [{ index: 0, id: 'discard', type: 'function', function: { name: 'write_file', arguments: 'malformed' in scenario ? '{"value":' : '{}' } }] } : {}) }
|
||||
: { role: 'assistant', content: 'Finished.' };
|
||||
return new Response(`data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason: first ? 'length' : 'stop' }] })}\n\ndata: [DONE]\n\n`,
|
||||
{ headers: { 'content-type': 'text/event-stream' } });
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { AgentRunner } from '../src/agent/runner.js';
|
||||
import { PersistentSession } from '../src/agent/persistent-session.js';
|
||||
import { createConfig } from '../src/config/loader.js';
|
||||
import { createPiProvider } from '../src/providers/pi-provider.js';
|
||||
import { ProviderRegistry } from '../src/providers/registry.js';
|
||||
import type { AgentRunEvent } from '../src/agent/types.js';
|
||||
|
||||
type Api = 'openai-completions' | 'openai-responses';
|
||||
type Reply = {
|
||||
kind: 'bad' | 'unfinished' | 'tool' | 'text';
|
||||
length?: boolean;
|
||||
text?: string;
|
||||
file?: string;
|
||||
sibling?: boolean;
|
||||
};
|
||||
const APIS: Api[] = ['openai-completions', 'openai-responses'];
|
||||
const BAD_ARGUMENTS = '{"path":"PRIVATE_INCOMPLETE_ARGUMENT';
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Exercise the installed SDK, adapter, Runner and durable Session. Only model
|
||||
// HTTP responses are synthetic; the executor appends real isolated files so a
|
||||
// duplicate or accidentally admitted sibling is independently observable.
|
||||
function wireReply(api: Api, reply: Reply, round: number): Response {
|
||||
const truncated = reply.length ?? (reply.kind === 'bad' || reply.kind === 'unfinished');
|
||||
const text = reply.text ?? 'Analysis retained.';
|
||||
const calls = reply.kind === 'text' ? [] : [{
|
||||
id: `${reply.kind}_${round}`, name: 'write_file',
|
||||
arguments: reply.kind === 'tool'
|
||||
? JSON.stringify({ path: reply.file ?? 'report.txt', content: 'verified\n' }) : BAD_ARGUMENTS,
|
||||
}];
|
||||
if (reply.sibling) calls.push({ id: `sibling_${round}`, name: 'write_file',
|
||||
arguments: JSON.stringify({ path: 'forbidden.txt', content: 'must not run\n' }) });
|
||||
let frames: unknown[];
|
||||
if (api === 'openai-completions') {
|
||||
frames = [{ id: 'fixture', model: 'fixture', choices: [{ index: 0,
|
||||
delta: { role: 'assistant', content: text, ...(calls.length ? { tool_calls: calls.map((call, index) => ({
|
||||
index, id: call.id, type: 'function', function: { name: call.name, arguments: call.arguments },
|
||||
})) } : {}) }, finish_reason: truncated ? 'length' : calls.length ? 'tool_calls' : 'stop',
|
||||
}], usage: { prompt_tokens: 20, completion_tokens: 10, total_tokens: 30 } }];
|
||||
} else {
|
||||
const message = { type: 'message', id: `msg_${round}`, role: 'assistant', status: 'completed',
|
||||
content: [{ type: 'output_text', text, annotations: [] }] };
|
||||
const items = calls.map(call => ({ type: 'function_call', id: `fc_${call.id}`, call_id: call.id,
|
||||
name: call.name, arguments: call.arguments, status: truncated ? 'incomplete' : 'completed' }));
|
||||
frames = [{ type: 'response.created', response: { id: `resp_${round}` } },
|
||||
{ type: 'response.output_item.added', output_index: 0, item: { ...message, content: [] } },
|
||||
{ type: 'response.output_text.delta', output_index: 0, delta: text },
|
||||
{ type: 'response.output_item.done', output_index: 0, item: message }];
|
||||
items.forEach((item, index) => {
|
||||
frames.push({ type: 'response.output_item.added', output_index: index + 1, item: { ...item, arguments: '' } },
|
||||
{ type: 'response.function_call_arguments.delta', output_index: index + 1, delta: item.arguments });
|
||||
if (reply.kind !== 'unfinished') frames.push({ type: 'response.output_item.done', output_index: index + 1, item });
|
||||
});
|
||||
frames.push({ type: truncated ? 'response.incomplete' : 'response.completed', response: {
|
||||
id: `resp_${round}`, status: truncated ? 'incomplete' : 'completed',
|
||||
incomplete_details: truncated ? { reason: 'max_output_tokens' } : null, output: [message, ...items],
|
||||
usage: { input_tokens: 20, output_tokens: 10, total_tokens: 30, input_tokens_details: { cached_tokens: 0 } },
|
||||
} });
|
||||
}
|
||||
return new Response(frames.map(frame => `data: ${JSON.stringify(frame)}\n\n`).join('')
|
||||
+ (api === 'openai-completions' ? 'data: [DONE]\n\n' : ''),
|
||||
{ headers: { 'content-type': 'text/event-stream' } });
|
||||
}
|
||||
|
||||
function setup(api: Api, replies: Reply[]) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-output-limit-'));
|
||||
roots.push(root);
|
||||
const bodies: any[] = [];
|
||||
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const body = JSON.parse(await new Request(input, init).text());
|
||||
bodies.push(body);
|
||||
const reply = replies[bodies.length - 1];
|
||||
if (!reply) throw new Error('Synthetic request budget exceeded');
|
||||
return wireReply(api, reply, bodies.length);
|
||||
}));
|
||||
const provider = createPiProvider({ provider: 'custom', apiKey: 'fixture', customModel: {
|
||||
id: 'fixture', name: 'Fixture', provider: 'custom', api, baseUrl: 'https://fixture.invalid/v1',
|
||||
reasoning: false, input: ['text'], contextWindow: 128000, maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
} });
|
||||
const registry = new ProviderRegistry();
|
||||
registry.registerFactory('custom', () => provider);
|
||||
const file = path.join(root, 'session.jsonl');
|
||||
const session = new PersistentSession({ sessionFile: file });
|
||||
const writes: unknown[] = [];
|
||||
const runner = new AgentRunner({ providers: registry, session,
|
||||
config: createConfig({ agent: { defaultProvider: 'custom', defaultModel: 'fixture', maxRetries: 0 } }),
|
||||
tools: [{ name: 'write_file', description: 'Write a report', inputSchema: {
|
||||
type: 'object', properties: { path: { type: 'string' }, content: { type: 'string' } }, required: ['path', 'content'],
|
||||
}, async execute(input) {
|
||||
writes.push(input);
|
||||
expect(['report.txt', 'first.txt', 'forbidden.txt']).toContain(input.path);
|
||||
fs.appendFileSync(path.join(root, String(input.path)), String(input.content));
|
||||
return { content: `Saved ${input.path}` };
|
||||
} }],
|
||||
});
|
||||
return { root, file, session, runner, provider, bodies, writes };
|
||||
}
|
||||
|
||||
describe('real SDK output-limit recovery', () => {
|
||||
it.each(APIS.flatMap(api => (['complete', 'stream'] as const).map(method => [api, method] as const)))
|
||||
('preserves a known length termination without executable malformed calls (%s/%s)', async (api, method) => {
|
||||
const { provider, bodies } = setup(api, [{ kind: 'bad', sibling: true }]);
|
||||
const params = { model: 'fixture', messages: [{ role: 'user' as const, content: [{ type: 'text' as const, text: 'Write the report.' }] }],
|
||||
onRequestFailure() {} };
|
||||
let result: any;
|
||||
if (method === 'complete') result = await provider.complete(params);
|
||||
else for await (const event of provider.stream(params)) if (event.type === 'message_end') result = event;
|
||||
expect(result.stopReason).toBe('max_tokens');
|
||||
expect(result.incompleteToolCall).toBe(true);
|
||||
expect(result.content).toContainEqual(expect.objectContaining({ type: 'text', text: 'Analysis retained.' }));
|
||||
expect(result.content.some((block: any) => block.type === 'tool_use')).toBe(false);
|
||||
expect(JSON.stringify(result)).not.toContain('PRIVATE_INCOMPLETE_ARGUMENT');
|
||||
expect(bodies).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(APIS.flatMap(api => (['complete', 'stream'] as const).map(method => [api, method] as const)))
|
||||
('keeps non-length malformed arguments rejected (%s/%s)', async (api, method) => {
|
||||
const { provider, bodies, writes } = setup(api, [{ kind: 'bad', length: false }]);
|
||||
const failures: any[] = [];
|
||||
const params = { model: 'fixture', messages: [], onRequestFailure: (failure: unknown) => failures.push(failure) };
|
||||
const call = async () => {
|
||||
if (method === 'complete') return provider.complete(params);
|
||||
for await (const _event of provider.stream(params)) { /* Drain the actual SDK. */ }
|
||||
};
|
||||
await expect(call()).rejects.toThrow('Invalid tool call arguments');
|
||||
expect(writes).toEqual([]);
|
||||
expect(bodies).toHaveLength(1);
|
||||
expect(failures).toHaveLength(1);
|
||||
expect(failures[0]).toMatchObject({ toolArguments: { code: 'tool_arguments_invalid', api,
|
||||
stop_reason: 'tool_use',
|
||||
stream_json: method === 'stream' ? 'non_strict' : 'unobserved' } });
|
||||
expect(JSON.stringify(failures)).not.toContain('PRIVATE_INCOMPLETE_ARGUMENT');
|
||||
});
|
||||
|
||||
it.each(APIS)('recovers only the incomplete proposal and retains completed files after reload (%s)', async api => {
|
||||
const { root, file, runner, session, bodies, writes } = setup(api, [
|
||||
{ kind: 'tool', file: 'first.txt' }, { kind: 'bad', sibling: true, text: '' },
|
||||
{ kind: 'tool', text: '' }, { kind: 'text', text: 'Finished.' },
|
||||
]);
|
||||
const events: AgentRunEvent[] = [];
|
||||
for await (const event of runner.runStream({ message: 'Write both reports.' })) events.push(event);
|
||||
const terminals = events.filter(event => event.type === 'done');
|
||||
expect(terminals).toHaveLength(1);
|
||||
const result = terminals[0].result;
|
||||
expect(result.meta.error).toBeUndefined();
|
||||
expect(result.text).toBe('Finished.');
|
||||
expect(result.meta.convergenceSignals).toContain('output_limit_continuation');
|
||||
expect(result.meta.usage.totalTokens).toBe(120);
|
||||
const calls = events.filter(event => event.type === 'provider_call');
|
||||
expect(calls).toHaveLength(4);
|
||||
expect(calls[1].output?.toolCalls).toBe(2);
|
||||
expect(bodies).toHaveLength(4);
|
||||
expect(writes).toHaveLength(2);
|
||||
expect(fs.readFileSync(path.join(root, 'first.txt'), 'utf8')).toBe('verified\n');
|
||||
expect(fs.readFileSync(path.join(root, 'report.txt'), 'utf8')).toBe('verified\n');
|
||||
expect(fs.existsSync(path.join(root, 'forbidden.txt'))).toBe(false);
|
||||
expect(JSON.stringify(bodies[2])).toContain('at or below 12000 characters');
|
||||
expect(JSON.stringify(bodies[2])).toContain('Saved first.txt');
|
||||
for (const body of bodies.slice(2)) {
|
||||
expect(JSON.stringify(body)).not.toMatch(/PRIVATE_INCOMPLETE_ARGUMENT|bad_2|sibling_2|incompleteToolCall/);
|
||||
}
|
||||
expect(new PersistentSession({ sessionFile: file }).getMessages()).toEqual(session.getMessages());
|
||||
expect(fs.readFileSync(file, 'utf8')).not.toMatch(/PRIVATE_INCOMPLETE_ARGUMENT|bad_2|sibling_2|incompleteToolCall/);
|
||||
});
|
||||
|
||||
it.each(APIS.flatMap(api => [false, true].map(mixed => [api, mixed] as const)))
|
||||
('bounds repeated and mixed truncation while preserving resumable prose (%s/mixed=%s)', async (api, mixed) => {
|
||||
const replies: Reply[] = mixed
|
||||
? [{ kind: 'bad' }, { kind: 'text', length: true }, { kind: 'unfinished' }, { kind: 'bad' }]
|
||||
: Array.from({ length: 4 }, () => ({ kind: 'bad' }));
|
||||
const { runner, bodies, writes, file, root } = setup(api, replies);
|
||||
const result = await runner.run({ message: 'Write the report.' });
|
||||
expect(result.meta.error?.code).toBe('OUTPUT_LIMIT');
|
||||
expect(result.text).toContain('Analysis retained.');
|
||||
expect(result.meta.convergenceSignals).toContain('output_limit_unrecovered');
|
||||
expect(bodies).toHaveLength(4);
|
||||
expect(writes).toEqual([]);
|
||||
expect(fs.existsSync(path.join(root, 'report.txt'))).toBe(false);
|
||||
const restored = JSON.stringify(new PersistentSession({ sessionFile: file }).getMessages());
|
||||
expect(new PersistentSession({ sessionFile: file }).getSerializedContextState()?.activeTurn).toBeDefined();
|
||||
expect(restored).toContain('Analysis retained.');
|
||||
expect(restored).toContain('tool calls from truncated responses were NOT executed');
|
||||
expect(restored).not.toMatch(/PRIVATE_INCOMPLETE_ARGUMENT|bad_\d|unfinished_\d|incompleteToolCall/);
|
||||
});
|
||||
|
||||
it.each(APIS)('honors cancellation before a recovery request without admitting any tool (%s)', async api => {
|
||||
const { runner, bodies, writes } = setup(api, [{ kind: 'bad' }]);
|
||||
const controller = new AbortController();
|
||||
let result;
|
||||
let completed = false;
|
||||
for await (const event of runner.runStream({ message: 'Write the report.', signal: controller.signal })) {
|
||||
if (event.type === 'provider_call' && event.outcome === 'completed') {
|
||||
completed = true;
|
||||
controller.abort();
|
||||
}
|
||||
if (event.type === 'done') result = event.result;
|
||||
}
|
||||
expect(completed).toBe(true);
|
||||
expect(result?.meta.aborted).toBe(true);
|
||||
expect(bodies).toHaveLength(1);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { createResponsesStatusDiagnostics as observe } from '../src/providers/re
|
||||
import { createPiProvider } from '../src/providers/pi-provider.js';
|
||||
import type { CompletionParams } from '../src/providers/base.js';
|
||||
import type { MessageContent } from '../src/shared/types.js';
|
||||
import { createRequestDiagnostics } from '../src/providers/request-diagnostics.js';
|
||||
|
||||
const model = { api: 'openai-responses', provider: 'openai', id: 'fixture' };
|
||||
const item = (id = 'PRIVATE_ID', status = 'in_progress') => ({ type: 'reasoning', id, status,
|
||||
@@ -10,10 +11,40 @@ const item = (id = 'PRIVATE_ID', status = 'in_progress') => ({ type: 'reasoning'
|
||||
const content = (value = item()) => [{ type: 'thinking', thinking: '', thinkingSignature: JSON.stringify(value) }];
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
|
||||
|
||||
it('retains only the first typed error metadata and excludes prose, other requests and cancelled evidence', () => {
|
||||
const controller = new AbortController();
|
||||
const first = createRequestDiagnostics(controller.signal, () => { throw new Error('PRIVATE observer'); });
|
||||
const second = createRequestDiagnostics();
|
||||
first.onResponse({ status: 200 }); second.onResponse({ status: 200 });
|
||||
const observeError = (value: unknown) => (first as any).observeProviderStreamEvent?.(value);
|
||||
observeError({ type: 'response.output_text.delta', error: { code: 'permission_error' }, delta: 'PRIVATE' });
|
||||
observeError({ type: 'response.failed', response: { error: { code: 'invalid_request_error', param: 'input[0].id', message: 'PRIVATE' } } });
|
||||
observeError({ type: 'error', code: 'permission_error', param: 'input[1].status' });
|
||||
expect(first.report(new Error('PRIVATE'), false, 'sdk_error')).toMatchObject({ code: 'invalid_request_error', httpStatus: 200 });
|
||||
expect((first as any).rejectedInput).toEqual({ index: 0, field: 'id' });
|
||||
expect(first.report(new Error('PRIVATE'))).toBeUndefined();
|
||||
expect(second.report(new Error('PRIVATE'))).toMatchObject({ code: 'unknown' });
|
||||
const aborted = createRequestDiagnostics(controller.signal);
|
||||
(aborted as any).observeProviderStreamEvent?.({ type: 'error', code: 'authentication_error', param: 'input[0].id' });
|
||||
controller.abort();
|
||||
const cancelled = aborted.report(new Error('PRIVATE'), true, 'sdk_error');
|
||||
expect(cancelled).toMatchObject({ code: 'unknown', aborted: true });
|
||||
expect(JSON.stringify(cancelled)).not.toContain('PRIVATE');
|
||||
});
|
||||
|
||||
it('reports a safe rejected field with its in-range item, without disclosing the item id', () => {
|
||||
const next = observe(() => {}, model, 1)!;
|
||||
next.payload({ input: [{ type: 'message', id: 'PRIVATE', content: 'PRIVATE' }] });
|
||||
const failure = (next.failure as any)(0, 'id');
|
||||
expect(failure).toMatchObject({ rejected_index: 0, rejected_field: 'id', rows: [{ i: 0, kind: 'message' }] });
|
||||
expect(JSON.stringify(failure)).not.toContain('PRIVATE');
|
||||
expect((next.failure as any)(9, 'id')).not.toHaveProperty('rejected_field');
|
||||
});
|
||||
|
||||
it('distinguishes source, history and wire state without changing any stage or leaking content', () => {
|
||||
const owner = () => {};
|
||||
observe(owner, model, 1, 'a'.repeat(32))!.output(content(), 'completed');
|
||||
const next = observe(owner, model, 2, undefined)!;
|
||||
(observe as any)(owner, model, 1, 'a'.repeat(32)).output(content(), 'completed');
|
||||
const next = observe(owner, model, 2)!;
|
||||
next.history(item('PRIVATE_ID', 'incomplete'));
|
||||
const wire = { input: [item('PRIVATE_ID', 'completed')] };
|
||||
const before = JSON.stringify(wire);
|
||||
@@ -21,41 +52,53 @@ it('distinguishes source, history and wire state without changing any stage or l
|
||||
const evidence = next.failure(0);
|
||||
expect(evidence).toMatchObject({ rows: [{ i: 0, source_status: 'in_progress',
|
||||
source_response_status: 'completed', history_status: 'incomplete', wire_status: 'completed',
|
||||
source_sequence: 1, source_request_ref: 'a'.repeat(32), same_model: true, origin: 'observed' }] });
|
||||
source_sequence: 1, same_model: true, origin: 'observed' }] });
|
||||
expect((evidence!.rows as any[])[0]).not.toHaveProperty('source_request_ref');
|
||||
expect(JSON.stringify(evidence)).not.toContain('a'.repeat(32));
|
||||
expect(JSON.stringify(evidence)).not.toContain('PRIVATE');
|
||||
expect(JSON.stringify(wire)).toBe(before);
|
||||
});
|
||||
|
||||
it('does not turn a legacy positional argument into public request correlation', () => {
|
||||
const diagnostics = (createRequestDiagnostics as any)(undefined, undefined, 'a'.repeat(32));
|
||||
diagnostics.onResponse({ status: 400 });
|
||||
const failure = diagnostics.report(new Error('PRIVATE_PROVIDER_BODY'));
|
||||
expect(failure).toMatchObject({ phase: 'after_response', httpStatus: 400, code: 'unknown' });
|
||||
expect(failure).not.toHaveProperty('requestRef');
|
||||
expect(JSON.stringify(failure)).not.toMatch(/PRIVATE|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/);
|
||||
});
|
||||
|
||||
it('marks restarted runs, duplicate identities and model changes without inventing provenance', () => {
|
||||
const owner = () => {};
|
||||
observe(owner, model, 1, undefined)!.output(content(), undefined);
|
||||
const changed = observe(owner, { ...model, id: 'other' }, 2, undefined)!;
|
||||
observe(owner, model, 1)!.output(content(), undefined);
|
||||
const changed = observe(owner, { ...model, id: 'other' }, 2)!;
|
||||
changed.payload({ input: [item()] });
|
||||
expect(changed.failure()).toMatchObject({ rows: [{ same_model: false, source_response_status: 'missing' }] });
|
||||
changed.history(item()); changed.history(item());
|
||||
changed.output(content(), 'completed');
|
||||
expect(changed.failure()).toMatchObject({ rows: [{ history_status: 'ambiguous', origin: 'ambiguous' }] });
|
||||
expect((changed.failure()!.rows as any[])[0]).not.toHaveProperty('source_status');
|
||||
const restarted = observe(() => {}, model, 1, undefined)!;
|
||||
const restarted = observe(() => {}, model, 1)!;
|
||||
restarted.history(item()); restarted.payload({ input: [item()] });
|
||||
expect(restarted.failure()).toMatchObject({ rows: [{ history_status: 'in_progress', origin: 'unobserved' }] });
|
||||
});
|
||||
|
||||
it('bounds retained sources and signature parsing, prioritizing one exact rejection outside the prefix', () => {
|
||||
expect(observe(undefined, model, 1, undefined)).toBeUndefined();
|
||||
expect(observe(() => {}, { ...model, api: 'openai-completions' }, 1, undefined)).toBeUndefined();
|
||||
expect(observe(undefined, model, 1)).toBeUndefined();
|
||||
expect(observe(() => {}, { ...model, api: 'openai-completions' }, 1)).toBeUndefined();
|
||||
const owner = () => {};
|
||||
const source = observe(owner, model, 1, undefined)!;
|
||||
const source = observe(owner, model, 1)!;
|
||||
for (let i = 0; i < 257; i++) source.output(content(item(String(i))), 'completed');
|
||||
source.output([{ type: 'thinking', thinkingSignature: JSON.stringify({ ...item('oversized'), encrypted_content: 'x'.repeat(65536) }) }], 'completed');
|
||||
const next = observe(owner, model, 2, undefined)!;
|
||||
const next = observe(owner, model, 2)!;
|
||||
next.payload({ input: [item('0'), item('256'), item('oversized'), ...Array(9997).fill(item('PRIVATE_OTHER'))] });
|
||||
expect(next.failure(9999)).toMatchObject({ input_count: 10000, rejected_index: 9999,
|
||||
rows: [{ i: 9999, origin: 'unobserved' }, { i: 0, origin: 'unobserved' },
|
||||
{ i: 1, origin: 'observed' }, { i: 2, origin: 'unobserved' }] });
|
||||
});
|
||||
|
||||
it.each(['complete', 'stream'] as const)('retains real SDK %s provenance across serialized history and an HTTP rejection', async method => {
|
||||
it.each((['complete', 'stream'] as const).flatMap(method => (['id', 'status'] as const).map(field => [method, field] as const)))
|
||||
('retains real SDK %s provenance across serialized history and an HTTP %s rejection', async (method, field) => {
|
||||
const reasoning = item();
|
||||
const events = [
|
||||
{ type: 'response.output_item.added', output_index: 0, item: reasoning },
|
||||
@@ -67,7 +110,7 @@ it.each(['complete', 'stream'] as const)('retains real SDK %s provenance across
|
||||
wire.push(JSON.parse(init.body));
|
||||
return wire.length === 1 ? new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(''),
|
||||
{ headers: { 'content-type': 'text/event-stream' } }) : new Response(JSON.stringify({ error: {
|
||||
type: 'invalid_request_error', param: 'input[1].status', message: 'fixture rejected state',
|
||||
type: 'invalid_request_error', param: `input[1].${field}`, message: 'fixture rejected state',
|
||||
} }), { status: 400, headers: { 'content-type': 'application/json' } });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
@@ -97,7 +140,7 @@ it.each(['complete', 'stream'] as const)('retains real SDK %s provenance across
|
||||
expect(wire[1].input[1]).toEqual(inputReasoning);
|
||||
expect(failures).toHaveLength(1);
|
||||
expect(failures[0]).toMatchObject({ httpStatus: 400, requestSequence: 2,
|
||||
responsesStatus: { rejected_index: 1, rows: [{ i: 1, origin: 'observed', source_sequence: 1,
|
||||
responsesStatus: { rejected_index: 1, rejected_field: field, rows: [{ i: 1, origin: 'observed', source_sequence: 1,
|
||||
source_status: 'in_progress', source_response_status: 'completed', history_status: 'in_progress',
|
||||
wire_status: 'missing', same_model: true }] } });
|
||||
expect(failures[0].responsesStatus.rows[0]).not.toHaveProperty('source_request_ref');
|
||||
|
||||
@@ -31,6 +31,7 @@ afterEach(() => {
|
||||
if (previousStateDir === undefined) delete process.env.CORE_AGENT_STATE_DIR;
|
||||
else process.env.CORE_AGENT_STATE_DIR = previousStateDir;
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
@@ -416,6 +417,11 @@ describe("web-search tool execution", () => {
|
||||
});
|
||||
|
||||
it("handles a Brave 429 inside one tool call by falling back to DuckDuckGo once", async () => {
|
||||
const warn = vi.spyOn(console, "warn");
|
||||
const rejected = new Response("private response body", {
|
||||
status: 429, statusText: "private-status-text", headers: { "content-type": "text/html; charset=utf-8" },
|
||||
});
|
||||
const readRejectedBody = vi.spyOn(rejected, "text");
|
||||
fs.writeFileSync(path.join(stateDir, "web-search-cache.json"), JSON.stringify({
|
||||
preferred: "brave",
|
||||
probedAt: new Date().toISOString(),
|
||||
@@ -423,7 +429,7 @@ describe("web-search tool execution", () => {
|
||||
const fetchMock = vi.fn(async (url: string, _init?: RequestInit) => {
|
||||
const href = String(url);
|
||||
return href.includes("brave.com")
|
||||
? new Response("rate limited", { status: 429, statusText: "Too Many Requests" })
|
||||
? rejected
|
||||
: new Response(DUCKDUCKGO_FIXTURE, { status: 200 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
@@ -437,6 +443,13 @@ describe("web-search tool execution", () => {
|
||||
const cache = JSON.parse(fs.readFileSync(path.join(stateDir, "web-search-cache.json"), "utf8"));
|
||||
expect(cache.preferred).toBe("duckduckgo");
|
||||
expect(cache.reason).toContain("HTTP 429");
|
||||
expect(readRejectedBody).not.toHaveBeenCalled();
|
||||
expect(warn).toHaveBeenCalledExactlyOnceWith("[web-search]", "provider request failed", {
|
||||
provider: "brave", next_provider: "duckduckgo", failure_stage: "http", attempts: 1,
|
||||
http_status: 429, content_type: "text/html", decoded_body_bytes: null,
|
||||
parsed_results: null, elapsed_ms: expect.any(Number),
|
||||
});
|
||||
expect(JSON.stringify(warn.mock.calls)).not.toContain("private-");
|
||||
});
|
||||
|
||||
it("uses Bing RSS after both Brave and DuckDuckGo fail", async () => {
|
||||
@@ -467,14 +480,15 @@ describe("web-search tool execution", () => {
|
||||
expect(String(fetchMock.mock.calls[5][0])).toContain("format=rss");
|
||||
});
|
||||
|
||||
it("recovers through Yahoo when DuckDuckGo returns an anti-bot page", async () => {
|
||||
it.each([200, 202])("records empty-result response facts (%i) and recovers through Yahoo", async (status) => {
|
||||
const warn = vi.spyOn(console, "warn");
|
||||
const fetchMock = vi.fn(async (url: string) => {
|
||||
const href = String(url);
|
||||
if (href.includes("brave.com")) {
|
||||
return new Response("rate limited", { status: 429, statusText: "Too Many Requests" });
|
||||
}
|
||||
if (href.includes("duckduckgo.com")) {
|
||||
return new Response("<html>challenge</html>", { status: 202 });
|
||||
return new Response("<html>challenge</html>", { status, headers: { "content-type": "text/html" } });
|
||||
}
|
||||
return new Response(YAHOO_FIXTURE, { status: 200 });
|
||||
});
|
||||
@@ -486,9 +500,17 @@ describe("web-search tool execution", () => {
|
||||
expect(result.content).toContain("via Yahoo");
|
||||
expect(result.content).toContain("https://official.example.com/report?id=1");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
// The fixture has no result markup; its HTTP status does not prove a CAPTCHA or a parser defect.
|
||||
expect(warn).toHaveBeenLastCalledWith("[web-search]", "provider request failed", {
|
||||
provider: "duckduckgo", next_provider: "yahoo", failure_stage: "empty_results", attempts: 1,
|
||||
http_status: status, content_type: "text/html", decoded_body_bytes: 22,
|
||||
parsed_results: 0, elapsed_ms: expect.any(Number),
|
||||
});
|
||||
expect(warn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("recovers through Sogou when Brave and DuckDuckGo are unavailable", async () => {
|
||||
const warn = vi.spyOn(console, "warn");
|
||||
const fetchMock = vi.fn(async (url: string) => {
|
||||
const href = String(url);
|
||||
if (href.includes("brave.com")) {
|
||||
@@ -510,12 +532,23 @@ describe("web-search tool execution", () => {
|
||||
expect(result.content).toContain("via Sogou");
|
||||
expect(result.content).toContain("https://report.example.cn/ai-hiring?id=2026");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(5);
|
||||
expect(warn).toHaveBeenCalledWith("[web-search]", "provider request retry", {
|
||||
provider: "yahoo", next_provider: "yahoo", failure_stage: "http", attempts: 1,
|
||||
http_status: 500, content_type: "text/plain", decoded_body_bytes: null,
|
||||
parsed_results: null, elapsed_ms: expect.any(Number),
|
||||
});
|
||||
expect(warn).toHaveBeenLastCalledWith("[web-search]", "provider request failed", {
|
||||
provider: "yahoo", next_provider: "sogou", failure_stage: "http", attempts: 2,
|
||||
http_status: 500, content_type: "text/plain", decoded_body_bytes: null,
|
||||
parsed_results: null, elapsed_ms: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back when the preferred provider returns an unparseable empty page", async () => {
|
||||
const warn = vi.spyOn(console, "warn");
|
||||
const fetchMock = vi.fn(async (url: string) => (
|
||||
String(url).includes("brave.com")
|
||||
? new Response("<html><body>layout changed</body></html>", { status: 200 })
|
||||
? new Response("<html>🌏</html>", { status: 200 })
|
||||
: new Response(DUCKDUCKGO_FIXTURE, { status: 200 })
|
||||
));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
@@ -525,6 +558,76 @@ describe("web-search tool execution", () => {
|
||||
expect(result.isError).toBeUndefined();
|
||||
expect(result.content).toContain("via DuckDuckGo");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(warn).toHaveBeenCalledExactlyOnceWith("[web-search]", "provider request failed", {
|
||||
provider: "brave", next_provider: "duckduckgo", failure_stage: "empty_results", attempts: 1,
|
||||
http_status: 200, content_type: "text/plain", decoded_body_bytes: 17,
|
||||
parsed_results: 0, elapsed_ms: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["transport", "body_read", "parse"] as const)("keeps %s failure diagnostics content-free and still recovers", async (stage) => {
|
||||
const warn = vi.spyOn(console, "warn");
|
||||
const privateText = "private-query https://private.example/?token=secret";
|
||||
const originalMatch = String.prototype.match;
|
||||
if (stage === "parse") {
|
||||
// Inject a parser fault after a real response body is read; no fake result is injected.
|
||||
vi.spyOn(String.prototype, "match").mockImplementation(function (pattern) {
|
||||
if (String(this).includes("parser-fault-marker")) throw new Error(privateText);
|
||||
return originalMatch.call(this, pattern);
|
||||
});
|
||||
}
|
||||
const fetchMock = vi.fn(async (url: string) => {
|
||||
if (!String(url).includes("brave.com")) return new Response(DUCKDUCKGO_FIXTURE);
|
||||
if (stage === "transport") throw new Error(privateText);
|
||||
const response = new Response(stage === "parse"
|
||||
? '<div class="snippet" data-type="web">parser-fault-marker</div>'
|
||||
: privateText, { headers: { "content-type": "text/html" } });
|
||||
if (stage === "body_read") vi.spyOn(response, "text").mockRejectedValue(new Error(privateText));
|
||||
return response;
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await runBuiltinWebSearch(privateText);
|
||||
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.displayName).toBe("DuckDuckGo");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(warn).toHaveBeenCalledExactlyOnceWith("[web-search]", "provider request failed", {
|
||||
provider: "brave", next_provider: "duckduckgo", failure_stage: stage, attempts: 1,
|
||||
http_status: stage === "transport" ? null : 200,
|
||||
content_type: stage === "transport" ? "unknown" : "text/html",
|
||||
decoded_body_bytes: stage === "parse" ? 62 : null,
|
||||
parsed_results: null, elapsed_ms: expect.any(Number),
|
||||
});
|
||||
expect(JSON.stringify(warn.mock.calls)).not.toMatch(/private|secret|parser-fault-marker/);
|
||||
});
|
||||
|
||||
it("logs every exhausted provider, including the terminal failure, without reading error bodies or echoing headers", async () => {
|
||||
const warn = vi.spyOn(console, "warn");
|
||||
const readBody = vi.fn();
|
||||
const fetchMock = vi.fn(async () => {
|
||||
const response = new Response("private response body", {
|
||||
status: 503, headers: { "content-type": `private/${"x".repeat(10000)}` },
|
||||
});
|
||||
vi.spyOn(response, "text").mockImplementation(readBody);
|
||||
return response;
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await runBuiltinWebSearch("private query");
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(6);
|
||||
expect(readBody).not.toHaveBeenCalled();
|
||||
expect(warn).toHaveBeenCalledTimes(6);
|
||||
expect(warn.mock.calls.map(call => call[2].provider)).toEqual(["brave", "duckduckgo", "yahoo", "sogou", "so", "bing"]);
|
||||
expect(warn).toHaveBeenLastCalledWith("[web-search]", "provider request failed", {
|
||||
provider: "bing", next_provider: null, failure_stage: "http", attempts: 1,
|
||||
http_status: 503, content_type: "other", decoded_body_bytes: null,
|
||||
parsed_results: null, elapsed_ms: expect.any(Number),
|
||||
});
|
||||
expect(JSON.stringify(warn.mock.calls)).not.toContain("private");
|
||||
expect(JSON.stringify(warn.mock.calls).length).toBeLessThan(2500);
|
||||
});
|
||||
|
||||
it("serializes sibling keyless searches and reuses the recovered provider", async () => {
|
||||
|
||||
@@ -17,7 +17,7 @@ export async function chatEligibility(
|
||||
const excluded = new Set<string>();
|
||||
const live = new Set<string>();
|
||||
for (const row of rows) {
|
||||
if (row.deleted || (row.project_id && !projectIds.has(row.project_id))) excluded.add(row.conversation_id);
|
||||
if (row.hidden || row.deleted || (row.project_id && !projectIds.has(row.project_id))) excluded.add(row.conversation_id);
|
||||
else live.add(row.conversation_id);
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -67,3 +67,7 @@ parentPort!.on('message', (request: { id: number; file: string; indexes: number[
|
||||
parentPort!.postMessage({ id: request.id, rows });
|
||||
});
|
||||
});
|
||||
|
||||
// This application-level receipt follows Electron/TypeScript initialization;
|
||||
// Worker.online alone does not prove that terminating bootstrap is safe.
|
||||
parentPort!.postMessage({ ready: true });
|
||||
|
||||
@@ -8,13 +8,15 @@ import type { ChatSnippet } from './snippet';
|
||||
const log = createLogger('search');
|
||||
interface Reader {
|
||||
worker?: Worker;
|
||||
ready: boolean;
|
||||
unavailableUntil: number;
|
||||
pending: Map<number, {
|
||||
resolve: (rows: Map<number, ChatSnippet | undefined>) => void;
|
||||
reject: (error: Error) => void;
|
||||
dispatch?: () => void;
|
||||
}>;
|
||||
}
|
||||
const readers: Reader[] = Array.from({ length: 2 }, () => ({ unavailableUntil: 0, pending: new Map() }));
|
||||
const readers: Reader[] = Array.from({ length: 2 }, () => ({ ready: false, unavailableUntil: 0, pending: new Map() }));
|
||||
// Stable source affinity reuses each worker's bounded projection/offset cache.
|
||||
// Two workers cap simultaneous large-record parsing; four in-flight requests
|
||||
// bound dispatch overhead without opening one worker per matching history.
|
||||
@@ -52,8 +54,19 @@ function requestSnippets(reader: Reader, file: string, indexes: ReadonlySet<numb
|
||||
execArgv: [], env: { ...process.env, ORKAS_WORKSPACE_ROOT: WS_ROOT },
|
||||
});
|
||||
reader.worker = current;
|
||||
reader.ready = false;
|
||||
current.on('message', (message) => {
|
||||
if (reader.worker !== current) return;
|
||||
if (message.ready === true) {
|
||||
reader.ready = true;
|
||||
for (const request of reader.pending.values()) {
|
||||
const dispatch = request.dispatch;
|
||||
delete request.dispatch;
|
||||
dispatch?.();
|
||||
}
|
||||
if (!reader.pending.size) current.unref();
|
||||
return;
|
||||
}
|
||||
const request = reader.pending.get(message.id);
|
||||
reader.pending.delete(message.id);
|
||||
request?.resolve(new Map(message.rows));
|
||||
@@ -84,23 +97,37 @@ function requestSnippets(reader: Reader, file: string, indexes: ReadonlySet<numb
|
||||
// Parsing one oversized JSON record cannot yield. Stop an unused worker
|
||||
// immediately, but keep unrelated requests alive on a shared reader.
|
||||
if (!reader.pending.size && reader.worker === current) {
|
||||
reader.worker = undefined;
|
||||
void current.terminate();
|
||||
if (reader.ready) {
|
||||
reader.worker = undefined;
|
||||
void current.terminate();
|
||||
} else {
|
||||
// No parser has started. Killing Electron during node_init can emit
|
||||
// a native failure; retain this bounded, unreferenced bootstrap for
|
||||
// the next query. Cancelled requests are never posted to the worker.
|
||||
current.unref();
|
||||
}
|
||||
}
|
||||
};
|
||||
// Admission owns a detached command while bootstrap is pending.
|
||||
const command = { id, file, indexes: [...indexes], tokens: [...tokens],
|
||||
source: source && { ...source }, cancellation: cancellation.buffer };
|
||||
const dispatch = () => {
|
||||
try { current.postMessage(command); }
|
||||
catch {
|
||||
cleanup();
|
||||
reader.pending.delete(id);
|
||||
if (!reader.pending.size) current.unref();
|
||||
reject(new Error('Chat snippet reader unavailable'));
|
||||
}
|
||||
};
|
||||
reader.pending.set(id, {
|
||||
resolve: rows => { cleanup(); resolve(rows); },
|
||||
reject: error => { cleanup(); reject(error); },
|
||||
...(!reader.ready ? { dispatch } : {}),
|
||||
});
|
||||
signal?.addEventListener('abort', cancel, { once: true });
|
||||
if (signal?.aborted) { cancel(); return; }
|
||||
try { current.postMessage({ id, file, indexes: [...indexes], tokens, source, cancellation: cancellation.buffer }); }
|
||||
catch {
|
||||
cleanup();
|
||||
reader.pending.delete(id);
|
||||
if (!reader.pending.size) current.unref();
|
||||
reject(new Error('Chat snippet reader unavailable'));
|
||||
}
|
||||
if (reader.ready) dispatch();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -109,7 +109,7 @@ async function _getChatDisplayCatalog(userId: string): Promise<ChatDisplayCatalo
|
||||
import('../projects'),
|
||||
]);
|
||||
const [conversationRows, projectRows] = await Promise.all([
|
||||
chats.listConversationDisplayRows(userId, { includeDeleted: true }),
|
||||
chats.listConversationDisplayRows(userId, { includeDeleted: true, includeHidden: true }),
|
||||
projects.listProjectNameRows(userId),
|
||||
]);
|
||||
const eligibility = await chatEligibility(userId, conversationRows);
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
projectChatIndexFile, userContextsIndexPath, userChatsIndexPath,
|
||||
} from '../../paths';
|
||||
import { conversationMessageReadFile, listProjectIds } from '../../util/project-layout';
|
||||
import { appConversationOwner } from '../../paths';
|
||||
import { getActiveUserId } from '../users';
|
||||
import { createLogger } from '../../logger';
|
||||
import { closeChatSnippetReader } from './chat-snippets';
|
||||
@@ -361,6 +362,7 @@ export function indexChatMessageDeferred(
|
||||
msgIndex: number,
|
||||
msg: ChatMessage | JsonlAppendSource,
|
||||
): void {
|
||||
if (appConversationOwner(cid)) return;
|
||||
void indexChatMessage(userId, cid, msgIndex, msg);
|
||||
}
|
||||
|
||||
@@ -631,7 +633,7 @@ async function _listUserChats(
|
||||
const { listConversationDisplayRows } = await import('../chats');
|
||||
const projectIds = listProjectIds(userId);
|
||||
const eligibility = await chatEligibility(userId,
|
||||
await listConversationDisplayRows(userId, { includeDeleted: true }), new Set(projectIds));
|
||||
await listConversationDisplayRows(userId, { includeDeleted: true, includeHidden: true }), new Set(projectIds));
|
||||
const roots = [userChatsDir(userId), ...projectIds.map((pid) => projectChatsDir(userId, pid))];
|
||||
const candidates: Array<{ fileKey: string; file: string }> = [];
|
||||
let reliable = eligibility.complete;
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type SearchProfile,
|
||||
} from './auth';
|
||||
import { createLogger } from '../logger';
|
||||
import { searchAdaptersByProvider, runSearchAdapter } from '../model/core-agent/search-adapters';
|
||||
import { searchAdaptersByProvider, runSearchAdapter, SEARCH_PROVIDER_LABEL, SEARCH_PROVIDER_DOCS } from '../model/core-agent/search-adapters';
|
||||
import { logErrorSummary } from '../util/log-redact';
|
||||
|
||||
const log = createLogger('search-auth');
|
||||
@@ -43,6 +43,13 @@ export function listSearchProfiles(): SearchProfile[] {
|
||||
return loadSearchProfiles();
|
||||
}
|
||||
|
||||
/** Shipped public choices, without credentials or network/runtime discovery. */
|
||||
export function listSearchProviderOptions(): Array<{ id: string; label: string; docs?: string }> {
|
||||
return Object.keys(searchAdaptersByProvider).map(id => ({
|
||||
id, label: SEARCH_PROVIDER_LABEL[id] || id, docs: SEARCH_PROVIDER_DOCS[id],
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the first usable search profile for tool dispatch. Returns null when
|
||||
* the user has no search profiles configured (caller should fall back to
|
||||
|
||||
@@ -98,6 +98,7 @@ function evidenceRowKey(line: string): string | null {
|
||||
|
||||
function normalizeSourceUrl(rawUrl: string): string {
|
||||
const parsed = new URL(rawUrl);
|
||||
if (!['http:', 'https:'].includes(parsed.protocol)) throw new TypeError('Invalid web source protocol');
|
||||
parsed.hash = '';
|
||||
return parsed.toString();
|
||||
}
|
||||
@@ -120,12 +121,14 @@ export function captureDeepResearchWebFetchEvidence(
|
||||
const content = String(result.content || '');
|
||||
if (result.isError || !content) return { captured: false, reason: 'not_web_source' };
|
||||
if (CACHE_REPLAY_RE.test(content)) return { captured: false, reason: 'cache_replay' };
|
||||
const match = SOURCE_URL_RE.exec(content);
|
||||
if (!match) return { captured: false, reason: 'not_web_source' };
|
||||
// Prefer the fetcher's authoritative response identity. Legacy HTML/GitHub
|
||||
// snapshots still carry the same source in their existing header.
|
||||
const sourceUrl = result.webSourceUrl ?? SOURCE_URL_RE.exec(content)?.[1];
|
||||
if (!sourceUrl) return { captured: false, reason: 'not_web_source' };
|
||||
|
||||
let canonicalUrl = '';
|
||||
try {
|
||||
canonicalUrl = normalizeSourceUrl(match[1]);
|
||||
canonicalUrl = normalizeSourceUrl(sourceUrl);
|
||||
} catch {
|
||||
return { captured: false, reason: 'not_web_source' };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
/** Stable across chats/devices and credential refresh, without sending raw uid.
|
||||
* This is a domain-separated pseudonym, not authentication or encryption.
|
||||
* Missing/anonymous scope retains per-chat SDK behavior instead of sharing it. */
|
||||
export function providerUserCacheKey(userId: string | null | undefined): string | undefined {
|
||||
if (!userId || userId === 'anonymous') return undefined;
|
||||
return createHash('sha256').update(JSON.stringify(['orkas:user-cache:v1', userId])).digest('hex');
|
||||
}
|
||||
@@ -24,7 +24,8 @@
|
||||
* this map.
|
||||
*/
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import type * as fs from 'node:fs';
|
||||
import { fileSystemForPath } from '../../util/user-file-fs';
|
||||
import type { ToolContext } from '#core-agent';
|
||||
|
||||
/** ctx.state key the runner injects the run-scoped read-state map under.
|
||||
@@ -73,7 +74,7 @@ export function recordRead(ctx: ToolContext, abs: string, st?: fs.Stats, hash?:
|
||||
const rs = getReadState(ctx);
|
||||
if (!rs) return;
|
||||
try {
|
||||
const stat = st ?? fs.statSync(abs);
|
||||
const stat = st ?? fileSystemForPath(abs).statSync(abs);
|
||||
rs.set(abs, stampFromStats(stat, hash));
|
||||
} catch {
|
||||
// File vanished between read and stamp — leave it unstamped; the edit
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import { fileSystemForPath } from '../../util/user-file-fs';
|
||||
import * as path from 'node:path';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
|
||||
@@ -405,7 +405,7 @@ export function parseIgnoreRules(content: string): IgnoreRule[] {
|
||||
/** Read `<dir>/.gitignore`, returning null when absent or unreadable. */
|
||||
export function readIgnoreScope(dir: string): IgnoreScope | null {
|
||||
let content: string;
|
||||
try { content = fs.readFileSync(path.join(dir, '.gitignore'), 'utf8'); }
|
||||
try { content = fileSystemForPath(dir).readFileSync(path.join(dir, '.gitignore'), 'utf8'); }
|
||||
catch { return null; }
|
||||
const rules = parseIgnoreRules(content);
|
||||
return rules.length ? { dir, rules } : null;
|
||||
@@ -422,11 +422,36 @@ export function isIgnoredByScopes(
|
||||
const rel = path.relative(scope.dir, absPath);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) continue;
|
||||
const posix = rel.split(path.sep).join('/');
|
||||
for (const rule of scope.rules) {
|
||||
if (rule.dirOnly && !isDir) continue;
|
||||
if (!rule.re.test(posix)) continue;
|
||||
ignored = !rule.negate;
|
||||
}
|
||||
ignored = applyIgnoreRules(ignored, posix, isDir, scope.rules);
|
||||
}
|
||||
return ignored;
|
||||
}
|
||||
|
||||
function applyIgnoreRules(ignored: boolean, relative: string, isDir: boolean, rules: readonly IgnoreRule[]): boolean {
|
||||
for (const rule of rules) {
|
||||
if (rule.dirOnly && !isDir) continue;
|
||||
if (rule.re.test(relative)) ignored = !rule.negate;
|
||||
}
|
||||
return ignored;
|
||||
}
|
||||
|
||||
/** Prepare inherited ignore scopes once for direct opendir entries in this directory. */
|
||||
export function createDirectoryIgnoreMatcher(dir: string, scopes: readonly IgnoreScope[]): (name: string, isDir: boolean) => boolean {
|
||||
const prepared = scopes.flatMap(scope => {
|
||||
const relative = path.relative(scope.dir, dir);
|
||||
if (relative.startsWith('..') || path.isAbsolute(relative)) return [];
|
||||
const prefix = relative ? relative.split(path.sep).join('/') + '/' : '';
|
||||
return [{ prefix, rules: scope.rules, fileRules: scope.rules.filter(rule => !rule.dirOnly) }];
|
||||
});
|
||||
const fileScopes = prepared.filter(scope => scope.fileRules.length > 0);
|
||||
return (name, isDir) => {
|
||||
let ignored = false;
|
||||
for (const scope of isDir ? prepared : fileScopes) {
|
||||
const relative = scope.prefix + name;
|
||||
// Preserve the absolute-path helper's existing relative-path boundary.
|
||||
if (relative.startsWith('..')) continue;
|
||||
ignored = applyIgnoreRules(ignored, relative, isDir, isDir ? scope.rules : scope.fileRules);
|
||||
}
|
||||
return ignored;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { parameterError } from '../../../../bin/tool-parameter-errors.cjs';
|
||||
/**
|
||||
* `web_search` override — last-write-wins replacement for core-agent's
|
||||
* built-in keyless web_search.
|
||||
@@ -31,6 +32,8 @@ import { runSearchAdapter, SEARCH_PROVIDER_LABEL, SearchAccountError } from './s
|
||||
import { createLogger } from '../../logger';
|
||||
import { logErrorSummary } from '../../util/log-redact';
|
||||
import { getSearchQueryMaxChars, validateSearchQuery } from '../../util/search-contract';
|
||||
import { createTavilySearchTurn, currentTavilySearchTurn, recordTavilySearchRequest,
|
||||
type TavilySearchTurn } from '../../util/tavily-search-turn';
|
||||
|
||||
// core-agent is ESM; main is CJS. Static import would yank pi-ai into the
|
||||
// CJS load graph and crash with `ERR_PACKAGE_PATH_NOT_EXPORTED`. Same
|
||||
@@ -97,7 +100,10 @@ function formatPaidResults(query: string, providerLabel: string, results: { titl
|
||||
}
|
||||
|
||||
export async function createWebSearchOverrideTool(context?: SearchExecutionContext): Promise<AgentTool> {
|
||||
const cid = context?.conversationId || '';
|
||||
const owningTurn = currentTavilySearchTurn(getActiveUserId(), cid);
|
||||
const mod = await ca();
|
||||
let fallbackTurn: TavilySearchTurn | undefined;
|
||||
const firstProfile = listSearchProfiles()[0];
|
||||
// Keyless search retains its existing unrestricted query contract.
|
||||
const maxQueryChars = firstProfile ? getSearchQueryMaxChars(firstProfile.provider) : undefined;
|
||||
@@ -153,7 +159,7 @@ export async function createWebSearchOverrideTool(context?: SearchExecutionConte
|
||||
const query = String((input as any)?.query || '').trim();
|
||||
const requested = Number((input as any)?.count) || DEFAULT_COUNT;
|
||||
const count = Math.min(Math.max(1, requested), MAX_COUNT);
|
||||
if (!query) return { content: 'Error: query is required', isError: true };
|
||||
if (!query) return parameterError('Error: query is required', ['query'], 'required');
|
||||
|
||||
const profiles = listSearchProfiles();
|
||||
// A changed setting can tighten this run's advertised bound. A wider
|
||||
@@ -161,10 +167,26 @@ export async function createWebSearchOverrideTool(context?: SearchExecutionConte
|
||||
const currentMax = profiles[0] ? getSearchQueryMaxChars(profiles[0].provider) : undefined;
|
||||
const applicableMax = Math.min(maxQueryChars ?? Infinity, currentMax ?? Infinity);
|
||||
try { if (Number.isFinite(applicableMax)) validateSearchQuery(query, applicableMax); } catch (error) {
|
||||
return { content: (error as Error).message, isError: true };
|
||||
return parameterError((error as Error).message, ['query'], 'invalid_value');
|
||||
}
|
||||
const userId = getActiveUserId();
|
||||
let searchTurn = owningTurn?.userId === userId ? owningTurn : currentTavilySearchTurn(userId, cid);
|
||||
if (!searchTurn) {
|
||||
if (!fallbackTurn || fallbackTurn.userId !== userId || fallbackTurn.cid !== cid) {
|
||||
fallbackTurn = createTavilySearchTurn(userId, cid);
|
||||
}
|
||||
searchTurn = fallbackTurn;
|
||||
}
|
||||
// Count one admitted tool invocation, independently of provider fallback
|
||||
// or retry attempts. Reserve synchronously so parallel results retain
|
||||
// their own threshold even when responses finish out of order.
|
||||
const reminderCount = recordTavilySearchRequest(searchTurn);
|
||||
const finish = (result: ToolResult): ToolResult => reminderCount === undefined ? result : {
|
||||
...result,
|
||||
content: `${result.content}\n\nThis turn: ${reminderCount} web searches. Prioritize completing the task with existing evidence; search further if necessary.`,
|
||||
};
|
||||
|
||||
if (profiles.length) {
|
||||
const userId = getActiveUserId();
|
||||
const candidates = profiles.map(profile => ({ profile, key: searchCooldownKey(userId, profile) }));
|
||||
const errors: string[] = [];
|
||||
let accountErr: string | null = null;
|
||||
@@ -178,16 +200,16 @@ export async function createWebSearchOverrideTool(context?: SearchExecutionConte
|
||||
paidSearchCooldowns.delete(key);
|
||||
// Input incompatibility must not advance the fallback chain or dispatch a request.
|
||||
try { validateSearchQuery(query, getSearchQueryMaxChars(profile.provider)); } catch (error) {
|
||||
return { content: (error as Error).message, isError: true };
|
||||
return finish({ content: (error as Error).message, isError: true });
|
||||
}
|
||||
log.info('web_search via paid API', { provider: profile.provider, query_len: query.length, count });
|
||||
try {
|
||||
const res = await runSearchAdapter(profile, query, count, context);
|
||||
log.info('web_search paid API ok', { provider: profile.provider, results: res.results.length });
|
||||
const text = formatPaidResults(query, label, res.results);
|
||||
return res.results.length
|
||||
return finish(res.results.length
|
||||
? { content: text, displayName: label }
|
||||
: { content: text, displayName: label, isError: true };
|
||||
: { content: text, displayName: label, isError: true });
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message || String(err);
|
||||
errors.push(`${label}: ${msg}`);
|
||||
@@ -203,11 +225,11 @@ export async function createWebSearchOverrideTool(context?: SearchExecutionConte
|
||||
});
|
||||
}
|
||||
}
|
||||
return runKeylessFallback(query, count, errors, accountErr);
|
||||
return finish(await runKeylessFallback(query, count, errors, accountErr));
|
||||
}
|
||||
|
||||
log.info('web_search via builtin keyless (no paid profile configured)', { query_len: query.length, count });
|
||||
return mod.runBuiltinWebSearch(query, count);
|
||||
return finish(await mod.runBuiltinWebSearch(query, count));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
|
||||
/** Memory-only user-turn state. Queue items retain this reference so delayed
|
||||
* descendants cannot adopt a later user message's counter. No queries are kept. */
|
||||
export interface TavilySearchTurn {
|
||||
readonly userId: string;
|
||||
readonly cid: string;
|
||||
requests: number;
|
||||
}
|
||||
|
||||
const activeTurn = new AsyncLocalStorage<TavilySearchTurn>();
|
||||
|
||||
export function createTavilySearchTurn(userId: string, cid: string): TavilySearchTurn {
|
||||
return { userId, cid, requests: 0 };
|
||||
}
|
||||
|
||||
export function currentTavilySearchTurn(userId: string, cid: string): TavilySearchTurn | undefined {
|
||||
const turn = activeTurn.getStore();
|
||||
return turn?.userId === userId && turn.cid === cid ? turn : undefined;
|
||||
}
|
||||
|
||||
export function withTavilySearchTurn<T>(turn: TavilySearchTurn, run: () => T): T {
|
||||
return activeTurn.run(turn, run);
|
||||
}
|
||||
|
||||
/** Called synchronously once per admitted web_search tool invocation, across
|
||||
* providers and keyless search, including failed calls.
|
||||
* Each crossing belongs to its issuing tool result; nothing rejects a request. */
|
||||
export function recordTavilySearchRequest(turn: TavilySearchTurn): number | undefined {
|
||||
const count = ++turn.requests;
|
||||
return count >= 10 && count % 5 === 0 ? count : undefined;
|
||||
}
|
||||
@@ -315,7 +315,7 @@ async function _loadVisibleChatSnippets() {
|
||||
const anchor = body.querySelector('.search-result.active');
|
||||
const rect = anchor?.getBoundingClientRect();
|
||||
const bounds = body.getBoundingClientRect();
|
||||
const visible = rect && rect.bottom > bounds.top && rect.top < bounds.bottom;
|
||||
const visible = top > 0 && rect && rect.bottom > bounds.top && rect.top < bounds.bottom;
|
||||
_renderSearchResults(query);
|
||||
body.scrollTop = top;
|
||||
const retained = visible && body.querySelector('.search-result.active');
|
||||
@@ -362,7 +362,9 @@ async function _runProgressiveSearch(query, seq, startedAt, projectId, pending)
|
||||
const anchor = body?.querySelector('.search-result.active');
|
||||
const rect = anchor?.getBoundingClientRect();
|
||||
const bounds = anchor ? body.getBoundingClientRect() : null;
|
||||
const visible = rect && rect.bottom > bounds.top && rect.top < bounds.bottom;
|
||||
// At the start of the list, late categories must not pull the viewport
|
||||
// down to the row that happened to be selected by the first page.
|
||||
const visible = top > 0 && rect && rect.bottom > bounds.top && rect.top < bounds.bottom;
|
||||
_renderSearchResults(query);
|
||||
if (body) {
|
||||
body.scrollTop = top;
|
||||
|
||||
@@ -9,26 +9,11 @@ for (const language of ['en', 'zh'] as const) {
|
||||
await page.locator('[data-settings-model-tab="search"]').click();
|
||||
};
|
||||
if (!orkas.page) throw new Error('Renderer unavailable');
|
||||
const installNetworkGuard = async () => {
|
||||
await orkas.electronApp!.evaluate(() => {
|
||||
const state = globalThis as typeof globalThis & { __deepseekSettingsExternalRequests?: number };
|
||||
state.__deepseekSettingsExternalRequests = 0;
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const raw = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
if (!['localhost', '127.0.0.1', '[::1]'].includes(new URL(raw).hostname)) {
|
||||
state.__deepseekSettingsExternalRequests! += 1;
|
||||
return Promise.reject(new Error('E_E2E_UNEXPECTED_EXTERNAL_REQUEST'));
|
||||
}
|
||||
return original(input, init);
|
||||
}) as typeof fetch;
|
||||
});
|
||||
};
|
||||
const installNetworkGuard = () => orkas.guardExternalFetches();
|
||||
const expectLocalOnly = async () => {
|
||||
expect(await orkas.electronApp!.evaluate(() => (globalThis as any).__deepseekSettingsExternalRequests)).toBe(0);
|
||||
expect(await orkas.externalFetchAttempts()).toBe(0);
|
||||
expect(orkas.modelRequests).toHaveLength(0);
|
||||
expect(orkas.imageGenerationRequests).toHaveLength(0);
|
||||
expect(orkas.videoGenerationRequests).toHaveLength(0);
|
||||
expect(orkas.apiRequests).toEqual([]);
|
||||
};
|
||||
await installNetworkGuard();
|
||||
expect(await orkas.invoke('orkasApi.configureAll', { apiKey: 'orkas-e2e-deepseek-public-row-xxxxxxxx' }))
|
||||
|
||||
@@ -39,6 +39,61 @@ test.afterEach(async ({}, info) => {
|
||||
if (analysis.requiresReview) console.info(formatProcessLogSummary(analysis));
|
||||
});
|
||||
|
||||
test('hides app-private history in real search and after restart while preserving the source archive', async ({}, info) => {
|
||||
const app = new OrkasTestApp(info, { configuredModel: false, marketplaceStub: true, seedLanguage: 'en' });
|
||||
try {
|
||||
await app.launch();
|
||||
await installEmptyLibrarySearch(app, pcRoot);
|
||||
const identity = await app.electronApp!.evaluate(async (_, root) => {
|
||||
const req = (process as any).mainModule.require.bind((process as any).mainModule);
|
||||
const fs = req('node:fs');
|
||||
const chats = req(`${root}/src/main/features/chats.ts`);
|
||||
const paths = req(`${root}/src/main/util/project-layout.ts`);
|
||||
const store = req(`${root}/src/main/features/search/chat_store.ts`);
|
||||
const hidden = await chats.createConversation('account-e2e', { kind: 'app_task', title: 'Internal application archive' });
|
||||
const visible = await chats.createConversation('account-e2e', { title: 'My archive notes' });
|
||||
const text = 'archivevisibilitymarker';
|
||||
for (const row of [hidden, visible]) {
|
||||
fs.writeFileSync(paths.conversationMessageFile('account-e2e', row.conversation_id), JSON.stringify({ role: 'user', content: text, time: 't' }) + '\n');
|
||||
store.replaceConversation('account-e2e', row.conversation_id,
|
||||
[{ cid: row.conversation_id, msgIndex: 0, role: 'user', time: 't', text }], { mtime: 1, size: 1, next: 1 });
|
||||
}
|
||||
return { hidden: hidden.conversation_id, visible: visible.conversation_id,
|
||||
file: paths.conversationMessageFile('account-e2e', hidden.conversation_id) };
|
||||
}, pcRoot);
|
||||
const source = readFileSync(identity.file);
|
||||
const check = async () => {
|
||||
for (const includeChatSnippets of [false, true]) {
|
||||
const page = await app.invoke<any>('search.global', { query: 'archivevisibilitymarker', scope: 'chat', includeChatSnippets });
|
||||
expect(page.results.map((row: any) => row.cid)).toEqual([identity.visible]);
|
||||
}
|
||||
const page = app.page!;
|
||||
await page.locator('#sidebar-search-btn').click();
|
||||
await page.locator('#search-input').fill('archivevisibilitymarker');
|
||||
await page.locator('#search-input').press('Enter');
|
||||
await page.locator('.search-tab[data-tab="chat"]').click();
|
||||
await expect(page.locator('#search-body .search-result-title')).toHaveText(['My archive notes']);
|
||||
await expect(page.locator('#search-body .search-result-snippet')).toContainText('archivevisibilitymarker');
|
||||
expect(readFileSync(identity.file)).toEqual(source);
|
||||
await page.locator('#search-input').press('Escape');
|
||||
};
|
||||
await check();
|
||||
expect(await app.electronApp!.evaluate(async (_, root) => {
|
||||
const req = (process as any).mainModule.require.bind((process as any).mainModule);
|
||||
await req(`${root}/src/main/features/search/indexer.ts`).reconcileChatsIndex('account-e2e');
|
||||
return [...req(`${root}/src/main/features/search/chat_store.ts`).indexedConversationIds('account-e2e')];
|
||||
}, pcRoot)).toEqual([identity.visible]);
|
||||
await app.relaunch();
|
||||
await installEmptyLibrarySearch(app, pcRoot);
|
||||
await check();
|
||||
await app.page!.locator('#sidebar-search-btn').click();
|
||||
await app.page!.locator('#search-input').fill('archivevisibilitymarker');
|
||||
await app.page!.locator('#search-input').press('Enter');
|
||||
await expect(app.page!.locator('#search-body .search-result-title')).toHaveText(['My archive notes']);
|
||||
await app.page!.screenshot({ path: info.outputPath('search-app-private-restart.png') });
|
||||
} finally { await app.dispose(); }
|
||||
});
|
||||
|
||||
test('searches automations and to-dos in distinct categories and reveals their current entries', async ({}, info) => {
|
||||
const app = new OrkasTestApp(info, { configuredModel: false, seedLanguage: 'zh' });
|
||||
try {
|
||||
@@ -601,6 +656,73 @@ test('shows cold chat matches within the input latency budget while snippet read
|
||||
}
|
||||
});
|
||||
|
||||
for (const [language, width, height] of [['zh', 1280, 800], ['en', 900, 640]] as const) {
|
||||
test(`keeps the start of search results visible when earlier categories arrive later (${language})`, async ({}, info) => {
|
||||
const app = new OrkasTestApp(info, { configuredModel: false, seedLanguage: language });
|
||||
try {
|
||||
await app.launch();
|
||||
await installEmptyLibrarySearch(app, pcRoot);
|
||||
const ids: string[] = [];
|
||||
for (let index = 0; index < 10; index++) {
|
||||
const { task } = await app.invoke<any>('autoTasks.create', {
|
||||
title: `Scrollmarker automation ${index}`, content: 'Scrollmarker ' + 'long summary '.repeat(30),
|
||||
enabled: false, schedule: { type: 'daily', hour: 9, minute: 0 },
|
||||
});
|
||||
ids.push(task.id);
|
||||
}
|
||||
await app.electronApp!.evaluate(async (_, root) => {
|
||||
const req = (process as any).mainModule.require.bind((process as any).mainModule);
|
||||
const uid = req(`${root}/src/main/features/users.ts`).getActiveUserId();
|
||||
const now = new Date().toISOString();
|
||||
await req(`${root}/src/main/features/connectors/registry.ts`).upsert(uid, {
|
||||
id: 'custom-scrollmarker', origin: 'custom', display_name: 'Scrollmarker connector',
|
||||
transport: { kind: 'streamable-http', url: 'https://example.test/mcp' },
|
||||
enabled_subtools: null, tools_cache: [], tools_cached_at: 0,
|
||||
status: { kind: 'disconnected' }, created_at: now, updated_at: now,
|
||||
});
|
||||
}, pcRoot);
|
||||
const page = app.page!;
|
||||
await page.setViewportSize({ width, height });
|
||||
// Hold only the automation files, leaving the real connector search,
|
||||
// stream/preload/IPC and renderer free to publish the first category.
|
||||
await app.electronApp!.evaluate((_, input) => {
|
||||
const req = (process as any).mainModule.require.bind((process as any).mainModule);
|
||||
const uid = req(`${input.root}/src/main/features/users.ts`).getActiveUserId();
|
||||
const layout = req(`${input.root}/src/main/util/project-layout.ts`);
|
||||
const files = new Set(input.ids.map(id => layout.findAutoTaskLocation(uid, id).configFile));
|
||||
const fsp = req('node:fs/promises'), originalRead = fsp.readFile;
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
fsp.readFile = async function(target: any, ...args: any[]) {
|
||||
if (files.has(String(target))) await gate;
|
||||
return originalRead.call(this, target, ...args);
|
||||
};
|
||||
req('node:module').syncBuiltinESMExports();
|
||||
(globalThis as any).__releaseScrollmarker = () => {
|
||||
release(); fsp.readFile = originalRead; req('node:module').syncBuiltinESMExports();
|
||||
};
|
||||
}, { root: pcRoot, ids });
|
||||
await page.locator('#sidebar-search-btn').click();
|
||||
await page.locator('#search-input').fill('Scrollmarker');
|
||||
await page.locator('#search-input').press('Enter');
|
||||
const results = page.locator('#search-body .search-result');
|
||||
await expect(results).toHaveCount(1);
|
||||
await expect(results).toContainText('Scrollmarker connector');
|
||||
expect(await page.locator('#search-body').evaluate(body => body.scrollTop)).toBe(0);
|
||||
await app.electronApp!.evaluate(() => (globalThis as any).__releaseScrollmarker());
|
||||
await expect(results).toHaveCount(11);
|
||||
await expect(page.locator('#search-body .search-loading-spinner')).toHaveCount(0);
|
||||
expect(await page.locator('#search-body').evaluate(body => body.scrollHeight > body.clientHeight)).toBe(true);
|
||||
expect(await page.locator('#search-body').evaluate(body => body.scrollTop)).toBe(0);
|
||||
await expect(results.first()).toBeInViewport();
|
||||
await expect(results.first()).toContainText('Scrollmarker automation 0');
|
||||
await expect(page.locator('#search-input')).toBeFocused();
|
||||
await page.screenshot({ path: info.outputPath(`search-top-${language}-${width}.png`) });
|
||||
await page.locator('#search-input').press('Escape');
|
||||
} finally { await app.dispose(); }
|
||||
});
|
||||
}
|
||||
|
||||
test('paints local hits before held semantic retrieval and preserves selection when body results arrive', async ({}, info) => {
|
||||
const app = new OrkasTestApp(info, { configuredModel: false, seedLanguage: 'en' });
|
||||
try {
|
||||
@@ -827,7 +949,7 @@ test('shows preparation before full results, searches partial history, and resum
|
||||
});
|
||||
|
||||
test('runs rebuild, live indexing and snippet workers from an ASAR with the shipped dependency layout', async ({}, testInfo) => {
|
||||
const app = new OrkasTestApp(testInfo, { configuredModel: false });
|
||||
const app = new OrkasTestApp(testInfo, { configuredModel: false, marketplaceStub: true });
|
||||
try {
|
||||
const source = path.join(app.root, 'package-source');
|
||||
const archive = path.join(app.root, 'fixture.asar');
|
||||
@@ -882,8 +1004,16 @@ test('runs rebuild, live indexing and snippet workers from an ASAR with the ship
|
||||
const snippet = await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(new Error('Packaged snippet worker did not respond')), 10_000);
|
||||
snippetWorker.once('error', (error: Error) => { clearTimeout(timeout); reject(error); });
|
||||
snippetWorker.once('message', (message: any) => { clearTimeout(timeout); resolve(message.rows[0]?.[1]?.snippet); });
|
||||
snippetWorker.postMessage({ id: 1, file, indexes: [0], tokens: ['packagedmarker'], source: { userId: 'packaged-fixture', cid: 'source' } });
|
||||
snippetWorker.on('message', (message: any) => {
|
||||
// The application-ready receipt precedes the correlated reply.
|
||||
if (message.ready === true) {
|
||||
snippetWorker!.postMessage({ id: 1, file, indexes: [0], tokens: ['packagedmarker'], source: { userId: 'packaged-fixture', cid: 'source' } });
|
||||
return;
|
||||
}
|
||||
if (message.id !== 1) return;
|
||||
clearTimeout(timeout);
|
||||
resolve(message.rows[0]?.[1]?.snippet);
|
||||
});
|
||||
});
|
||||
return { complete: batch.complete, liveComplete, liveMatches: store.postingsFor('packaged-fixture', 'packagedlivemarker').length, count: store.docCount('packaged-fixture'),
|
||||
matches: store.postingsFor('packaged-fixture', 'packagedmarker').length, snippet };
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { webFetchTool } from '../../../src/core-agent/src/tools/web-fetch';
|
||||
import { captureDeepResearchWebFetchEvidence } from '../../../src/main/model/core-agent/deep-research-evidence';
|
||||
|
||||
const PC_ROOT = path.resolve(__dirname, '../../..');
|
||||
const RUN_SKILL = path.join(PC_ROOT, 'bin', 'run-skill.cjs');
|
||||
@@ -23,6 +25,7 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
@@ -48,6 +51,41 @@ function runScript(script: string, args: string[]) {
|
||||
}
|
||||
|
||||
describe('DeepResearch bundled Skill scripts through run-skill.cjs', () => {
|
||||
it.each(['application/json', 'text/plain'])('verifies a quote from a successful %s fetch without changing its body', async (contentType) => {
|
||||
const quote = 'Offline use requires an initial model download.';
|
||||
const body = contentType === 'application/json' ? JSON.stringify({ fact: quote }) : quote;
|
||||
const url = 'https://example.test/official-guide';
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, {
|
||||
headers: { 'content-type': contentType },
|
||||
})));
|
||||
const fetched = await webFetchTool.execute({ url }, { state: {} });
|
||||
expect(fetched.isError).not.toBe(true);
|
||||
expect(fetched.content).toBe(contentType === 'application/json'
|
||||
? JSON.stringify({ fact: quote }, null, 2) : body);
|
||||
captureDeepResearchWebFetchEvidence(fetched, path.join(tmpDir, 'source-snapshots.jsonl'));
|
||||
fs.writeFileSync(path.join(tmpDir, 'evidence_ledger.jsonl'), JSON.stringify({
|
||||
id: 'E1', source_id: 'S1', candidate: 'Example app', field: 'local_offline',
|
||||
claim: quote, quote, canonical_url: url,
|
||||
}) + '\n');
|
||||
writeJson('citations_input.json', { compact_landscape: {
|
||||
title: 'Offline availability', boundary: 'Controlled official source.',
|
||||
analysis_markdown: 'Offline availability is conditional on the initial download [E1].',
|
||||
candidates: [{ candidate: 'Example app', best_for: 'Conditional offline use', ideal_user: 'Local user' }],
|
||||
} });
|
||||
const result = runScript('citations', [
|
||||
'--op', 'verify', '--input', 'citations_input.json', '--out', 'citations_output.json',
|
||||
'--report-out', 'RESEARCH-offline.md',
|
||||
]);
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stderr).toBe('');
|
||||
const output = JSON.parse(fs.readFileSync(path.join(tmpDir, 'citations_output.json'), 'utf8')).data;
|
||||
expect(output.summary).toMatchObject({ verified: 1, flagged: 0 });
|
||||
expect(output.comparison_coverage[0].fields_with_citations).toEqual(['local_offline']);
|
||||
const report = fs.readFileSync(path.join(tmpDir, 'RESEARCH-offline.md'), 'utf8');
|
||||
expect(report).toContain(quote);
|
||||
expect(report).toContain('E1');
|
||||
});
|
||||
|
||||
it('plans caps from workspace-relative input and writes workspace-relative output', () => {
|
||||
writeJson('caps_input.json', {
|
||||
depth: 1,
|
||||
@@ -238,6 +276,7 @@ describe('DeepResearch bundled Skill scripts through run-skill.cjs', () => {
|
||||
'utf8',
|
||||
);
|
||||
const sourceText = Object.values(claims).join('\n');
|
||||
fs.appendFileSync(path.join(tmpDir, 'evidence_ledger.jsonl'), '{broken\nnull\n', 'utf8');
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, 'source-snapshots.jsonl'),
|
||||
`${JSON.stringify({
|
||||
@@ -276,6 +315,12 @@ describe('DeepResearch bundled Skill scripts through run-skill.cjs', () => {
|
||||
enabled: true,
|
||||
selected_evidence_rows: 6,
|
||||
candidate_rows: 1,
|
||||
ledger_diagnostics: {
|
||||
nonempty_lines: 8,
|
||||
reason_counts: { invalid_json: 1, non_object: 1 },
|
||||
samples: [{ line: 7, reason: 'invalid_json' }, { line: 8, reason: 'non_object' }],
|
||||
omitted_samples: 0,
|
||||
},
|
||||
});
|
||||
expect(stdout.report).toMatchObject({ path: 'RESEARCH-REPORT.md' });
|
||||
expect(stdout).not.toHaveProperty('comparison_markdown');
|
||||
@@ -288,6 +333,7 @@ describe('DeepResearch bundled Skill scripts through run-skill.cjs', () => {
|
||||
expect(report).not.toContain('material limitation:');
|
||||
expect(report).toContain('| Candidate | Best for |');
|
||||
expect(report).toContain('## Evidence used');
|
||||
expect(report).not.toContain('invalid_json');
|
||||
});
|
||||
|
||||
it('loads the academic entrypoint and reports an unknown provider without making a network call', () => {
|
||||
|
||||
@@ -161,7 +161,7 @@ it('avoids history reads and full cache scans for cold summaries, with negative
|
||||
return await new Promise<any>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(Error('Cold summary worker timed out')), 10_000);
|
||||
worker.once('error', error => { clearTimeout(timeout); reject(error); });
|
||||
worker.once('message', result => { clearTimeout(timeout); resolve(result); });
|
||||
worker.on('message', result => { if (result.id !== 1) return; clearTimeout(timeout); resolve(result); });
|
||||
// No entry covers every token: pruning must work even without the
|
||||
// early-return path, and the later best match must retain its position.
|
||||
worker.postMessage({ id: 1, file, indexes: [0], tokens: ['电商', '领域', 'absent'], ...(cached ? { source: { userId: uid, cid } } : {}) });
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'node:events';
|
||||
|
||||
const state = vi.hoisted(() => ({ workers: [] as any[], warn: vi.fn() }));
|
||||
const state = vi.hoisted(() => ({ workers: [] as any[], warn: vi.fn(), holdReady: false }));
|
||||
vi.mock('../../../../src/main/logger', () => ({ createLogger: () => ({ warn: state.warn }) }));
|
||||
vi.mock('node:worker_threads', () => ({
|
||||
Worker: class extends EventEmitter {
|
||||
commands: any[] = [];
|
||||
constructor() { super(); state.workers.push(this); }
|
||||
constructor() { super(); state.workers.push(this); queueMicrotask(() => { if (!state.holdReady) this.emit('message', { ready: true }); }); }
|
||||
ref() {}
|
||||
unref() {}
|
||||
postMessage(command: unknown) { this.commands.push(command); }
|
||||
@@ -15,10 +15,44 @@ vi.mock('node:worker_threads', () => ({
|
||||
}));
|
||||
|
||||
afterEach(async () => {
|
||||
state.holdReady = false;
|
||||
await (await import('../../../../src/main/features/search/chat-snippets')).closeChatSnippetReader();
|
||||
state.workers = [];
|
||||
state.warn.mockClear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.each([false, true])('cancels without terminating bootstrap, but still interrupts an initialized parser (ready=%s)', async ready => {
|
||||
const { readChatSnippets } = await import('../../../../src/main/features/search/chat-snippets');
|
||||
state.holdReady = true;
|
||||
const before = state.workers.length;
|
||||
const controller = new AbortController();
|
||||
const cancelled = readChatSnippets('cancelled-source', new Set([0]), ['old'], controller.signal);
|
||||
void cancelled.catch(() => {});
|
||||
await vi.waitFor(() => expect(state.workers).toHaveLength(before + 1));
|
||||
const worker = state.workers[before];
|
||||
const terminate = vi.spyOn(worker, 'terminate');
|
||||
if (ready) worker.emit('message', { ready: true });
|
||||
expect(worker.commands).toHaveLength(ready ? 1 : 0);
|
||||
controller.abort();
|
||||
expect((await cancelled).size).toBe(0);
|
||||
expect(terminate).toHaveBeenCalledTimes(ready ? 1 : 0);
|
||||
|
||||
const indexes = new Set([1]), tokens = ['replacement'];
|
||||
const replacement = readChatSnippets('cancelled-source', indexes, tokens);
|
||||
void replacement.catch(() => {});
|
||||
await vi.waitFor(() => expect(state.workers).toHaveLength(before + (ready ? 2 : 1)));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
indexes.add(2); tokens[0] = 'later query';
|
||||
const owner = state.workers.at(-1);
|
||||
owner.emit('message', { ready: true });
|
||||
await vi.waitFor(() => expect(owner.commands.at(-1)?.tokens).toEqual(['replacement']));
|
||||
expect(owner.commands.at(-1).indexes).toEqual([1]);
|
||||
const command = owner.commands.at(-1);
|
||||
owner.emit('message', { id: command.id, rows: [[1, { snippet: 'replacement', visible: true }]] });
|
||||
expect((await replacement).get(1)?.snippet).toBe('replacement');
|
||||
});
|
||||
|
||||
it('fails pending and queued reads on worker failure without leaking source details or causing a restart storm', async () => {
|
||||
const { readChatSnippets } = await import('../../../../src/main/features/search/chat-snippets');
|
||||
let now = 100_000;
|
||||
|
||||
@@ -860,6 +860,48 @@ describe('search › searchChats — group-chat shape end-to-end', () => {
|
||||
});
|
||||
|
||||
describe('search › searchChats', () => {
|
||||
it('excludes app-owned background history from both real search and rebuild without deleting its source',async()=>{
|
||||
const chats=await import('../../../../src/main/features/chats');const hidden=await chats.createConversation(TEST_UID,{kind:'app_task',title:'Background media'}),visible=await chats.createConversation(TEST_UID,{title:'My media task'});
|
||||
for(const row of [hidden,visible])writeChat(TEST_UID,row.conversation_id,[{role:'user',content:'unique media archive reference',time:'2026-11-12T00:00:00Z'}]);
|
||||
const ix=await import('../../../../src/main/features/search/indexer');await ix.reconcileChatsIndex(TEST_UID);const search=await loadSearch();
|
||||
expect((await search.searchChats(TEST_UID,'unique media archive reference')).map(r=>r.cid)).toEqual([visible.conversation_id]);
|
||||
expect(fs.existsSync(path.join(tmpDir,TEST_UID,'cloud/chats',hidden.conversation_id+'.jsonl'))).toBe(true);expect((await chats.getConversationMetadata(TEST_UID,hidden.conversation_id))?.kind).toBe('app_task');
|
||||
});
|
||||
|
||||
it('filters old app-task postings from previews, snippets and progressive results before repairing only derived data', async () => {
|
||||
const boot = await import('../../../../src/main/util/boot_init');
|
||||
boot.configureBootAdmission({ isRuntimeBusy: () => true });
|
||||
try {
|
||||
const chats = await import('../../../../src/main/features/chats');
|
||||
const store = await import('../../../../src/main/features/search/chat_store');
|
||||
const hidden = await chats.createConversation(TEST_UID, { kind: 'app_task', title: 'Internal archive' });
|
||||
const visible = await chats.createConversation(TEST_UID, { title: 'App notes' });
|
||||
const text = 'archivevisibilitymarker';
|
||||
for (const row of [hidden, visible]) {
|
||||
writeChat(TEST_UID, row.conversation_id, [{ role: 'user', content: text, time: 't' }]);
|
||||
store.replaceConversation(TEST_UID, row.conversation_id,
|
||||
[{ cid: row.conversation_id, msgIndex: 0, role: 'user', time: 't', text }],
|
||||
{ mtime: 1, size: 1, next: 1 });
|
||||
}
|
||||
const source = path.join(tmpDir, TEST_UID, 'cloud/chats', `${hidden.conversation_id}.jsonl`);
|
||||
const before = fs.readFileSync(source);
|
||||
const search = await loadSearch();
|
||||
for (const includeChatSnippets of [false, true]) {
|
||||
expect((await search.searchAll(TEST_UID, text, { scope: 'chat', includeChatSnippets })).results.map(row => row.cid))
|
||||
.toEqual([visible.conversation_id]);
|
||||
}
|
||||
const pages = [];
|
||||
for await (const page of search.streamSearch(TEST_UID, text, { scope: 'chat' })) pages.push(page);
|
||||
expect(pages.length).toBeGreaterThan(0);
|
||||
for (const page of pages) expect(page.results.map(row => row.cid)).toEqual([visible.conversation_id]);
|
||||
const ix = await import('../../../../src/main/features/search/indexer');
|
||||
expect((await ix.reconcileChatsIndex(TEST_UID)).complete).toBe(true);
|
||||
expect(store.indexedConversationIds(TEST_UID)).toEqual(new Set([visible.conversation_id]));
|
||||
expect(fs.readFileSync(source)).toEqual(before);
|
||||
expect((await chats.getConversationMetadata(TEST_UID, hidden.conversation_id))?.kind).toBe('app_task');
|
||||
} finally { boot._resetForTests(); }
|
||||
});
|
||||
|
||||
it('fills conv_title from _index.json when present', async () => {
|
||||
writeChat('u1', 'c1', [{ role: 'user', content: 'widget question', time: 't' }]);
|
||||
const indexFile = path.join(tmpDir, 'u1', 'cloud', 'chats', '_index.json');
|
||||
|
||||
@@ -56,6 +56,27 @@ async function loadIndexer() {
|
||||
return import('../../../../src/main/features/search/indexer');
|
||||
}
|
||||
|
||||
it('keeps both app execution lifetimes out of live indexing while ordinary app-named conversations remain searchable', async () => {
|
||||
const ix = await loadIndexer();
|
||||
await ix.reconcileChatsIndex(TEST_UID);
|
||||
const storage = await import('../../../../src/main/storage');
|
||||
const { conversationMessageFile } = await import('../../../../src/main/util/project-layout');
|
||||
const cids = ['app_notes', ...['once', 'retain'].map(mode => `app_${'a'.repeat(64)}_${mode}_${'b'.repeat(32)}`)];
|
||||
const sources: string[] = [];
|
||||
for (const cid of cids) {
|
||||
const file = conversationMessageFile(TEST_UID, cid);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const row = await storage.appendJsonlAtomic(file, { role: 'user', content: 'appindexmarker', time: 't' }, true);
|
||||
sources.push(file);
|
||||
ix.indexChatMessageDeferred(TEST_UID, cid, row.msgIndex, row.source!);
|
||||
}
|
||||
await ix.drainDeferredChatWrites(TEST_UID);
|
||||
expect((await loadChatStore()).indexedConversationIds(TEST_UID)).toEqual(new Set(['app_notes']));
|
||||
expect((await (await import('../../../../src/main/features/search')).searchChats(TEST_UID, 'appindexmarker')).map(row => row.cid))
|
||||
.toEqual(['app_notes']);
|
||||
for (const file of sources) expect(fs.readFileSync(file, 'utf8')).toContain('appindexmarker');
|
||||
});
|
||||
|
||||
// The chat index moved from a JSON snapshot to `chat_store`; these read the
|
||||
// same facts the cases used to read off `entry.idx`.
|
||||
async function loadChatStore() {
|
||||
|
||||
@@ -85,7 +85,8 @@ it('immediately searches the full tool-output tail while live indexing leaves th
|
||||
const maxGap = Math.max(...gaps);
|
||||
expect(gaps.length).toBeGreaterThan(5);
|
||||
expect(maxGap).toBeLessThan(INTERACTIVE_MAIN_GAP_LIMIT_MS);
|
||||
expect(controlGap, 'the synchronous control must exceed the platform ceiling').toBeGreaterThanOrEqual(INTERACTIVE_MAIN_GAP_LIMIT_MS);
|
||||
// The relative control still rejects moving the same work back onto main,
|
||||
// even on a host where that reference fits the absolute device allowance.
|
||||
expect(maxGap).toBeLessThan(controlGap / 2);
|
||||
expect(store.postingsFor(uid, 'word099999')).toHaveLength(1);
|
||||
expect(store.postingsFor(uid, 'privatethoughtmarker')).toHaveLength(0);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BULK_MAIN_GAP_LIMIT_MS } from '../../../helpers/latency-budget';
|
||||
import { BULK_MAIN_GAP_LIMIT_MS, INDEXED_SEARCH_LATENCY_LIMIT_MS } from '../../../helpers/latency-budget';
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
@@ -88,9 +88,10 @@ it('keeps real searches and the main timer responsive while indexing a full mult
|
||||
const sorted = partial.map(query => query.ms).sort((a, b) => a - b);
|
||||
const p95 = sorted[Math.floor((sorted.length - 1) * .95)];
|
||||
expect(maxGap, 'main timer remains interactive during the native worker transaction').toBeLessThan(BULK_MAIN_GAP_LIMIT_MS);
|
||||
expect(controlGap, 'the synchronous control must exceed the platform ceiling').toBeGreaterThanOrEqual(BULK_MAIN_GAP_LIMIT_MS);
|
||||
// Keep the same-work relative control even when this host's synchronous
|
||||
// reference is faster than the device-tolerant absolute ceiling.
|
||||
expect(maxGap, 'negative control must detect main-thread tokenization/writes').toBeLessThan(controlGap / 2);
|
||||
expect(p95).toBeLessThan(200);
|
||||
expect(p95).toBeLessThan(INDEXED_SEARCH_LATENCY_LIMIT_MS);
|
||||
expect(store.docCount(uid), 'reader statistics observe external worker commits').toBe(2);
|
||||
expect(store.postingsFor(uid, 'tailmarker')).toHaveLength(1);
|
||||
expect(store.postingsFor(uid, 'term0149999')).toHaveLength(1);
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { it, expect, vi } from 'vitest';
|
||||
import { createPiProvider, AgentRunner, ProviderRegistry, createConfig } from '#core-agent';
|
||||
import { createRotatingProvider } from '../../../../src/main/model/core-agent/rotating-provider';
|
||||
import { _clearAll, getCooldown } from '../../../../src/main/model/core-agent/profile-cooldown';
|
||||
|
||||
// Recovery portfolio: a known length stop must remain distinguishable from
|
||||
// unknown emptiness. Compare the native Runner seam with its configured entry.
|
||||
// No network, model, tools, or private account state is used.
|
||||
for (const api of ['openai-completions', 'openai-responses'] as const) {
|
||||
for (const shape of ['empty', 'text', 'thinking', 'repeated-empty'] as const) {
|
||||
for (const wrapped of [false, true]) {
|
||||
it(`${api}/${shape}/${wrapped ? 'configured' : 'direct'}`, async () => {
|
||||
_clearAll();
|
||||
let requests = 0;
|
||||
const emitted: string[] = [];
|
||||
const fallbackBuild = vi.fn();
|
||||
vi.stubGlobal('fetch', vi.fn(async () => {
|
||||
requests++;
|
||||
if (requests > 4) throw new Error('Synthetic request budget exceeded');
|
||||
const truncated = requests === 1 || shape === 'repeated-empty';
|
||||
const text = truncated ? shape === 'text' ? 'Partial explanation.' : '' : 'Recovered.';
|
||||
const reasoning = truncated && shape === 'thinking' ? 'Synthetic reasoning.' : '';
|
||||
if (api === 'openai-completions') {
|
||||
return new Response(`data: ${JSON.stringify({ choices: [{ index: 0,
|
||||
delta: { role: 'assistant', ...(text ? { content: text } : {}),
|
||||
...(reasoning ? { reasoning_content: reasoning } : {}) },
|
||||
finish_reason: truncated ? 'length' : 'stop',
|
||||
}], usage: { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 } })}\n\ndata: [DONE]\n\n`,
|
||||
{ headers: { 'content-type': 'text/event-stream' } });
|
||||
}
|
||||
const output: any[] = [];
|
||||
if (reasoning) output.push({ type: 'reasoning', id: 'rs_fixture', summary: [{ type: 'summary_text', text: reasoning }] });
|
||||
if (text) output.push({ type: 'message', id: 'msg_fixture', role: 'assistant',
|
||||
content: [{ type: 'output_text', text, annotations: [] }] });
|
||||
const events: any[] = output.flatMap((item, output_index) => [
|
||||
{ type: 'response.output_item.added', output_index, item: { ...item, content: [], summary: [] } },
|
||||
...(item.type === 'reasoning'
|
||||
? [{ type: 'response.reasoning_summary_text.delta', output_index, summary_index: 0, delta: reasoning }]
|
||||
: [{ type: 'response.output_text.delta', output_index, delta: text }]),
|
||||
{ type: 'response.output_item.done', output_index, item },
|
||||
]);
|
||||
events.push({ type: truncated ? 'response.incomplete' : 'response.completed', response: {
|
||||
id: 'resp_fixture', status: truncated ? 'incomplete' : 'completed', output,
|
||||
...(truncated ? { incomplete_details: { reason: 'max_output_tokens' } } : {}),
|
||||
usage: { input_tokens: 10, output_tokens: 10, total_tokens: 20 },
|
||||
} });
|
||||
return new Response(events.map(event => `data: ${JSON.stringify(event)}\n\n`).join(''),
|
||||
{ headers: { 'content-type': 'text/event-stream' } });
|
||||
}));
|
||||
try {
|
||||
const native = createPiProvider({ provider: 'custom', apiKey: 'fixture', customModel: {
|
||||
id: 'fixture', name: 'Fixture', provider: 'custom', api, baseUrl: 'https://fixture.invalid/v1',
|
||||
reasoning: true, input: ['text'], contextWindow: 128000, maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
} });
|
||||
const provider = wrapped ? createRotatingProvider({ providerId: 'custom', networkRetryAttempts: 0,
|
||||
candidates: [{ profileId: 'primary', providerId: 'custom', modelId: 'fixture', build: async () => native },
|
||||
{ profileId: 'fallback', providerId: 'custom', modelId: 'fixture', build: fallbackBuild }],
|
||||
}) : native;
|
||||
const registry = new ProviderRegistry();
|
||||
registry.registerFactory('custom', () => provider);
|
||||
const runner = new AgentRunner({ providers: registry,
|
||||
config: createConfig({ agent: { defaultProvider: 'custom', defaultModel: 'fixture', maxRetries: 0 } }),
|
||||
evolution: { enabled: false }, tools: [],
|
||||
});
|
||||
let result: any;
|
||||
for await (const event of runner.runStream({ message: 'Explain the result.' })) {
|
||||
emitted.push(event.type);
|
||||
if (event.type === 'done') result = event.result;
|
||||
}
|
||||
const row = { api, shape, wrapped, requests, text: result?.text,
|
||||
error: result?.meta.error, signals: result?.meta.convergenceSignals,
|
||||
providerEmpty: emitted.filter(type => type === 'provider_empty').length,
|
||||
terminalCount: emitted.filter(type => type === 'done').length,
|
||||
cooldown: !!getCooldown('primary'), fallbackBuilds: fallbackBuild.mock.calls.length };
|
||||
expect(row.providerEmpty).toBe(0);
|
||||
expect(row.fallbackBuilds).toBe(0);
|
||||
expect(row.cooldown).toBe(false);
|
||||
expect(row.terminalCount).toBe(1);
|
||||
expect(result.meta.usage.totalTokens).toBe(shape === 'repeated-empty' ? 80 : 40);
|
||||
if (shape === 'repeated-empty') {
|
||||
expect(requests).toBe(4);
|
||||
expect(result.meta.error?.code).toBe('OUTPUT_LIMIT');
|
||||
} else {
|
||||
expect(result.meta.error).toBeUndefined();
|
||||
expect(requests).toBe(2);
|
||||
expect(result.text).toContain('Recovered.');
|
||||
}
|
||||
} finally { vi.unstubAllGlobals(); _clearAll(); }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,7 @@ describe('deep research evidence capture', () => {
|
||||
|
||||
it('does not replace evidence with a compacted cache replay', () => {
|
||||
const capture = captureDeepResearchWebFetchEvidence({
|
||||
webSourceUrl: 'https://example.test/guide',
|
||||
content: [
|
||||
'WEB_FETCH_RUN_CACHE_HIT: no network request was made.',
|
||||
'URL: https://example.test/guide',
|
||||
@@ -115,6 +116,37 @@ describe('deep research evidence capture', () => {
|
||||
expect(capture).toEqual({ captured: false, reason: 'cache_replay' });
|
||||
});
|
||||
|
||||
it('uses the fetched response identity instead of a URL line supplied by the page', async () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-evidence-origin-'));
|
||||
const body = 'URL: https://unrelated.test/spoofed\nThe app requires an initial download.';
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, {
|
||||
headers: { 'content-type': 'text/plain' },
|
||||
})));
|
||||
try {
|
||||
const { webFetchTool } = await import('../../../../src/core-agent/src/tools/web-fetch');
|
||||
const result = await webFetchTool.execute({ url: 'https://example.test/official' }, { state: {} });
|
||||
const file = deepResearchEvidenceFile(root);
|
||||
// Ordinary result transformations copy the envelope; provenance follows it.
|
||||
expect(captureDeepResearchWebFetchEvidence({ ...result }, file).captured).toBe(true);
|
||||
const row = JSON.parse(fs.readFileSync(file, 'utf8').trim());
|
||||
expect(row).toMatchObject({ canonical_url: 'https://example.test/official', text: body });
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['not a URL', 'file:///private/source', 'javascript:alert(1)'])('rejects invalid explicit source identity %s', (webSourceUrl) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-evidence-invalid-origin-'));
|
||||
try {
|
||||
const file = deepResearchEvidenceFile(root);
|
||||
expect(captureDeepResearchWebFetchEvidence({
|
||||
webSourceUrl, content: 'URL: https://unrelated.test/fallback\nClaimed source fact.',
|
||||
}, file)).toEqual({ captured: false, reason: 'not_web_source' });
|
||||
expect(fs.existsSync(file)).toBe(false);
|
||||
} finally { fs.rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it.each(['overwrite', 'replace'])('recaptures evidence after a same-size %s preserving mtime', async (operation) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-evidence-preserved-time-'));
|
||||
try {
|
||||
@@ -187,6 +219,7 @@ describe('deep research evidence capture', () => {
|
||||
try {
|
||||
const file = deepResearchEvidenceFile(root);
|
||||
const failed = captureDeepResearchWebFetchEvidence({
|
||||
webSourceUrl: 'https://example.test/guide',
|
||||
content: [
|
||||
'URL: https://example.test/guide',
|
||||
'E_FETCH_FAILED: upstream request timed out',
|
||||
|
||||
@@ -6,9 +6,10 @@ import type { Api, Model } from '@earendil-works/pi-ai';
|
||||
import { createPiProvider } from '../../../../src/core-agent/src/providers/pi-provider.js';
|
||||
import { PUBLIC_PROVIDER_MODELS } from '../../../../src/main/model/public_model_catalog';
|
||||
import { CATALOG } from '../../../../src/main/model/provider_catalog';
|
||||
import { providerUserCacheKey } from '../../../../src/main/model/core-agent/provider-cache-scope';
|
||||
import type { CompletionParams } from '../../../../src/core-agent/src/providers/base.js';
|
||||
|
||||
import { buildCustomAnthropicModel, buildCustomOpenAICompatibleModel,
|
||||
import { buildCustomAnthropicModel, buildCustomOpenAICompatibleModel, buildCustomResponsesModel,
|
||||
buildDeepSeekModel, buildDoubaoModel, buildRuntimeMoonshotModel, buildOrkasApiModel,
|
||||
} from '../../../../src/main/model/core-agent/external-providers';
|
||||
|
||||
@@ -38,6 +39,7 @@ const scenarios: Array<[string, () => Model<Api> | Promise<Model<Api>>]> = [
|
||||
['minimax-cn-oauth', () => ({ ...builtin('minimax-cn', 'MiniMax-M3'), provider: 'minimax-portal-cn' })],
|
||||
['orkas-api', () => buildOrkasApiModel('orkas-llm-1.5-pro')],
|
||||
['custom-chat', () => buildCustomOpenAICompatibleModel('fixture', config)],
|
||||
['custom-responses', () => buildCustomResponsesModel('fixture', config)],
|
||||
['custom-claude', () => buildCustomAnthropicModel('fixture', config)],
|
||||
];
|
||||
const report: unknown[] = [];
|
||||
@@ -48,6 +50,14 @@ afterAll(() => {
|
||||
});
|
||||
|
||||
describe('Provider cache and conversation isolation contracts', () => {
|
||||
it('keeps opaque user mapping stable without manufacturing a shared anonymous identity', () => {
|
||||
for (const absent of [undefined, null, '', 'anonymous']) expect(providerUserCacheKey(absent)).toBeUndefined();
|
||||
const a = providerUserCacheKey('用户/opaque-A')!;
|
||||
expect(a).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(a).toBe(providerUserCacheKey('用户/opaque-A'));
|
||||
expect(a).not.toBe(providerUserCacheKey('用户/opaque-B'));
|
||||
expect(a).not.toContain('opaque-A');
|
||||
});
|
||||
it('covers every built-in provider card and public custom routes', async () => {
|
||||
const models = await Promise.all(scenarios.map(([, build]) => build()));
|
||||
expect(new Set(models.map(model => model.provider))).toEqual(new Set([
|
||||
@@ -95,9 +105,9 @@ describe('Provider cache and conversation isolation contracts', () => {
|
||||
expect(semantic(captures[0].payload)).toEqual(semantic(captures[1].payload));
|
||||
expect(JSON.stringify(semantic(captures[0].payload))).not.toContain('fixture-chat-');
|
||||
const a = captures[0].headers!, b = captures[1].headers!;
|
||||
if (model.api === 'openai-codex-responses') {
|
||||
expect(a.get('session-id')).toBe(b.get('session-id'));
|
||||
expect(a.get('session-id')).not.toBe('fixture-chat-a');
|
||||
if (model.api === 'openai-codex-responses' || model.api === 'openai-responses') {
|
||||
expect(a.get('session-id')).toBe('opaque-user-fixture');
|
||||
expect(b.get('session-id')).toBe('opaque-user-fixture');
|
||||
expect(a.get('x-client-request-id')).not.toBe(b.get('x-client-request-id'));
|
||||
} else expect(a.has('session-id') || b.has('session-id')).toBe(false);
|
||||
if (model.provider === 'openrouter') {
|
||||
|
||||
@@ -9,7 +9,8 @@ import { PassThrough } from 'node:stream';
|
||||
|
||||
import {
|
||||
grepRepository,
|
||||
isIgnoredByScopes,
|
||||
isIgnoredByScopes as isIgnoredByAbsolutePath,
|
||||
createDirectoryIgnoreMatcher,
|
||||
listRepositoryFiles,
|
||||
parseIgnoreRules,
|
||||
visitRepositoryFiles,
|
||||
@@ -145,7 +146,10 @@ describe('repository search interruption', () => {
|
||||
// implementation these cases pin. A miss here means `search_files` starts
|
||||
// surfacing build output, logs and local config that the project ignored —
|
||||
// the model's context fills with noise nobody asked for.
|
||||
describe('repository-search › ignore rules', () => {
|
||||
describe.each(['absolute', 'directory'] as const)('repository-search › ignore rules (%s)', backend => {
|
||||
const isIgnoredByScopes: typeof isIgnoredByAbsolutePath = backend === 'absolute'
|
||||
? isIgnoredByAbsolutePath
|
||||
: (file, isDir, scopes) => createDirectoryIgnoreMatcher(path.dirname(file), scopes)(path.basename(file), isDir);
|
||||
function scope(dir: string, content: string) {
|
||||
return [{ dir, rules: parseIgnoreRules(content) }];
|
||||
}
|
||||
@@ -213,6 +217,15 @@ describe('repository-search › ignore rules', () => {
|
||||
expect(isIgnoredByScopes(at('other', 'dist'), true, nested)).toBe(false);
|
||||
});
|
||||
|
||||
it('applies nested scope overrides in declaration order without leaking to sibling directories', () => {
|
||||
const scopes = [...scope(ROOT, '*.log\n'), ...scope(at('pkg'), '!keep.log\nprivate/\n')];
|
||||
expect(isIgnoredByScopes(at('pkg', 'keep.log'), false, scopes)).toBe(false);
|
||||
expect(isIgnoredByScopes(at('pkg', 'drop.log'), false, scopes)).toBe(true);
|
||||
expect(isIgnoredByScopes(at('peer', 'keep.log'), false, scopes)).toBe(true);
|
||||
expect(isIgnoredByScopes(at('pkg', 'private'), true, scopes)).toBe(true);
|
||||
expect(isIgnoredByScopes(at('pkg', 'private'), false, scopes)).toBe(false);
|
||||
});
|
||||
|
||||
it('skips comments and blank lines instead of treating them as patterns', () => {
|
||||
const rules = parseIgnoreRules('# comment\n\n \nreal\n');
|
||||
expect(rules).toHaveLength(1);
|
||||
|
||||
@@ -319,10 +319,12 @@ describe('public search query and response bounds', () => {
|
||||
await expect(runSearchAdapter({provider, apiKey:'fixture'} as any, '🌏'.repeat(provider === 'tavily' ? 401 : 129), 8)).rejects.toThrow(String(provider === 'tavily' ? 400 : 128));
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([['deepseek',128], ['tavily',400]] as const)('sends the complete trimmed %s Unicode query', async(provider,length)=>{
|
||||
const fetch=vi.fn(async()=>new Response(JSON.stringify({results:[]}))); vi.stubGlobal('fetch',fetch);
|
||||
it.each([['deepseek',127], ['deepseek',128], ['tavily',129], ['tavily',399], ['tavily',400]] as const)('sends the complete trimmed %s Unicode query', async(provider,length)=>{
|
||||
const fetch=vi.fn(async()=>new Response(JSON.stringify({results:[{url:'https://example.org',summary:'DS evidence',content:'TV evidence'}]}))); vi.stubGlobal('fetch',fetch);
|
||||
const query='🌏'.repeat(length);
|
||||
await runSearchAdapter({provider,apiKey:'fixture'} as any,' '+query+' ',3);
|
||||
const result=await runSearchAdapter({provider,apiKey:'fixture'} as any,' '+query+' ',3);
|
||||
expect(result.results[0].snippet).toBe(provider==='deepseek'?'DS evidence':'TV evidence');
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
expect(JSON.parse((fetch.mock.calls[0] as any)[1].body).query).toBe(query);
|
||||
});
|
||||
it.each(['deepseek','tavily'])('rejects unsafe result URLs and bounds %s evidence',async provider=>{
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { AgentRunner, createConfig, ProviderRegistry, Session } from '../../../../src/core-agent/src/index';
|
||||
import type { CompletionParams, LLMProvider } from '../../../../src/core-agent/src/providers/base';
|
||||
import type { MessageContent } from '../../../../src/core-agent/src/shared/types';
|
||||
import { createRunProgramTool } from '../../../../src/core-agent/src/tools/run-program';
|
||||
import { ProgramWorkerPool, programWorkerPool } from '../../../../src/core-agent/src/tools/run-program-worker-pool';
|
||||
import { createWebSearchOverrideTool } from '../../../../src/main/model/core-agent/search-tools';
|
||||
import { capToolResult } from '../../../../src/main/util/tool-result-cap';
|
||||
import { createTavilySearchTurn, withTavilySearchTurn } from '../../../../src/main/util/tavily-search-turn';
|
||||
|
||||
const h = vi.hoisted(() => ({ provider: 'tavily', warn: vi.fn(), error: vi.fn() }));
|
||||
vi.mock('../../../../src/main/features/users', () => ({ getActiveUserId: () => 'reminder-user' }));
|
||||
vi.mock('../../../../src/main/features/search_auth', () => ({
|
||||
listSearchProfiles: () => [{ id: 'fixture-search', provider: h.provider, apiKey: 'fixture-key' }],
|
||||
}));
|
||||
vi.mock('../../../../src/main/logger', () => ({
|
||||
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: h.warn, error: h.error }),
|
||||
}));
|
||||
|
||||
const search = (count: number): MessageContent => ({
|
||||
type: 'tool_use', id: `source-${count}`, name: 'web_search', input: { query: `source ${count}` },
|
||||
});
|
||||
const reminder = 'This turn: 10 web searches. Prioritize completing the task with existing evidence; search further if necessary.';
|
||||
|
||||
describe('search reminder delivery through the real execution loop', () => {
|
||||
let root: string;
|
||||
let dispatched: string[];
|
||||
beforeEach(() => {
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), 'search-reminder-runtime-'));
|
||||
dispatched = [];
|
||||
h.provider = 'tavily';
|
||||
h.warn.mockClear(); h.error.mockClear();
|
||||
vi.stubGlobal('fetch', vi.fn(async (url, init) => {
|
||||
expect(String(url)).toBe(h.provider === 'tavily' ? 'https://api.tavily.com/search' : 'https://api.deepseek.com/v1/tools/search');
|
||||
const { query } = JSON.parse(String(init.body));
|
||||
dispatched.push(query);
|
||||
const evidence = query === 'source 10' ? 'Evidence from source ten. '.repeat(400) : `Evidence for ${query}.`;
|
||||
return new Response(JSON.stringify({ code: 0, results: Array.from({ length: query === 'source 10' ? 5 : 1 }, (_, index) => ({ title: query, url: `https://source.test/evidence/${index}`, content: evidence, snippet: evidence })) }));
|
||||
}));
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
expect(h.warn).not.toHaveBeenCalled();
|
||||
expect(h.error).not.toHaveBeenCalled();
|
||||
});
|
||||
afterAll(() => programWorkerPool.dispose());
|
||||
|
||||
async function execute(script: MessageContent[][], programmatic = false) {
|
||||
const requests: CompletionParams[] = [];
|
||||
const registry = new ProviderRegistry();
|
||||
const provider: LLMProvider = {
|
||||
id: 'fixture', name: 'Fixture', validateAuth: async () => true,
|
||||
async complete() { throw new Error('No auxiliary model calls expected'); },
|
||||
async *stream(params) {
|
||||
requests.push(structuredClone(params));
|
||||
const content = script.shift();
|
||||
if (!content) throw new Error('Unexpected additional model request');
|
||||
yield { type: 'message_start' as const };
|
||||
for (const part of content) if (part.type === 'text') yield { type: 'text_delta' as const, text: part.text };
|
||||
yield { type: 'message_end' as const, content, model: 'fixture-model',
|
||||
stopReason: content.some(part => part.type === 'tool_use') ? 'tool_use' as const : 'end_turn' as const };
|
||||
},
|
||||
};
|
||||
registry.registerFactory('fixture', () => provider);
|
||||
const scope = createTavilySearchTurn('reminder-user', 'reminder-conversation');
|
||||
return withTavilySearchTurn(scope, async () => {
|
||||
const tool = await createWebSearchOverrideTool({ conversationId: 'reminder-conversation', turnId: 'fixture-turn' });
|
||||
const runner = new AgentRunner({
|
||||
providers: registry, session: new Session(), tools: [tool],
|
||||
config: createConfig({
|
||||
agent: { defaultProvider: 'fixture', defaultModel: 'fixture-model' },
|
||||
models: { catalog: { 'fixture-model': { provider: 'fixture', model: 'fixture-model', contextWindow: 272_000, maxOutputTokens: 4_096 } } },
|
||||
evolution: { enabled: false },
|
||||
}),
|
||||
transformToolResult: (name, result, ctx) => capToolResult(name, result, ctx, {
|
||||
toolResultsDir: path.join(root, 'results'), maxInlineTokens: 512,
|
||||
}),
|
||||
...(programmatic ? { programmaticToolPolicy: {
|
||||
isEligible: (name: string) => name === 'web_search', authorize: () => ({ allowed: true as const }),
|
||||
} } : {}),
|
||||
});
|
||||
const result = await runner.run({ message: 'Research the sources and deliver the findings.', workingDir: root });
|
||||
return { requests, result, scope };
|
||||
});
|
||||
}
|
||||
|
||||
it.each(['tavily', 'deepseek'])('delivers provider-specific query bounds and outcomes through the real runner (%s)', async provider => {
|
||||
h.provider = provider;
|
||||
const query = '🌏'.repeat(129);
|
||||
const { requests, scope } = await execute([
|
||||
[{type:'tool_use', id:'long-query', name:'web_search', input:{query}}],
|
||||
[{type:'text', text:'Boundary observed.'}],
|
||||
]);
|
||||
const definition = requests[0].tools?.find(tool => tool.name === 'web_search');
|
||||
expect((definition?.inputSchema as any).properties.query.maxLength).toBe(provider === 'tavily' ? 400 : 128);
|
||||
const receipt = requests[1].messages.flatMap(message => message.content)
|
||||
.find(part => part.type === 'tool_result' && part.toolUseId === 'long-query');
|
||||
expect(receipt).toBeDefined();
|
||||
if (receipt?.type !== 'tool_result') throw new Error('Missing search receipt');
|
||||
expect(Boolean(receipt.isError)).toBe(provider !== 'tavily');
|
||||
expect(dispatched).toEqual(provider === 'tavily' ? [query] : []);
|
||||
expect(scope.requests).toBe(provider === 'tavily' ? 1 : 0);
|
||||
});
|
||||
|
||||
it.each(['tavily', 'deepseek'])('delivers one reminder after parallel search and result spilling, then permits another search (%s)', async provider => {
|
||||
h.provider = provider;
|
||||
const { requests, result, scope } = await execute([
|
||||
Array.from({ length: 9 }, (_, index) => search(index + 1)), [search(10)], [search(11)],
|
||||
[{ type: 'text', text: 'Research delivered.' }],
|
||||
]);
|
||||
expect(result.text).toBe('Research delivered.');
|
||||
expect(dispatched).toHaveLength(11);
|
||||
expect(scope.requests).toBe(11);
|
||||
expect(requests).toHaveLength(4);
|
||||
const receipts = requests[2].messages.flatMap(message => message.content).filter(part => part.type === 'tool_result');
|
||||
expect(receipts.filter(part => part.content.includes(reminder))).toHaveLength(1);
|
||||
const last = receipts.find(part => part.toolUseId === 'source-10');
|
||||
expect(last?.content).toContain('<persisted-output');
|
||||
expect(last?.content).toContain(reminder);
|
||||
expect(requests.every(request => !(request.systemPrompt || '').includes('web searches.'))).toBe(true);
|
||||
});
|
||||
|
||||
it('shares the parent counter with a programmatic search when a previously created worker handles the call', async () => {
|
||||
// Warm the reusable worker outside this conversation, so callback execution
|
||||
// cannot accidentally inherit the first user's async context forever.
|
||||
const warm = createRunProgramTool({ listToolNames: () => [], invokeTool: async () => { throw new Error('No child calls expected'); } });
|
||||
expect((await warm.execute({ code: "text('ready')" }, { workingDir: root, state: {} })).isError).not.toBe(true);
|
||||
const { requests, result, scope } = await execute([
|
||||
Array.from({ length: 9 }, (_, index) => search(index + 1)),
|
||||
[{ type: 'tool_use', id: 'program-source-10', name: 'run_program', input: {
|
||||
code: "const result = await tools.web_search({query:'source 10'}); if (!result.ok) throw new Error(result.content); text(result.content);",
|
||||
} }],
|
||||
[{ type: 'text', text: 'Research delivered.' }],
|
||||
], true);
|
||||
expect(result.text).toBe('Research delivered.');
|
||||
expect(dispatched).toHaveLength(10);
|
||||
expect(scope.requests).toBe(10);
|
||||
const receipts = requests[2].messages.flatMap(message => message.content).filter(part => part.type === 'tool_result');
|
||||
expect(receipts.find(part => part.toolUseId === 'program-source-10')?.content).toContain(reminder);
|
||||
});
|
||||
|
||||
it.each(['tavily', 'deepseek'])('starts a fresh counter in the same conversation while reusing a previous turn worker (%s)', async provider => {
|
||||
h.provider = provider;
|
||||
// A dedicated real pool guarantees reuse of the worker created under the
|
||||
// first turn, regardless of test order or other workers' async contexts.
|
||||
const pool = new ProgramWorkerPool(1);
|
||||
const executeWorker = vi.spyOn(programWorkerPool, 'execute').mockImplementation(options => pool.execute(options));
|
||||
const programSearch = (index: number): MessageContent => ({
|
||||
type: 'tool_use', id: `program-source-${index}`, name: 'run_program', input: {
|
||||
code: `const result = await tools.web_search({query:'source ${index}'}); if (!result.ok) throw new Error(result.content); text(result.content);`,
|
||||
},
|
||||
});
|
||||
try {
|
||||
const first = await execute([
|
||||
[programSearch(1)], Array.from({ length: 8 }, (_, index) => search(index + 2)),
|
||||
[{ type: 'text', text: 'Research delivered.' }],
|
||||
], true);
|
||||
expect(first.result.text).toBe('Research delivered.');
|
||||
expect(first.scope.requests).toBe(9);
|
||||
const second = await execute([
|
||||
[programSearch(1)], Array.from({ length: 8 }, (_, index) => search(index + 2)), [programSearch(10)],
|
||||
[{ type: 'text', text: 'Research delivered.' }],
|
||||
], true);
|
||||
expect(second.result.text).toBe('Research delivered.');
|
||||
expect(second.requests).toHaveLength(4);
|
||||
for (const request of second.requests.slice(0, 3)) {
|
||||
expect(request.messages.flatMap(message => message.content)
|
||||
.some(part => part.type === 'tool_result' && part.content.includes('This turn:'))).toBe(false);
|
||||
}
|
||||
const receipts = second.requests[3].messages.flatMap(message => message.content).filter(part => part.type === 'tool_result');
|
||||
expect(receipts.filter(part => part.content.includes(reminder))).toHaveLength(1);
|
||||
expect(receipts.find(part => part.toolUseId === 'program-source-10')?.content).toContain(reminder);
|
||||
expect(first.scope.requests).toBe(9);
|
||||
expect(second.scope.requests).toBe(10);
|
||||
expect(dispatched).toHaveLength(19);
|
||||
expect(executeWorker).toHaveBeenCalledTimes(3);
|
||||
} finally {
|
||||
executeWorker.mockRestore();
|
||||
await pool.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps counting private programmatic results and delivers the next reminder on a direct search', async () => {
|
||||
const { requests, result, scope } = await execute([
|
||||
Array.from({ length: 9 }, (_, index) => search(index + 1)),
|
||||
[{ type: 'tool_use', id: 'filtered-source-10', name: 'run_program', input: {
|
||||
code: "const result = await tools.web_search({query:'source 10'}); if (!result.ok) throw new Error(result.content); text('Selected one relevant source.');",
|
||||
} }],
|
||||
Array.from({ length: 5 }, (_, index) => search(index + 11)),
|
||||
[{ type: 'text', text: 'Research delivered.' }],
|
||||
], true);
|
||||
expect(result.text).toBe('Research delivered.');
|
||||
expect(dispatched).toHaveLength(15);
|
||||
expect(scope.requests).toBe(15);
|
||||
expect(requests).toHaveLength(4);
|
||||
const filtered = requests[2].messages.flatMap(message => message.content)
|
||||
.find(part => part.type === 'tool_result' && part.toolUseId === 'filtered-source-10');
|
||||
// Existing program privacy: only explicit program output enters context.
|
||||
// This also documents why child-result reminders alone cannot guarantee delivery.
|
||||
expect(filtered?.type === 'tool_result' && filtered.content).toContain('Selected one relevant source.');
|
||||
expect(filtered?.type === 'tool_result' && filtered.content).not.toContain(reminder);
|
||||
const receipts = requests[3].messages.flatMap(message => message.content).filter(part => part.type === 'tool_result');
|
||||
expect(receipts.filter(part => part.content.includes('This turn: 15 web searches.'))).toHaveLength(1);
|
||||
expect(receipts.find(part => part.toolUseId === 'source-15')?.content).toContain('This turn: 15 web searches.');
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,18 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const h = vi.hoisted(() => ({
|
||||
candidates: [] as Array<Record<string, any>>,
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
apiBase: 'https://search-account.test/api',
|
||||
runBuiltinWebSearch: vi.fn(),
|
||||
runSearchAdapter: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../../src/main/features/users', () => ({ getActiveUserId: () => h.userId }));
|
||||
vi.mock('../../../../src/main/features/account/token_store', () => ({
|
||||
authHeaders: () => ({ user_id: h.userId, session_id: h.sessionId }),
|
||||
}));
|
||||
vi.mock('../../../../src/main/features/account/server', () => ({ accountApiBase: () => h.apiBase }));
|
||||
|
||||
vi.mock('#core-agent', () => ({
|
||||
defineTool: (definition: Record<string, unknown>) => definition,
|
||||
runBuiltinWebSearch: (...args: unknown[]) => h.runBuiltinWebSearch(...args),
|
||||
@@ -36,10 +34,10 @@ vi.mock('../../../../src/main/model/core-agent/search-adapters', () => {
|
||||
};
|
||||
});
|
||||
vi.mock('../../../../src/main/logger', () => ({
|
||||
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
|
||||
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: h.warn, error: h.error }),
|
||||
}));
|
||||
vi.mock('../../../../src/main/util/log-redact', () => ({
|
||||
logErrorSummary: (error: unknown) => String(error),
|
||||
vi.mock('../../../../src/main/util/log-redact', async importOriginal => ({
|
||||
...await importOriginal<any>(),
|
||||
}));
|
||||
|
||||
async function createTool(agentId = 'agent-1') {
|
||||
@@ -57,14 +55,13 @@ describe('web_search override tool', () => {
|
||||
vi.resetModules();
|
||||
h.candidates = [];
|
||||
h.userId = 'user-1';
|
||||
h.sessionId = 'session-1';
|
||||
h.apiBase = 'https://search-account.test/api';
|
||||
h.runBuiltinWebSearch.mockReset();
|
||||
h.runSearchAdapter.mockReset();
|
||||
h.warn.mockReset(); h.error.mockReset();
|
||||
h.runBuiltinWebSearch.mockResolvedValue({ content: 'free results', displayName: 'Brave' });
|
||||
});
|
||||
|
||||
afterEach(() => { vi.restoreAllMocks(); });
|
||||
afterEach(() => { expect(h.error).not.toHaveBeenCalled(); vi.restoreAllMocks(); });
|
||||
|
||||
it('keeps the parallel execution contract and validates query before provider access', async () => {
|
||||
const tool = await createTool();
|
||||
@@ -89,6 +86,256 @@ describe('web_search override tool', () => {
|
||||
expect(h.runSearchAdapter).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([undefined, 'tavily', 'serper', 'brave-search', 'baidu-ai-search', 'deepseek', 'metaso', 'orkas-api'] as const)(
|
||||
'counts each admitted web_search call independently of its provider (%s)', async provider => {
|
||||
h.candidates = provider ? [{ provider, apiKey: 'synthetic' }] : [];
|
||||
h.runSearchAdapter.mockResolvedValue({ results: [{ title: 'Evidence', url: 'https://example.test/source', snippet: 'Kept result' }] });
|
||||
const { createTavilySearchTurn, withTavilySearchTurn } = await import('../../../../src/main/util/tavily-search-turn');
|
||||
const turn = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
await withTavilySearchTurn(turn, async () => {
|
||||
const tool = await createTool();
|
||||
const observed: number[] = [];
|
||||
for (let n = 1; n <= 16; n++) {
|
||||
const result = await tool.execute({ query: `bounded evidence ${n}` }, {} as any);
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.content).toContain(provider ? 'Kept result' : 'free results');
|
||||
if (result.content.includes('This turn:')) {
|
||||
observed.push(n);
|
||||
expect(result.content).toContain(`This turn: ${n} web searches. Prioritize completing the task with existing evidence; search further if necessary.`);
|
||||
}
|
||||
}
|
||||
expect(observed).toEqual([10, 15]);
|
||||
expect(turn.requests).toBe(16);
|
||||
});
|
||||
expect(provider ? h.runSearchAdapter : h.runBuiltinWebSearch).toHaveBeenCalledTimes(16);
|
||||
expect(h.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('counts a failed keyless call but never counts rejected tool input', async () => {
|
||||
const { createTavilySearchTurn, withTavilySearchTurn } = await import('../../../../src/main/util/tavily-search-turn');
|
||||
const turn = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
await withTavilySearchTurn(turn, async () => {
|
||||
const tool = await createTool();
|
||||
for (let n = 0; n < 9; n++) await tool.execute({ query: 'existing evidence' }, {} as any);
|
||||
expect((await tool.execute({ query: ' ' }, {} as any)).isError).toBe(true);
|
||||
expect(turn.requests).toBe(9);
|
||||
h.runBuiltinWebSearch.mockResolvedValue({ content: 'Search failed without a new result', isError: true });
|
||||
const result = await tool.execute({ query: 'last source' }, {} as any);
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content).toContain('Search failed without a new result');
|
||||
expect(result.content).toContain('This turn: 10 web searches.');
|
||||
expect(turn.requests).toBe(10);
|
||||
expect(h.runBuiltinWebSearch).toHaveBeenCalledTimes(10);
|
||||
});
|
||||
});
|
||||
|
||||
it('reminds at 10 searches and every 5 thereafter while continuing to return results', async () => {
|
||||
h.candidates = [{ provider: 'tavily', apiKey: 'synthetic' }];
|
||||
h.runSearchAdapter.mockImplementation(async (_profile, _query, _count) => {
|
||||
return { results: [{ title: 'Evidence', url: 'https://example.test/source', snippet: 'Source text' }] };
|
||||
});
|
||||
const tool = await createTool();
|
||||
const reminders: number[] = [];
|
||||
for (let count = 1; count <= 26; count++) {
|
||||
const result = await tool.execute({ query: `question ${count}` }, { state: {} } as any);
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.content).toContain('Source text');
|
||||
if (result.content.includes('This turn:')) {
|
||||
reminders.push(count);
|
||||
expect(result.content).toContain(`This turn: ${count} web searches. Prioritize completing the task with existing evidence; search further if necessary.`);
|
||||
}
|
||||
}
|
||||
expect(reminders).toEqual([10, 15, 20, 25]);
|
||||
expect(h.runSearchAdapter).toHaveBeenCalledTimes(26);
|
||||
});
|
||||
|
||||
it('keeps the reminder visible when a large search result is retained behind a bounded preview', async () => {
|
||||
h.candidates = [{ provider: 'tavily', apiKey: 'synthetic' }];
|
||||
h.runSearchAdapter.mockImplementation(async (_profile, _query, _count) => {
|
||||
return { results: [{ title: 'Evidence', url: 'https://example.test/source', snippet: 'Source evidence. '.repeat(12_000) }] };
|
||||
});
|
||||
const tool = await createTool();
|
||||
for (let i = 0; i < 9; i++) await tool.execute({ query: 'evidence' }, {} as any);
|
||||
const result = await tool.execute({ query: 'last source' }, {} as any);
|
||||
const { capToolResult } = await import('../../../../src/main/util/tool-result-cap');
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'search-reminder-'));
|
||||
try {
|
||||
const capped = capToolResult('web_search', result, { state: {} } as any, { toolResultsDir: dir, maxInlineTokens: 256 });
|
||||
expect(capped.persistedOutput).toBeTruthy();
|
||||
expect(capped.content).toContain('This turn: 10 web searches.');
|
||||
expect(capped.content).toContain('search further if necessary.');
|
||||
expect(fs.readFileSync(capped.persistedOutput!.path, 'utf8')).toContain('Source evidence.');
|
||||
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
|
||||
it('shares one search count across providers, parallel actors and rebuilt tools', async () => {
|
||||
const { createTavilySearchTurn, withTavilySearchTurn } = await import('../../../../src/main/util/tavily-search-turn');
|
||||
h.runSearchAdapter.mockImplementation(async (profile, _query, _count) => {
|
||||
await Promise.resolve();
|
||||
return { results: [{ title: 'Evidence', url: 'https://example.test/source', snippet: 'Source text' }] };
|
||||
});
|
||||
const scope = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
const all: string[] = [];
|
||||
await withTavilySearchTurn(scope, async () => {
|
||||
h.candidates = [{ provider: 'serper', apiKey: 'synthetic' }];
|
||||
const parent = await createTool('commander');
|
||||
for (let i = 0; i < 12; i++) {
|
||||
all.push((await parent.execute({ query: `other provider ${i}` }, {} as any)).content);
|
||||
}
|
||||
h.candidates = [{ provider: 'tavily', apiKey: 'synthetic' }];
|
||||
const child = await createTool('agent-2');
|
||||
const results = await Promise.all(Array.from({ length: 16 }, (_, index) =>
|
||||
(index % 2 ? parent : child).execute({ query: `evidence ${index}` }, {} as any)));
|
||||
all.push(...results.map(result => result.content));
|
||||
// Rebuilding an actor after compaction or a model change keeps this scope.
|
||||
const rebuilt = await createTool('agent-2');
|
||||
for (let i = 0; i < 5; i++) all.push((await rebuilt.execute({ query: `more evidence ${i}` }, {} as any)).content);
|
||||
});
|
||||
expect(all.filter(content => content.includes('This turn:')).map(content => content.match(/This turn: (\d+)/)?.[1]))
|
||||
.toEqual(['10', '15', '20', '25', '30']);
|
||||
const next = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
await withTavilySearchTurn(next, async () => {
|
||||
expect((await (await createTool()).execute({ query: 'new user request' }, {} as any)).content).not.toContain('This turn:');
|
||||
});
|
||||
});
|
||||
|
||||
it.each([false, true])('counts dispatched failures and preserves the fallback result (fallback fails: %s)', async failedFallback => {
|
||||
h.candidates = [{ provider: 'tavily', apiKey: 'synthetic' }];
|
||||
h.runSearchAdapter.mockImplementation(async (_profile, query, _count) => {
|
||||
if (query === 'failed request') throw new Error('Tavily 500: temporary outage');
|
||||
return { results: [] };
|
||||
});
|
||||
h.runBuiltinWebSearch.mockResolvedValue({ content: 'fallback receipt', displayName: 'Brave', ...(failedFallback ? { isError: true } : {}) });
|
||||
const tool = await createTool();
|
||||
for (let i = 0; i < 9; i++) await tool.execute({ query: 'empty but dispatched' }, {} as any);
|
||||
const result = await tool.execute({ query: 'failed request' }, {} as any);
|
||||
expect(result.content).toContain('This turn: 10 web searches.');
|
||||
expect(result.content).toContain('fallback receipt');
|
||||
expect(result.isError === true).toBe(failedFallback);
|
||||
expect((await tool.execute({ query: 'continued request' }, {} as any)).content).not.toContain('This turn:');
|
||||
expect(h.runSearchAdapter).toHaveBeenCalledTimes(11);
|
||||
});
|
||||
|
||||
it.each(['absent', 'previous turn'])('retains the owning turn when a worker callback has %s async context', async context => {
|
||||
const { createTavilySearchTurn, withTavilySearchTurn } = await import('../../../../src/main/util/tavily-search-turn');
|
||||
h.candidates = [{ provider: 'tavily', apiKey: 'synthetic' }];
|
||||
h.runSearchAdapter.mockImplementation(async (_profile, _query, _count) => {
|
||||
return { results: [{ title: 'Evidence', url: 'https://example.test', snippet: 'Source' }] };
|
||||
});
|
||||
const previous = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
previous.requests = 9;
|
||||
const owning = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
const tool = await withTavilySearchTurn(owning, () => createTool());
|
||||
const run = async () => {
|
||||
for (let i = 1; i <= 10; i++) {
|
||||
const result = await tool.execute({ query: `source ${i}` }, {} as any);
|
||||
expect(result.content.includes('This turn:')).toBe(i === 10);
|
||||
}
|
||||
};
|
||||
if (context === 'previous turn') await withTavilySearchTurn(previous, run);
|
||||
else await run();
|
||||
expect(owning.requests).toBe(10);
|
||||
expect(previous.requests).toBe(9);
|
||||
expect(h.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not increment the bound turn after the active account changes', async () => {
|
||||
const { createTavilySearchTurn, withTavilySearchTurn } = await import('../../../../src/main/util/tavily-search-turn');
|
||||
h.candidates = [{ provider: 'tavily', apiKey: 'synthetic' }];
|
||||
h.runSearchAdapter.mockImplementation(async (_profile, _query, _count) => {
|
||||
return { results: [] };
|
||||
});
|
||||
const first = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
first.requests = 9;
|
||||
const tool = await withTavilySearchTurn(first, () => createTool());
|
||||
h.userId = 'user-2';
|
||||
const second = createTavilySearchTurn('user-2', 'conversation-1');
|
||||
await withTavilySearchTurn(second, async () => {
|
||||
expect((await tool.execute({ query: 'another account' }, {} as any)).content).not.toContain('This turn:');
|
||||
});
|
||||
expect(first.requests).toBe(9);
|
||||
expect(second.requests).toBe(1);
|
||||
expect(h.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('counts cooldown fallback, keyless and changed providers once while rejecting invalid input', async () => {
|
||||
const { createTavilySearchTurn, withTavilySearchTurn } = await import('../../../../src/main/util/tavily-search-turn');
|
||||
h.candidates = [{ id: 'paid', provider: 'tavily', apiKey: 'synthetic' }];
|
||||
h.runSearchAdapter.mockImplementation(async (profile, query, _count) => {
|
||||
if (query === 'account rejected') throw new Error('Tavily 401: rejected');
|
||||
return { results: [{ title: 'Evidence', url: 'https://example.test', snippet: '' }] };
|
||||
});
|
||||
const scope = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
await withTavilySearchTurn(scope, async () => {
|
||||
const tool = await createTool();
|
||||
for (let i = 0; i < 8; i++) await tool.execute({ query: 'source' }, {} as any);
|
||||
expect((await tool.execute({ query: 'account rejected' }, {} as any)).content).not.toContain('This turn:');
|
||||
expect(scope.requests).toBe(9);
|
||||
expect((await tool.execute({ query: ' ' }, {} as any)).isError).toBe(true);
|
||||
expect(scope.requests).toBe(9);
|
||||
expect((await tool.execute({ query: 'cooldown skipped' }, {} as any)).content).toContain('This turn: 10 web searches.');
|
||||
h.candidates = [];
|
||||
expect((await tool.execute({ query: 'free source' }, {} as any)).content).not.toContain('This turn:');
|
||||
h.candidates = [{ provider: 'serper', apiKey: 'synthetic' }];
|
||||
expect((await tool.execute({ query: 'other provider' }, {} as any)).content).not.toContain('This turn:');
|
||||
expect(scope.requests).toBe(12);
|
||||
h.candidates = [{ id: 'paid', provider: 'tavily', apiKey: 'new credential' }];
|
||||
const result = await tool.execute({ query: 'recovered source' }, {} as any);
|
||||
expect(result.content).not.toContain('This turn:');
|
||||
expect(result.content).toContain('Evidence');
|
||||
expect(scope.requests).toBe(13);
|
||||
});
|
||||
expect(h.runSearchAdapter).toHaveBeenCalledTimes(11);
|
||||
expect(h.runBuiltinWebSearch).toHaveBeenCalledTimes(3);
|
||||
expect(h.warn).toHaveBeenCalledExactlyOnceWith('paid search failed; trying next provider',
|
||||
expect.objectContaining({ provider: 'tavily', account_error: true }));
|
||||
});
|
||||
|
||||
it('preserves the threshold reminder when the dispatched Tavily request fails over to another paid provider', async () => {
|
||||
const { createTavilySearchTurn, withTavilySearchTurn } = await import('../../../../src/main/util/tavily-search-turn');
|
||||
const scope = createTavilySearchTurn('user-1', 'conversation-1');
|
||||
scope.requests = 9;
|
||||
h.candidates = [{ provider: 'tavily', apiKey: 'synthetic' }, { provider: 'serper', apiKey: 'synthetic' }];
|
||||
h.runSearchAdapter.mockImplementation(async (profile, _query, _count) => {
|
||||
if (profile.provider === 'tavily') { throw new Error('Tavily 500: unavailable'); }
|
||||
return { results: [{ title: 'Recovered source', url: 'https://example.test', snippet: '' }] };
|
||||
});
|
||||
const tool = await withTavilySearchTurn(scope, () => createTool());
|
||||
const result = await withTavilySearchTurn(scope, () => tool.execute({ query: 'source' }, {} as any));
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.displayName).toBe('Serper');
|
||||
expect(result.content).toContain('Recovered source');
|
||||
expect(result.content.match(/This turn: 10 web searches\./g)).toHaveLength(1);
|
||||
expect(scope.requests).toBe(10);
|
||||
expect(h.runBuiltinWebSearch).not.toHaveBeenCalled();
|
||||
expect(h.warn).toHaveBeenCalledExactlyOnceWith('paid search failed; trying next provider',
|
||||
expect.objectContaining({ provider: 'tavily', account_error: false }));
|
||||
});
|
||||
|
||||
it('attaches each threshold to its dispatched request when parallel responses finish in reverse order', async () => {
|
||||
h.candidates = [{ provider: 'tavily', apiKey: 'synthetic' }];
|
||||
const pending: Array<() => void> = [];
|
||||
h.runSearchAdapter.mockImplementation((_profile, query, _count) => {
|
||||
return new Promise(resolve => pending.push(() => resolve({
|
||||
results: [{ title: query, url: 'https://example.test', snippet: '' }],
|
||||
})));
|
||||
});
|
||||
const tool = await createTool();
|
||||
const completed: number[] = [];
|
||||
const work = Array.from({ length: 16 }, (_, index) => tool.execute({ query: `request ${index + 1}` }, {} as any)
|
||||
.then(result => { completed.push(index + 1); return result; }));
|
||||
expect(pending).toHaveLength(16);
|
||||
pending.reverse().forEach(resolve => resolve());
|
||||
const results = await Promise.all(work);
|
||||
expect(completed).toEqual(Array.from({ length: 16 }, (_, index) => 16 - index));
|
||||
expect(results.flatMap((result, index) => result.content.includes('This turn:') ? [index + 1] : [])).toEqual([10, 15]);
|
||||
expect(results[9].content).toContain('This turn: 10 web searches.');
|
||||
expect(results[14].content).toContain('This turn: 15 web searches.');
|
||||
expect(h.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
it('keeps search capability generic instead of branching on an Agent ID', async () => {
|
||||
const tool = await createTool('173d4235a431');
|
||||
const results = await Promise.all([
|
||||
@@ -312,13 +559,19 @@ describe('web_search override tool', () => {
|
||||
expect(h.runSearchAdapter).toHaveBeenCalledTimes(130);
|
||||
});
|
||||
|
||||
it.each([['deepseek',128], ['orkas-api',128], ['tavily',400]] as const)('advertises and enforces the first provider Unicode bound (%s)', async(provider,limit)=>{
|
||||
h.candidates=provider?[{provider,apiKey:'fixture'}]:[];
|
||||
it.each([['deepseek',128], ['orkas-api',128], ['serper',128], ['tavily',400]] as const)('advertises and enforces the first provider Unicode bound (%s)', async(provider,limit)=>{
|
||||
h.candidates=[{provider,apiKey:'fixture'}];
|
||||
h.runSearchAdapter.mockResolvedValue({results:[{title:'Source',url:'https://example.test',snippet:'Evidence'}]});
|
||||
const tool=await createTool();
|
||||
expect((tool.inputSchema as any).properties.query.maxLength).toBe(limit);
|
||||
const result=await tool.execute({query:'🌏'.repeat(limit+1)},{} as any);
|
||||
expect(result.isError).toBe(true);expect(result.content).toContain(String(limit));
|
||||
expect(h.runSearchAdapter).not.toHaveBeenCalled();expect(h.runBuiltinWebSearch).not.toHaveBeenCalled();
|
||||
for (const length of [limit-1,limit]) {
|
||||
const accepted=await tool.execute({query:'🌏'.repeat(length)},{} as any);
|
||||
expect(accepted.isError).not.toBe(true);
|
||||
expect(h.runSearchAdapter.mock.lastCall?.[1]).toBe('🌏'.repeat(length));
|
||||
}
|
||||
});
|
||||
it('lets a changed first provider tighten but never widen an existing run schema',async()=>{
|
||||
h.candidates=[{provider:'tavily',apiKey:'fixture'}]; const wide=await createTool();
|
||||
@@ -327,6 +580,8 @@ describe('web_search override tool', () => {
|
||||
const narrow=await createTool();h.candidates=[{provider:'tavily',apiKey:'fixture'}];
|
||||
expect((await narrow.execute({query:'🌏'.repeat(129)},{} as any)).isError).toBe(true);
|
||||
expect(h.runSearchAdapter).not.toHaveBeenCalled();expect(h.runBuiltinWebSearch).not.toHaveBeenCalled();
|
||||
const recreated=await createTool();
|
||||
expect((recreated.inputSchema as any).properties.query.maxLength).toBe(400);
|
||||
});
|
||||
it.each(['deepseek','orkas-api'])('stops an incompatible fallback without dispatching it (%s)',async backup=>{
|
||||
h.candidates=[{provider:'tavily',apiKey:'fixture'},...(backup?[{provider:backup,apiKey:'fixture'}]:[])];
|
||||
@@ -336,14 +591,16 @@ describe('web_search override tool', () => {
|
||||
expect(h.runSearchAdapter).toHaveBeenCalledTimes(1);expect(h.runBuiltinWebSearch).not.toHaveBeenCalled();
|
||||
expect(h.runSearchAdapter.mock.calls[0][1]).toBe('🌏'.repeat(200));
|
||||
});
|
||||
it('keeps the existing tool guidance and does not append paid-search reminders',async()=>{
|
||||
it('keeps the existing tool guidance and adds only the approved threshold reminder',async()=>{
|
||||
h.candidates=[{provider:'tavily',apiKey:'fixture'}];
|
||||
h.runSearchAdapter.mockResolvedValue({results:[{title:'Source',url:'https://example.org',snippet:'Evidence'}]});
|
||||
const tool=await createTool();
|
||||
expect(tool.description).toBe('Search the web for information. Returns a list of search results with titles, URLs, and snippets. Use this when you need to find current information, news, documentation, or any web content. After searching, use web_fetch to read the full content of relevant result URLs.');
|
||||
for(let i=0;i<15;i++){
|
||||
const result=await tool.execute({query:'public query'},{} as any);
|
||||
expect(result.content).toContain('Evidence');expect(result.content).not.toMatch(/This turn:|paid web searches|Prioritize completing/);
|
||||
expect(result.content).toContain('Evidence');
|
||||
expect(result.content.includes('This turn:')).toBe(i === 9 || i === 14);
|
||||
expect(result.content).not.toContain('paid web searches');
|
||||
}
|
||||
expect(h.runSearchAdapter).toHaveBeenCalledTimes(15);
|
||||
});
|
||||
@@ -363,4 +620,13 @@ describe('web_search override tool', () => {
|
||||
expect(h.runSearchAdapter).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(['required', 'invalid_value'] as const)('returns the established structured query %s error before dispatch', async reason => {
|
||||
h.candidates = [{provider: 'tavily', apiKey: 'fixture'}];
|
||||
const result = await (await createTool()).execute({query: reason === 'required' ? ' ' : '🌏'.repeat(401)}, {} as any);
|
||||
expect(result.isError).toBe(true);
|
||||
expect(JSON.parse(result.content)).toMatchObject({code: 'E_BAD_INPUT', issues: [{field: 'query', reason}]});
|
||||
expect(h.runSearchAdapter).not.toHaveBeenCalled();
|
||||
expect(h.runBuiltinWebSearch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { validateAgentDir } from '../../../src/main/quality';
|
||||
|
||||
const repoRoot = path.resolve(__dirname, '../../..');
|
||||
const agentDir = path.join(repoRoot, 'resources/builtin/marketplace/agents/78900d8758bc');
|
||||
const readAgent = () => JSON.parse(fs.readFileSync(path.join(agentDir, 'agent.json'), 'utf8'));
|
||||
|
||||
describe('DeepResearcher domain consolidation', () => {
|
||||
it('advertises evidence synthesis and social analysis rather than ordinary search', () => {
|
||||
const agent = readAgent();
|
||||
expect(agent.description_zh).toMatch(/多源取证.*样本分析.*综合判断/);
|
||||
expect(agent.description_zh).toMatch(/社媒.*口碑.*活动分析/);
|
||||
expect(agent.description_zh).toMatch(/不用于普通事实查询或找链接/);
|
||||
expect(agent.description_en).toMatch(/multi-source evidence.*sample analysis.*synthesis/i);
|
||||
expect(agent.description_en).toMatch(/social reputation.*campaign analysis/i);
|
||||
expect(agent.description_en).toMatch(/not for ordinary fact lookups or link finding/i);
|
||||
expect(agent.workflow).toMatch(/not ordinary fact lookup or link finding/i);
|
||||
});
|
||||
|
||||
it('owns bounded social work without forcing a deep-report lifecycle or fresh public collection', () => {
|
||||
const agent = readAgent();
|
||||
expect(agent.workflow).toMatch(/social-data` for reputation or supplied campaign analysis/i);
|
||||
expect(agent.workflow).toMatch(/social work.*freezes platforms, keywords, period and sample plan/i);
|
||||
expect(agent.workflow).toMatch(/never expand after failure\/zero results/i);
|
||||
expect(agent.workflow).toMatch(/brand context only if decision-changing/i);
|
||||
expect(agent.workflow).toMatch(/do not fetch for sufficient supplied data/i);
|
||||
expect(agent.workflow).toMatch(/social work returns planned\/completed scope.*themes or metrics.*evidence.*next experiments/i);
|
||||
expect(agent.standards.join('\n')).toMatch(/social findings retain scope, denominators and confidence/i);
|
||||
expect(agent.inputs.find((field: any) => field.id === 'task').placeholder).toMatch(/social.*campaign/i);
|
||||
});
|
||||
|
||||
it('advertises both focused Brand DNA and existing complex research without a new launch requirement', () => {
|
||||
const agent = readAgent();
|
||||
expect(agent.agent_id).toBe('78900d8758bc');
|
||||
expect(agent.name).toBe('DeepResearcher');
|
||||
expect(agent.interactive).toBe(true);
|
||||
expect(agent.inputs.map((field: any) => field.id)).toEqual(['task', 'materials']);
|
||||
expect(agent.inputs.filter((field: any) => field.required).map((field: any) => field.id)).toEqual(['task']);
|
||||
for (const term of ['Brand DNA', '定位', '受众', '竞品', '语气', '文献', '核验']) expect(agent.description_zh).toContain(term);
|
||||
for (const term of ['Brand DNA', 'positioning', 'audience', 'competitors', 'voice', 'literature', 'verif']) expect(agent.description_en).toContain(term);
|
||||
expect(agent.description_en).toMatch(/not.*copywriting.*publishing/i);
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(repoRoot, 'resources/builtin/_manifest.json'), 'utf8'));
|
||||
expect(manifest.inventory.marketplace_agents.find((row: any) => row.id === agent.agent_id)?.version).toBe(agent.version);
|
||||
expect(agent.version).toMatch(/^\d+\.\d+\.\d+$/);
|
||||
expect(Date.parse(agent.updated_at)).not.toBeNaN();
|
||||
const validated = validateAgentDir(agentDir);
|
||||
expect(validated.ok, JSON.stringify(validated.violations)).toBe(true);
|
||||
});
|
||||
|
||||
it('uses existing domain capabilities while preserving narrow tools and the deep-research evidence contract', () => {
|
||||
const agent = readAgent();
|
||||
expect(agent.skill_list).toEqual(['ee99fbb42964', '9be6fda271a5', 'e7f5c0e6f1be', '6743aa0797a2']);
|
||||
expect(agent.tool_list).toEqual(['workspace.read', 'workspace.write.output', 'workspace.execute.command', 'web']);
|
||||
const workflow = agent.workflow;
|
||||
expect(workflow).toMatch(/brand-research` for focused.*Brand DNA/);
|
||||
expect(workflow).toMatch(/broader or complex.*deep-research` as the governing Skill/);
|
||||
expect(workflow).toMatch(/freeze sources and competitors/i);
|
||||
expect(workflow).toMatch(/not widen.*optional.*fields/);
|
||||
expect(workflow).toMatch(/social-data` for reputation or supplied campaign analysis/);
|
||||
expect(workflow).toContain('`material-organizer`');
|
||||
expect(workflow).toMatch(/resume only unfinished subquestions.*honor recorded limits/);
|
||||
expect(workflow).toMatch(/exact quotes.*contradictions.*failed-source gaps/);
|
||||
expect(workflow).toMatch(/verify each factual part and its conditions/i);
|
||||
expect(workflow).toMatch(/canonical citation-checked report.*publish(?:es)? once/);
|
||||
expect(workflow.length).toBeLessThanOrEqual(1800);
|
||||
expect(workflow).not.toMatch(/run-skill|scripts\//);
|
||||
});
|
||||
|
||||
it('keeps focused briefs in chat by default without weakening deep-investigation ledgers or report delivery', async () => {
|
||||
const agent = readAgent();
|
||||
expect(agent.workflow).toMatch(/brand briefs.*brand-research`'s chat\/file output contract/i);
|
||||
const brand = fs.readFileSync(path.resolve(agentDir, '../../skills/6743aa0797a2/SKILL.md'), 'utf8');
|
||||
expect(brand).toMatch(/By default, return the Brand DNA in the conversation/);
|
||||
expect(brand).toMatch(/Save.*only when the user asks for a file or confirms saving/);
|
||||
const standards = agent.standards.join('\n');
|
||||
expect(standards).toMatch(/deep-research paths.*ledgers/i);
|
||||
expect(standards).toMatch(/deep-research handoff.*RESEARCH-<topic>\.md/i);
|
||||
expect(standards).toMatch(/brand briefs?.*(?:distinguishes|separate|separating) company statements, third-party evidence and interpretation/i);
|
||||
expect(standards).toMatch(/caveats.*(?:gaps|missing fields) and next uses/i);
|
||||
expect(standards).toMatch(/unresolved choice-changing gaps.*partial, never complete/i);
|
||||
const { normalizeAgent } = await import('../../../src/main/features/agents');
|
||||
const { _buildAgentInGroupSystemPromptForTest } = await import('../../../src/main/features/group_chat/bus');
|
||||
const normalized = normalizeAgent(agent, 'builtin')!;
|
||||
const prompt = await _buildAgentInGroupSystemPromptForTest(normalized, '/test/brand-research', 'en');
|
||||
expect(prompt).toContain(agent.workflow);
|
||||
for (const standard of agent.standards) expect(prompt.split(standard)).toHaveLength(2);
|
||||
expect(prompt.split('<handback reason="capability_boundary" />')).toHaveLength(2);
|
||||
expect([agent.workflow, ...agent.standards].join('\n')).not.toMatch(/<handback|@commander|BrandResearcher/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
createTavilySearchTurn, currentTavilySearchTurn, recordTavilySearchRequest,
|
||||
withTavilySearchTurn,
|
||||
} from '../../../src/main/util/tavily-search-turn';
|
||||
|
||||
describe('user-turn Tavily search reminders', () => {
|
||||
it('shares counts across concurrent descendants and preserves them across actor rebuilds', async () => {
|
||||
const turn = createTavilySearchTurn('user-a', 'conversation-a');
|
||||
const reminders: number[] = [];
|
||||
await withTavilySearchTurn(turn, async () => {
|
||||
await Promise.all(Array.from({ length: 16 }, async () => {
|
||||
await Promise.resolve();
|
||||
expect(currentTavilySearchTurn('user-a', 'conversation-a')).toBe(turn);
|
||||
const reminder = recordTavilySearchRequest(turn);
|
||||
if (reminder !== undefined) reminders.push(reminder);
|
||||
}));
|
||||
});
|
||||
await withTavilySearchTurn(turn, async () => {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const reminder = recordTavilySearchRequest(turn);
|
||||
if (reminder !== undefined) reminders.push(reminder);
|
||||
}
|
||||
});
|
||||
expect(reminders).toEqual([10, 15, 20, 25]);
|
||||
expect(currentTavilySearchTurn('user-a', 'conversation-a')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('isolates a later user message and foreign owners while an earlier turn is still running', async () => {
|
||||
const old = createTavilySearchTurn('user-a', 'conversation-a');
|
||||
const next = createTavilySearchTurn('user-a', 'conversation-a');
|
||||
await withTavilySearchTurn(old, async () => {
|
||||
for (let i = 0; i < 9; i++) expect(recordTavilySearchRequest(old)).toBeUndefined();
|
||||
expect(currentTavilySearchTurn('user-b', 'conversation-a')).toBeUndefined();
|
||||
expect(currentTavilySearchTurn('user-a', 'conversation-b')).toBeUndefined();
|
||||
await withTavilySearchTurn(next, async () => {
|
||||
expect(recordTavilySearchRequest(next)).toBeUndefined();
|
||||
await Promise.resolve();
|
||||
expect(currentTavilySearchTurn('user-a', 'conversation-a')).toBe(next);
|
||||
});
|
||||
expect(currentTavilySearchTurn('user-a', 'conversation-a')).toBe(old);
|
||||
expect(recordTavilySearchRequest(old)).toBe(10);
|
||||
});
|
||||
for (let i = 0; i < 8; i++) expect(recordTavilySearchRequest(next)).toBeUndefined();
|
||||
expect(recordTavilySearchRequest(next)).toBe(10);
|
||||
});
|
||||
});
|
||||
@@ -630,6 +630,38 @@ it('hydrates only visible chat rows and requests newly visible rows after scroll
|
||||
} finally { vi.useRealTimers(); vi.restoreAllMocks(); }
|
||||
});
|
||||
|
||||
it.each([0, 40])('keeps the reading position at scrollTop=%i when summaries above the selection grow', async initialTop => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const { body, input, context, streams } = progressiveHarness(domHarness());
|
||||
vi.spyOn(MiniElement.prototype, 'getBoundingClientRect').mockImplementation(function(this: MiniElement) {
|
||||
if (this.id === 'search-body') return { top: 0, bottom: 200, left: 0, right: 0, width: 0, height: 200 };
|
||||
const index = Number(this.dataset.idx);
|
||||
const growth = index > 0 && body.querySelector('.search-result-snippet') ? 120 : 0;
|
||||
const top = index * 80 + growth - body.scrollTop;
|
||||
return { top, bottom: top + 80, left: 0, right: 0, width: 0, height: 80 };
|
||||
});
|
||||
input.value = 'needle';
|
||||
const rows = [0, 1].map(index => ({ kind: 'chat', cid: `c${index}`, msg_index: 0, conv_title: `Result ${index}` }));
|
||||
const search = context._runSearchNow(input.value);
|
||||
streams[0].finish({ results: rows, pending_kinds: [], failed_kinds: [] });
|
||||
await search;
|
||||
vm.runInContext('_searchActiveIdx = 1', context);
|
||||
context._renderSearchResults(input.value);
|
||||
body.scrollTop = initialTop;
|
||||
const before = body.querySelector('.search-result.active').getBoundingClientRect().top;
|
||||
const summaries = context._loadVisibleChatSnippets();
|
||||
streams[1].finish({
|
||||
results: rows.map((row, index) => ({ ...row, snippet_loaded: true, snippet: index === 0 ? 'needle summary' : '' })),
|
||||
pending_kinds: [], failed_kinds: [],
|
||||
});
|
||||
await summaries;
|
||||
expect(body.querySelector('.search-result-snippet').textContent).toBe('needle summary');
|
||||
if (initialTop === 0) expect(body.scrollTop).toBe(0);
|
||||
else expect(body.querySelector('.search-result.active').getBoundingClientRect().top).toBe(before);
|
||||
} finally { vi.useRealTimers(); vi.restoreAllMocks(); }
|
||||
});
|
||||
|
||||
it('paints completed modules while chats are held and retains selection when chat and Library results arrive', async () => {
|
||||
const { body, context, streams } = progressiveHarness();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user