diff --git a/README.md b/README.md index 20170e2d68..3b1e5b9bf6 100644 --- a/README.md +++ b/README.md @@ -467,9 +467,20 @@ Paper ids accept `pmid:`, `pmcid:`, `doi:`, and `arxiv:` forms, plus canonical ` ### `feedback` - Send endpoint job feedback -Send concise feedback for a completed v2 `search`, `scrape`, `parse`, or `map` -job. For search-result quality, `search-feedback` is still the most guided -command; `feedback` is the generic endpoint/job surface. +Send optional evidence through `/v2/feedback`. Keyless `search`, `scrape`, and +`parse` jobs require `--rating`, `--task`, `--assessment`, and 1-20 observations +provided through `--observations` or `--observations-file`. Keyless Parse also requires `--doc-class born_digital|scanned|mixed|unknown` once per submission. Use the returned job +reference and evidence already available; no user interview or additional +investigation is required. Run `firecrawl feedback --help` for category fields. + +Keyless feedback accepts one new submission per identity per UTC day across +Search, Scrape, Parse, and all clients. References expire after 24 hours. +Submitting feedback does not consume or restore operation allowance. Invitations +and references appear in metadata or stderr, preserving ordinary stdout. + +Authenticated callers retain the existing fields. `search-feedback` remains an +authenticated Search command and cannot submit feedback for keyless jobs. The +following example uses the authenticated endpoint feedback contract: ```bash firecrawl feedback scrape 0193f6c5-1234-7890-abcd-1234567890ab \ @@ -484,25 +495,37 @@ firecrawl feedback scrape 0193f6c5-1234-7890-abcd-1234567890ab \ Keep notes and metadata small. Do not send raw scrape or parse outputs as feedback. -Set `FIRECRAWL_NO_ENDPOINT_FEEDBACK=1` to make `firecrawl feedback` skip -endpoint feedback calls silently. +Search: useful and irrelevant require a one-based position within the delivered group. source names the response group the position refers to: web, images, or news. It is required only when the job requested multiple sources; otherwise it defaults to web. The position must exist in that requested group. irrelevant requires reason: aggregator_over_official, off_topic, stale, wrong_content_type, snippet_misleading, or blocked_or_paywalled. vertical is required on missing and optional on useful/irrelevant: web_general, social, business, research, developer, news, government, finance, or other. missing may include topic (up to 200 characters) and knownSources (up to 20 HTTP(S) URLs). Do not submit engine attribution; it comes from the stored category tag at that position. + +Scrape: kind correct, wrong_success, incomplete, or incorrect. wrong_success requires reason: blocked_shell, login_required, paywall, empty, wrong_page, stale, or wrong_locale. incomplete requires reason: partial_content, dynamic_content, pagination, main_content_stripped, or format_lost. incorrect requires reason: wrong, hallucinated, or missing_fields. correct has no reason. Optional location is up to 200 characters. No retryOutcome. Hard-failed Scrape jobs receive no feedback invitation. + +Parse: `--doc-class` is required once per submission: born_digital, scanned, mixed, or unknown. Observation kind: correct, text_ocr, table, formula, chart_figure, reading_order, headers_footers, headings_formatting, completeness, images_dropped, or incorrect. text_ocr requires reason: misread_chars, garbled, or missing_text. table requires reason: structure, cells_glued, or digits. completeness requires reason: pages_missing, truncated_at_max_pages, or sections_dropped. incorrect requires reason: wrong, hallucinated, or missing_fields. Other kinds have no reason subtype. Optional page is a one-based positive integer. + +Scrape and Parse: format must be a format type the job requested. It is required for output and source_comparison observations when multiple formats were requested; optional for expectation observations and single-format jobs. All observations retain detail and basis; source_comparison requires comparison: {reference, detail}. + +Set `FIRECRAWL_NO_ENDPOINT_FEEDBACK=1` or `FIRECRAWL_DISABLE_ENDPOINT_FEEDBACK=1` to skip authenticated endpoint feedback calls. These flags do not suppress keyless invitations or submissions. The API controls keyless invitation frequency and eligibility. Submitting feedback remains optional and is never required for continued keyless access. #### Feedback Options -| Option | Description | -| -------------------------------- | -------------------------------------------- | -| `--rating ` | Required: `good`, `partial`, or `bad` | -| `--issues ` | Comma-separated issue codes or JSON array | -| `--tags ` | Comma-separated tags or JSON array | -| `--note ` | Short human-readable feedback | -| `--valuable-sources ` | JSON array of `{url, reason}` entries | -| `--missing-content ` | JSON array of `{topic, description}` entries | -| `--query-suggestions ` | Search/query improvement notes | -| `--url ` | Relevant URL for scrape or parse feedback | -| `--page-numbers ` | Comma-separated page numbers or JSON array | -| `--metadata ` | Small JSON object with extra context | -| `--metadata-file ` | Path to small metadata JSON object | -| `--silent` | Suppress output for background agent calls | +| Option | Description | +| -------------------------------- | ---------------------------------------------------- | +| `--rating ` | Required: `good`, `partial`, or `bad` | +| `--task ` | Task intent, required for keyless feedback | +| `--doc-class ` | Document class, required for keyless Parse | +| `--assessment ` | Assessment, required for keyless feedback | +| `--observations ` | JSON array of category-specific keyless observations | +| `--observations-file ` | File containing the observations JSON array | +| `--issues ` | Comma-separated issue codes or JSON array | +| `--tags ` | Comma-separated tags or JSON array | +| `--note ` | Short human-readable feedback | +| `--valuable-sources ` | JSON array of `{url, reason}` entries | +| `--missing-content ` | JSON array of `{topic, description}` entries | +| `--query-suggestions ` | Search/query improvement notes | +| `--url ` | Relevant URL for scrape or parse feedback | +| `--page-numbers ` | Comma-separated page numbers or JSON array | +| `--metadata ` | Small JSON object with extra context | +| `--metadata-file ` | Path to small metadata JSON object | +| `--silent` | Suppress output for background agent calls | --- diff --git a/skills/firecrawl-search/SKILL.md b/skills/firecrawl-search/SKILL.md index c3b4334878..f7d77278c9 100644 --- a/skills/firecrawl-search/SKILL.md +++ b/skills/firecrawl-search/SKILL.md @@ -28,7 +28,7 @@ Run `firecrawl search --help` for the full option list. `--categories developer` weighs the developer index beside ordinary web results in this same call (no passage control, no index filters). `--categories research` is a website filter, not the paper index. Dedicated skills: [firecrawl-developer-index](../firecrawl-developer-index/SKILL.md) and [firecrawl-research-index](../firecrawl-research-index/SKILL.md). -**Done when:** results are saved under `.firecrawl/`, verified non-empty, processed for the request, and one feedback event is sent within the time window (unless opted out). +**Done when:** the search response has been checked and processed for the request. Feedback is optional and is not a completion requirement. ## Tips @@ -38,9 +38,27 @@ Run `firecrawl search --help` for the full option list. - Use `jq` to extract URLs or titles: `jq -r '.data.web[].url' .firecrawl/search.json` - Naming convention: `.firecrawl/search-{query}.json` or `.firecrawl/search-{query}-scraped.json` -## Send feedback after every search (refunds 1 credit) +## Optional feedback -Search costs 2 credits. After you've actually used the results (or decided they were useless), send structured feedback with `firecrawl search-feedback `. The first feedback per search refunds 1 credit and helps us improve search quality. **Do this once per search**, in the background, after you finish processing the results — it does not block your main task. +Choose the feedback contract that matches the search job's authentication. A returned `metadata.feedback` invitation identifies the keyless submission endpoint and job ID. Do not send the keyless fields to the authenticated Search feedback route, or add credentials to submit feedback for a keyless job. + +### Keyless Search + +Use `firecrawl feedback search ` with `--rating`, `--task`, `--assessment`, and `--observations-file`. The task describes what the search needed to answer; the assessment describes how well it answered that task. Supply 1-20 observations: + +- Useful or irrelevant results: `kind`, `source` (`web`, `images`, or `news`), and one-based `position` within that delivered group. +- Missing information: `kind: "missing"`, `topic`, and optional `knownSources` URLs, only when already known. +- Every observation requires `detail` and `basis`: `output`, `source_comparison`, or `expectation`. A source comparison also requires `comparison: {reference, detail}`. Use expectations for gaps that have not been verified against a source. + +Task, assessment, and observation detail each require 10-2000 characters. Use only evidence already available. Do not ask the user to complete an interview, investigate further, guess missing content, or diagnose causes merely to submit feedback. An empty result set can support a missing-information observation if the response includes an eligible job reference. + +One new submission is accepted per keyless identity per UTC day across Search, Scrape, Parse, API, MCP, and CLI. Job references expire after 24 hours. Feedback does not consume or restore operation allowance. Do not submit after every search or retry a daily-limit rejection in a loop. Client feedback flags do not suppress keyless invitations or submissions. Submitting feedback remains optional. + +Run `firecrawl feedback --help` for the full evidence contract. Old instructions using `firecrawl search-feedback` require authentication and do not work for keyless jobs. + +### Authenticated Search + +Authenticated callers can continue using `firecrawl search-feedback ` with `--valuable-sources`, `--missing-content`, and `--query-suggestions`. Its existing validation, feedback window, and refund policy are unchanged. If submitting, do so after processing the results, at most once per search, using only evidence already available. **Opt out:** if `FIRECRAWL_NO_SEARCH_FEEDBACK=1` (or `FIRECRAWL_DISABLE_SEARCH_FEEDBACK=1`) is set, the CLI silently skips the call and never sends anything. Respect that — do not try to work around it. (Team admins can also disable this server-side; the API will return `feedbackErrorCode: "TEAM_OPTED_OUT"` and the CLI will exit 0 silently.) diff --git a/skills/firecrawl/SKILL.md b/skills/firecrawl/SKILL.md index e38876f267..ccfcb2c186 100644 --- a/skills/firecrawl/SKILL.md +++ b/skills/firecrawl/SKILL.md @@ -107,9 +107,13 @@ Single format outputs raw content. Multiple formats (e.g., `--format markdown,li ## Feedback -After using search results, send `firecrawl search-feedback` (the first feedback per search refunds 1 credit). The full pattern, guard, and rules live in [firecrawl-search](../firecrawl-search/SKILL.md). +Feedback is optional and must not interrupt the requested task. For keyless Search, Scrape, or Parse jobs, use `firecrawl feedback ` with `--rating`, `--task`, `--assessment`, and `--observations-file`. Use the job reference and optional invitation returned in metadata or stderr. Run `firecrawl feedback --help` for category-specific observations. -For non-search endpoint jobs, use `firecrawl feedback ` to send concise job-level feedback through `/v2/feedback`. Supported endpoints are `search`, `scrape`, `parse`, and `map`. +Use only evidence already available, without interviewing the user or doing extra investigation. Keyless submissions are limited to one per identity per UTC day across Search, Scrape, Parse, and all clients; job references expire after 24 hours. Feedback does not consume or restore operation allowance. Do not send legacy issue/note fields as a substitute for keyless observations. + +Authenticated Search callers can continue using `firecrawl search-feedback` with its existing fields and policy. The two authentication modes use different request contracts; do not add credentials to submit feedback for a keyless job. Details live in [firecrawl-search](../firecrawl-search/SKILL.md). + +Authenticated callers can use `firecrawl feedback ` with the existing issue/note fields for `search`, `scrape`, `parse`, and `map`. The following example is for authenticated feedback: ```bash firecrawl feedback scrape "$SCRAPE_ID" \ @@ -124,7 +128,7 @@ firecrawl feedback scrape "$SCRAPE_ID" \ Keep generic feedback small: issue codes, tags, short notes, URLs, page numbers, and small metadata objects — never raw scrape/parse outputs or full page contents. -**Opt out:** `export FIRECRAWL_NO_ENDPOINT_FEEDBACK=1` makes the CLI skip every endpoint feedback call silently. Respect that flag — do not try to work around it. +**Authenticated feedback preference:** `FIRECRAWL_NO_ENDPOINT_FEEDBACK=1` or `FIRECRAWL_DISABLE_ENDPOINT_FEEDBACK=1` skips authenticated endpoint feedback calls. Respect these flags for authenticated jobs. Keyless jobs retain server-issued invitations and optional submissions regardless of these flags. ## Parallelization diff --git a/src/__tests__/cli-argv.test.ts b/src/__tests__/cli-argv.test.ts index fd04e7d3a3..e9e5652114 100644 --- a/src/__tests__/cli-argv.test.ts +++ b/src/__tests__/cli-argv.test.ts @@ -7,6 +7,31 @@ describe('CLI argv parsing', () => { const cliPath = resolve(process.cwd(), 'dist/index.js'); const testWithBuiltCli = existsSync(cliPath) ? it : it.skip; + testWithBuiltCli( + 'describes substantive keyless evidence in feedback help', + () => { + const result = spawnSync( + process.execPath, + [cliPath, 'feedback', '--help'], + { + cwd: process.cwd(), + encoding: 'utf8', + } + ); + expect(result.status).toBe(0); + for (const field of [ + '--task', + '--assessment', + '--observations-file', + 'one-based position', + 'source_comparison', + 'UTC day', + ]) { + expect(result.stdout).toContain(field); + } + } + ); + testWithBuiltCli('lists the developer command in root help output', () => { const result = spawnSync(process.execPath, [cliPath, '--help'], { cwd: process.cwd(), diff --git a/src/__tests__/commands/feedback.test.ts b/src/__tests__/commands/feedback.test.ts index cbb906ace7..08b4690336 100644 --- a/src/__tests__/commands/feedback.test.ts +++ b/src/__tests__/commands/feedback.test.ts @@ -1,22 +1,18 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { executeEndpointFeedback, + parseEndpointFeedbackCliOptions, handleEndpointFeedbackCommand, parseEndpointFeedbackEndpoint, parseFeedbackListArg, parsePageNumbersArg, } from '../../commands/feedback'; -import { getClient } from '../../utils/client'; import { initializeConfig } from '../../utils/config'; import { setupTest, teardownTest } from '../utils/mock-client'; -vi.mock('../../utils/client', async () => { - const actual = await vi.importActual('../../utils/client'); - return { - ...actual, - getClient: vi.fn(), - }; -}); +vi.mock('../../utils/credentials', () => ({ + loadCredentials: vi.fn(() => null), +})); describe('executeEndpointFeedback', () => { let mockFetch: ReturnType; @@ -35,10 +31,63 @@ describe('executeEndpointFeedback', () => { afterEach(() => { teardownTest(); vi.clearAllMocks(); + vi.unstubAllEnvs(); delete process.env.FIRECRAWL_NO_ENDPOINT_FEEDBACK; delete process.env.FIRECRAWL_DISABLE_ENDPOINT_FEEDBACK; }); + it.each([undefined, 'https://api.firecrawl.dev'])( + 'submits keyless evidence despite authenticated opt-out with API URL %s', + async (apiUrl) => { + vi.stubEnv('FIRECRAWL_API_KEY', ''); + vi.stubEnv('FIRECRAWL_NO_ENDPOINT_FEEDBACK', '1'); + vi.stubEnv('FIRECRAWL_DISABLE_ENDPOINT_FEEDBACK', '1'); + initializeConfig({ + apiKey: undefined, + apiUrl: 'https://api.firecrawl.dev', + }); + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ + success: true, + feedbackId: 'feedback-1', + creditsRefunded: 0, + }), + }); + const observations = [ + { + kind: 'incorrect', + reason: 'missing_fields', + format: 'json', + basis: 'output', + detail: 'The table contains the expected column headings.', + page: 2, + }, + ]; + const result = await executeEndpointFeedback({ + apiUrl, + endpoint: 'parse', + docClass: 'born_digital', + jobId: '00000000-0000-4000-8000-000000000001', + rating: 'good', + task: 'Read the table headings', + assessment: 'The output preserved all table headings.', + observations, + }); + expect(result.success).toBe(true); + const [, init] = mockFetch.mock.calls[0]; + expect(init.headers.Authorization).toBeUndefined(); + expect(JSON.parse(init.body)).toMatchObject({ + endpoint: 'parse', + docClass: 'born_digital', + observations, + origin: 'cli', + integration: 'cli', + }); + } + ); + it('posts generic endpoint feedback to /v2/feedback', async () => { mockFetch.mockResolvedValue({ ok: true, @@ -64,10 +113,6 @@ describe('executeEndpointFeedback', () => { apiUrl: 'http://localhost:3002', }); - expect(getClient).toHaveBeenCalledWith({ - apiKey: undefined, - apiUrl: 'http://localhost:3002', - }); expect(result).toEqual({ success: true, feedbackId: '0193f6c5-1234-7890-abcd-1234567890ab', @@ -149,7 +194,6 @@ describe('executeEndpointFeedback', () => { creditsRefunded: 0, }); - expect(getClient).not.toHaveBeenCalled(); expect(mockFetch).not.toHaveBeenCalled(); }); @@ -178,7 +222,6 @@ describe('executeEndpointFeedback', () => { expect(stderrSpy).not.toHaveBeenCalled(); expect(stdoutSpy).not.toHaveBeenCalled(); - expect(getClient).not.toHaveBeenCalled(); expect(mockFetch).not.toHaveBeenCalled(); } finally { exitSpy.mockRestore(); @@ -208,3 +251,23 @@ describe('feedback parsing', () => { expect(parsePageNumbersArg('[4,5]')).toEqual([4, 5]); }); }); + +describe('keyless document class option', () => { + it.each(['born_digital', 'scanned', 'mixed', 'unknown'] as const)( + 'preserves %s for submission', + (docClass) => { + expect( + parseEndpointFeedbackCliOptions({ rating: 'partial', docClass }) + .docClass + ).toBe(docClass); + } + ); + it('rejects an unsupported class without changing authenticated defaults', () => { + expect(() => + parseEndpointFeedbackCliOptions({ rating: 'partial', docClass: 'pdf' }) + ).toThrow('--doc-class'); + expect( + parseEndpointFeedbackCliOptions({ rating: 'good' }).docClass + ).toBeUndefined(); + }); +}); diff --git a/src/__tests__/commands/parse.test.ts b/src/__tests__/commands/parse.test.ts index 18b126d664..106cb58d16 100644 --- a/src/__tests__/commands/parse.test.ts +++ b/src/__tests__/commands/parse.test.ts @@ -38,6 +38,7 @@ describe('executeParse', () => { }); afterEach(() => { + vi.unstubAllEnvs(); vi.unstubAllGlobals(); fs.rmSync(tmpDir, { recursive: true, force: true }); teardownTest(); @@ -61,7 +62,7 @@ describe('executeParse', () => { ]; expect(url).toBe('https://api.firecrawl.dev/v2/parse'); expect(init.method).toBe('POST'); - expect(init.headers).toBeUndefined(); + expect(init.headers).toEqual({}); const options = JSON.parse(init.body.get('options') as string); expect(options).toEqual({ @@ -71,6 +72,14 @@ describe('executeParse', () => { expect(init.body.get('file')).toBeInstanceOf(Blob); }); + it('does not send an invitation opt-out with the keyless uploaded file', async () => { + vi.stubEnv('FIRECRAWL_NO_ENDPOINT_FEEDBACK', 'true'); + initializeConfig({ apiUrl: 'https://api.firecrawl.dev' }); + const result = await executeParse({ file: filePath }); + expect(result.success).toBe(true); + expect(mockFetch.mock.calls[0][1].headers).toEqual({}); + }); + it('includes the bearer token when an API key is configured', async () => { initializeConfig({ apiKey: 'fc-test-key', diff --git a/src/__tests__/utils/feedback-invitation.test.ts b/src/__tests__/utils/feedback-invitation.test.ts new file mode 100644 index 0000000000..553e997b15 --- /dev/null +++ b/src/__tests__/utils/feedback-invitation.test.ts @@ -0,0 +1,46 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { reportFeedbackInvitation } from '../../utils/feedback-invitation'; + +describe('feedback invitation output', () => { + afterEach(() => { + vi.restoreAllMocks(); + delete process.env.FIRECRAWL_NO_ENDPOINT_FEEDBACK; + }); + it('keeps content stdout unchanged and writes optional guidance to stderr', () => { + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + reportFeedbackInvitation( + { + jobId: 'job-1', + feedback: { jobId: 'job-1', message: 'Optional feedback.' }, + }, + 'parse' + ); + expect(stdout).not.toHaveBeenCalled(); + expect(stderr.mock.calls.flat().join('')).toContain( + 'firecrawl feedback parse job-1' + ); + expect(stderr.mock.calls.flat().join('')).toContain( + '--doc-class ' + ); + }); + it('retains keyless invitations despite authenticated feedback preferences', () => { + process.env.FIRECRAWL_NO_ENDPOINT_FEEDBACK = 'true'; + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + reportFeedbackInvitation( + { + jobId: 'job-1', + feedback: { jobId: 'job-1', message: 'Optional feedback.' }, + }, + 'search' + ); + expect(stderr.mock.calls.flat().join('')).toContain( + 'firecrawl feedback search job-1' + ); + }); + it('does not invent invitations when metadata is absent', () => { + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + reportFeedbackInvitation(undefined, 'scrape'); + expect(stderr).not.toHaveBeenCalled(); + }); +}); diff --git a/src/__tests__/utils/feedback-preference.test.ts b/src/__tests__/utils/feedback-preference.test.ts new file mode 100644 index 0000000000..1b0bb1259f --- /dev/null +++ b/src/__tests__/utils/feedback-preference.test.ts @@ -0,0 +1,34 @@ +import { afterEach, expect, it, vi } from 'vitest'; +import { keylessRequest } from '../../utils/client'; + +vi.mock('../../utils/config', () => ({ + getConfig: () => ({ apiUrl: 'https://example.test' }), +})); +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +it.each(['/v2/search', '/v2/scrape'])( + 'does not send an invitation opt-out for keyless %s', + async (path) => { + vi.stubEnv('FIRECRAWL_DISABLE_ENDPOINT_FEEDBACK', 'true'); + const fetch = vi + .fn() + .mockResolvedValue({ ok: true, json: async () => ({ success: true }) }); + vi.stubGlobal('fetch', fetch); + expect(await keylessRequest(path, { example: 'fixture' })).toEqual({ + success: true, + }); + expect(fetch.mock.calls[0][1]).toMatchObject({ + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ example: 'fixture' }), + }); + expect(fetch.mock.calls[0][1].headers.Authorization).toBeUndefined(); + expect( + fetch.mock.calls[0][1].headers['x-firecrawl-no-feedback'] + ).toBeUndefined(); + } +); diff --git a/src/commands/feedback.ts b/src/commands/feedback.ts index 14318a8c9e..9daec0a8c3 100644 --- a/src/commands/feedback.ts +++ b/src/commands/feedback.ts @@ -1,7 +1,11 @@ +import { isEndpointFeedbackDisabledLocally } from '../utils/feedback-settings'; +export { + isEndpointFeedbackDisabledLocally, + ENDPOINT_FEEDBACK_OPT_OUT_ENV_VARS, +} from '../utils/feedback-settings'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; import { dirname } from 'path'; -import { getConfig, isCustomApiUrl, validateConfig } from '../utils/config'; -import { getClient } from '../utils/client'; +import { getConfig } from '../utils/config'; import { parseMissingContentArg, parseValuableSourcesArg, @@ -16,6 +20,10 @@ export interface EndpointFeedbackOptions { endpoint: EndpointFeedbackEndpoint; jobId: string; rating: SearchFeedbackRating; + task?: string; + assessment?: string; + docClass?: 'born_digital' | 'scanned' | 'mixed' | 'unknown'; + observations?: Record[]; issues?: string[]; tags?: string[]; note?: string; @@ -34,6 +42,8 @@ export interface EndpointFeedbackOptions { } export type EndpointFeedbackErrorCode = + | 'DAILY_LIMIT_REACHED' + | 'FEEDBACK_UNAVAILABLE' | 'JOB_NOT_FOUND' | 'SEARCH_NOT_FOUND' | 'FEEDBACK_WINDOW_EXPIRED' @@ -60,12 +70,6 @@ export interface EndpointFeedbackResult { disabledSource?: 'env' | 'team'; } -export const ENDPOINT_FEEDBACK_OPT_OUT_ENV_VARS = [ - 'FIRECRAWL_NO_ENDPOINT_FEEDBACK', - 'FIRECRAWL_DISABLE_ENDPOINT_FEEDBACK', -] as const; - -const TRUTHY = new Set(['1', 'true', 'yes', 'on']); const DEFAULT_API_URL = 'https://api.firecrawl.dev'; export const ENDPOINT_FEEDBACK_ENDPOINTS: EndpointFeedbackEndpoint[] = [ @@ -188,16 +192,25 @@ export function parseEndpointFeedbackRating( return rating as SearchFeedbackRating; } -export function isEndpointFeedbackDisabledLocally( - env: NodeJS.ProcessEnv = process.env -): boolean { - for (const key of ENDPOINT_FEEDBACK_OPT_OUT_ENV_VARS) { - const value = env[key]; - if (typeof value === 'string' && TRUTHY.has(value.trim().toLowerCase())) { - return true; - } +export function parseObservations( + raw?: string, + filePath?: string +): Record[] | undefined { + if (raw === undefined && filePath === undefined) return undefined; + if (raw !== undefined && filePath !== undefined) + throw new Error('Provide either --observations or --observations-file.'); + const value: unknown = JSON.parse(raw ?? readFileSync(filePath!, 'utf8')); + if ( + !Array.isArray(value) || + value.length < 1 || + value.length > 20 || + value.some( + (item) => !item || typeof item !== 'object' || Array.isArray(item) + ) + ) { + throw new Error('Observations must be a JSON array of 1-20 objects.'); } - return false; + return value; } export function parseEndpointFeedbackCliOptions(options: { @@ -209,8 +222,23 @@ export function parseEndpointFeedbackCliOptions(options: { valuableSources?: string; missingContent?: string | string[]; rating?: string; + observations?: string; + observationsFile?: string; + docClass?: string; }) { + if ( + options.docClass !== undefined && + !['born_digital', 'scanned', 'mixed', 'unknown'].includes(options.docClass) + ) + throw new Error( + '--doc-class must be one of: born_digital, scanned, mixed, unknown' + ); return { + docClass: options.docClass as EndpointFeedbackOptions['docClass'], + observations: parseObservations( + options.observations, + options.observationsFile + ), rating: parseEndpointFeedbackRating(String(options.rating || '')), issues: parseFeedbackListArg(options.issues, '--issues'), tags: parseFeedbackListArg(options.tags, '--tags'), @@ -224,29 +252,21 @@ export function parseEndpointFeedbackCliOptions(options: { export async function executeEndpointFeedback( options: EndpointFeedbackOptions ): Promise { - if (isEndpointFeedbackDisabledLocally()) { - return { - success: true, - disabled: true, - disabledSource: 'env', - creditsRefunded: 0, - }; - } - try { - if (options.apiKey || options.apiUrl) { - getClient({ apiKey: options.apiKey, apiUrl: options.apiUrl }); - } - const config = getConfig(); const apiKey = options.apiKey || config.apiKey; + if (apiKey && isEndpointFeedbackDisabledLocally()) { + return { + success: true, + disabled: true, + disabledSource: 'env', + creditsRefunded: 0, + }; + } const apiUrl = (options.apiUrl || config.apiUrl || DEFAULT_API_URL).replace( /\/$/, '' ); - if (!isCustomApiUrl(apiUrl)) { - validateConfig(apiKey); - } const body: Record = { endpoint: options.endpoint, @@ -260,6 +280,10 @@ export async function executeEndpointFeedback( ['issues', normalizeList(options.issues)], ['tags', normalizeList(options.tags)], ['note', options.note], + ['task', options.task], + ['assessment', options.assessment], + ['docClass', options.docClass], + ['observations', options.observations], ['valuableSources', options.valuableSources], ['missingContent', options.missingContent], ['querySuggestions', options.querySuggestions], diff --git a/src/commands/parse.ts b/src/commands/parse.ts index 4aa832fd9f..76fbd296d9 100644 --- a/src/commands/parse.ts +++ b/src/commands/parse.ts @@ -1,3 +1,4 @@ +import { reportFeedbackInvitation } from '../utils/feedback-invitation'; /** * Parse command implementation * @@ -184,8 +185,9 @@ export async function executeParse( try { const response = await fetch(`${apiUrl}/v2/parse`, { method: 'POST', - headers: - !keyless && apiKey ? { Authorization: `Bearer ${apiKey}` } : undefined, + headers: { + ...(!keyless && apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), + }, body: form, }); @@ -194,6 +196,11 @@ export async function executeParse( const payload = (await response.json().catch(() => ({}))) as any; + if (keyless) + reportFeedbackInvitation( + payload?.data?.metadata ?? payload?.metadata, + 'parse' + ); if (!response.ok || payload?.success === false) { const message = payload?.error || diff --git a/src/commands/scrape.ts b/src/commands/scrape.ts index c4d86f7c15..47c8860147 100644 --- a/src/commands/scrape.ts +++ b/src/commands/scrape.ts @@ -1,3 +1,4 @@ +import { reportFeedbackInvitation } from '../utils/feedback-invitation'; /** * Scrape command implementation */ @@ -151,6 +152,7 @@ export async function executeScrape( ...scrapeParams, }); result = json?.data ?? json; + reportFeedbackInvitation(result?.metadata, 'scrape'); } else { const app = getClient({ apiKey: options.apiKey, diff --git a/src/commands/search.ts b/src/commands/search.ts index 1abda30b17..6fe559ac9b 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -1,3 +1,4 @@ +import { reportFeedbackInvitation } from '../utils/feedback-invitation'; /** * Search command implementation */ @@ -110,6 +111,7 @@ export async function executeSearch( string, any >; + reportFeedbackInvitation(envelope.metadata, 'search'); } else { const app = getClient({ apiKey: options.apiKey, apiUrl: options.apiUrl }); const httpResponse = await (app as any).http.post( @@ -135,6 +137,7 @@ export async function executeSearch( warning: envelope.warning, id: envelope.id, creditsUsed: envelope.creditsUsed, + metadata: envelope.metadata, }; } catch (error) { return { @@ -315,6 +318,7 @@ export async function handleSearchCommand( if (result.warning) { jsonOutput.warning = result.warning; } + if (result.metadata) jsonOutput.metadata = result.metadata; if (result.id) { jsonOutput.id = result.id; } diff --git a/src/index.ts b/src/index.ts index 9bef16f0fd..eed2a9ba3c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -87,7 +87,6 @@ const AUTH_REQUIRED_COMMANDS = [ 'download', 'crawl', 'map', - 'feedback', 'search-feedback', 'agent', 'browser', @@ -417,6 +416,10 @@ function createScrapeCommand(): Command { .option('--actions-file ', 'Path to JSON actions file') .option('--proxy ', 'Proxy mode for scraping (e.g., auto, basic)') + .addHelpText( + 'after', + '\nOptional keyless feedback: firecrawl feedback --rating --task --assessment --observations-file . Use only evidence already available. Invitations and job references appear in metadata or stderr. Feedback does not consume operation quota.' + ) .action(async (positionalArgs, options) => { // Collect URLs from positional args and --url option let urls: string[] = []; @@ -866,6 +869,10 @@ Supported file types: .html, .htm, .pdf, .docx, .doc, .odt, .rtf, .xlsx, .xls Max upload size: 50 MB ` ) + .addHelpText( + 'after', + '\nOptional keyless feedback: firecrawl feedback --rating --task --assessment --observations-file . Use only evidence already available. Invitations and job references appear in metadata or stderr. Feedback does not consume operation quota.' + ) .action(async (file: string, options) => { let format: string | undefined; if (options.html) { @@ -974,6 +981,10 @@ function createSearchCommand(): Command { // false // ) .option('--json', 'Output as compact JSON', false) + .addHelpText( + 'after', + '\nOptional keyless feedback: firecrawl feedback --rating --task --assessment --observations-file . Use only evidence already available. Invitations and job references appear in metadata or stderr. Feedback does not consume operation quota.' + ) .action(async (query, options) => { // Parse sources let sources: SearchSource[] | undefined; @@ -1422,7 +1433,9 @@ function createSearchFeedbackCommand(): Command { */ function createFeedbackCommand(): Command { const cmd = new Command('feedback') - .description('Send feedback on a Firecrawl endpoint job.') + .description( + 'Send optional evidence about a job. Keyless Search, Scrape, and Parse accept one submission per identity per UTC day across all three categories without consuming operation quota.' + ) .argument('', 'Endpoint: search | scrape | parse | map') .argument('', 'The job id returned by the endpoint') .requiredOption('--rating ', 'Overall rating: good | bad | partial') @@ -1435,6 +1448,26 @@ function createFeedbackCommand(): Command { 'Comma-separated tags OR JSON array of tags' ) .option('--note ', 'Short note describing the feedback') + .option( + '--task ', + 'Task the output needed to support, required for keyless feedback' + ) + .option( + '--assessment ', + 'Meaningful assessment, required for keyless feedback' + ) + .option( + '--doc-class ', + 'Document class, required once for keyless Parse: born_digital | scanned | mixed | unknown' + ) + .option( + '--observations ', + 'JSON array of category-specific observations with kind, detail, and basis (output, source_comparison, or expectation)' + ) + .option( + '--observations-file ', + 'Read observations JSON from a file; use only evidence already available' + ) .option( '--valuable-sources ', 'Comma-separated URLs OR JSON array of {url, reason} entries' @@ -1469,6 +1502,15 @@ function createFeedbackCommand(): Command { 'Suppress output; useful when called in the background by another agent', false ) + .addHelpText( + 'after', + '\nKeyless evidence: task, assessment, and each observation detail must contain 10-2000 characters. Submit 1-20 observations.\n' + + 'Search: useful and irrelevant require a one-based position within the delivered group. source names the response group the position refers to: web, images, or news. It is required only when the job requested multiple sources; otherwise it defaults to web. The position must exist in that requested group. irrelevant requires reason: aggregator_over_official, off_topic, stale, wrong_content_type, snippet_misleading, or blocked_or_paywalled. vertical is required on missing and optional on useful/irrelevant: web_general, social, business, research, developer, news, government, finance, or other. missing may include topic (up to 200 characters) and knownSources (up to 20 HTTP(S) URLs). Do not submit engine attribution; it comes from the stored category tag at that position.\n' + + 'Scrape: kind correct, wrong_success, incomplete, or incorrect. wrong_success requires reason: blocked_shell, login_required, paywall, empty, wrong_page, stale, or wrong_locale. incomplete requires reason: partial_content, dynamic_content, pagination, main_content_stripped, or format_lost. incorrect requires reason: wrong, hallucinated, or missing_fields. correct has no reason. Optional location is up to 200 characters. No retryOutcome. Hard-failed Scrape jobs receive no feedback invitation.\n' + + 'Parse: --doc-class is required once per submission: born_digital, scanned, mixed, or unknown. Observation kind: correct, text_ocr, table, formula, chart_figure, reading_order, headers_footers, headings_formatting, completeness, images_dropped, or incorrect. text_ocr requires reason: misread_chars, garbled, or missing_text. table requires reason: structure, cells_glued, or digits. completeness requires reason: pages_missing, truncated_at_max_pages, or sections_dropped. incorrect requires reason: wrong, hallucinated, or missing_fields. Other kinds have no reason subtype. Optional page is a one-based positive integer.\n' + + 'Scrape and Parse: format must be a format type the job requested. It is required for output and source_comparison observations when multiple formats were requested; optional for expectation observations and single-format jobs. All observations retain detail and basis; source_comparison requires comparison: {reference, detail}.\n' + + 'Use only evidence already available. One accepted submission per keyless identity per UTC day, shared across Search, Scrape, Parse, and all clients.' + ) .action(async (endpointArg: string, jobId: string, options: any) => { let endpoint; try { @@ -1493,6 +1535,10 @@ function createFeedbackCommand(): Command { issues: parsed.issues, tags: parsed.tags, note: options.note, + task: options.task, + assessment: options.assessment, + docClass: parsed.docClass, + observations: parsed.observations, valuableSources: parsed.valuableSources, missingContent: parsed.missingContent, querySuggestions: options.querySuggestions, diff --git a/src/types/search.ts b/src/types/search.ts index 04486bf543..1088858ef0 100644 --- a/src/types/search.ts +++ b/src/types/search.ts @@ -120,6 +120,7 @@ export interface SearchResultData { } export interface SearchResult { + metadata?: Record; success: boolean; data?: SearchResultData; warning?: string; diff --git a/src/utils/client.ts b/src/utils/client.ts index 6519495bfc..728e6811dd 100644 --- a/src/utils/client.ts +++ b/src/utils/client.ts @@ -1,3 +1,4 @@ +import { reportFeedbackInvitation } from './feedback-invitation'; /** * Firecrawl client utility * Provides a singleton client instance initialized with global configuration @@ -36,11 +37,14 @@ export async function keylessRequest( const apiUrl = (getConfig().apiUrl || DEFAULT_API_URL).replace(/\/$/, ''); const response = await fetch(`${apiUrl}${path}`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { + 'Content-Type': 'application/json', + }, body: JSON.stringify(body), }); const json: any = await response.json().catch(() => ({})); if (!response.ok) { + reportFeedbackInvitation(json?.metadata, path.split('/').pop()!); throw new Error( json?.error || `Firecrawl request failed (HTTP ${response.status})` ); diff --git a/src/utils/feedback-invitation.ts b/src/utils/feedback-invitation.ts new file mode 100644 index 0000000000..fd699c1a7b --- /dev/null +++ b/src/utils/feedback-invitation.ts @@ -0,0 +1,13 @@ +export function reportFeedbackInvitation( + metadata: any, + endpoint: string +): void { + if (typeof metadata?.jobId === 'string') { + process.stderr.write(`Feedback job (${endpoint}): ${metadata.jobId}\n`); + } + if (typeof metadata?.feedback?.message === 'string') { + process.stderr.write( + `${metadata.feedback.message}\nUse: firecrawl feedback ${endpoint} ${metadata.feedback.jobId} --rating --task --assessment --observations-file ${endpoint === 'parse' ? ' --doc-class ' : ''}\n` + ); + } +} diff --git a/src/utils/feedback-settings.ts b/src/utils/feedback-settings.ts new file mode 100644 index 0000000000..7eca34d9ba --- /dev/null +++ b/src/utils/feedback-settings.ts @@ -0,0 +1,12 @@ +export const ENDPOINT_FEEDBACK_OPT_OUT_ENV_VARS = [ + 'FIRECRAWL_NO_ENDPOINT_FEEDBACK', + 'FIRECRAWL_DISABLE_ENDPOINT_FEEDBACK', +] as const; + +export function isEndpointFeedbackDisabledLocally( + env: NodeJS.ProcessEnv = process.env +): boolean { + return ENDPOINT_FEEDBACK_OPT_OUT_ENV_VARS.some((key) => + /^(1|true|yes|on)$/i.test(env[key]?.trim() ?? '') + ); +}