diff --git a/README.md b/README.md index f68dc29107..af330f03e6 100644 --- a/README.md +++ b/README.md @@ -466,9 +466,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 evidence through `/v2/feedback`. Feedback on keyless `search`, `scrape`, and +`parse` jobs is requested in exchange for free keyless use. These 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. + +Each keyless job accepts one submission; retrying returns the original feedback +ID. 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 \ @@ -483,25 +494,79 @@ 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 for multi-source jobs. Omission defaults to web, so images-only and news-only jobs must explicitly name their source. 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). missing and irrelevant may include knownSources (up to 20 HTTP(S) URLs): where absent content lives or the source that should have ranked instead. Unmentioned results are unassessed; a full ranking is not required. Do not submit engine attribution. + +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. hallucinated applies only to json, deterministicJson, summary, question, highlights, and changeTracking in json mode; missing_fields applies only to json and deterministicJson. For incomplete and incorrect, prefer source_comparison when the source is already available. + +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. incorrect applies to json and summary outputs. For text_ocr and table, include the correct text or cell values in comparison.detail when already known. Parse feedback does not automatically retain the document, extracted output, page images, or layout blocks; submitted observations and corrections are retained. + +Scrape and Parse observations other than failure: 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}. comparison.detail contains the correct content from the inspected source. + +Failed Search, Scrape, or Parse jobs: use kind failure with reason timeout, transport_error, proxy_error, or other. Accepted only for a failed job. Include detail and basis; do not supply position, source, format, location, or page. Parse still requires docClass (unknown is allowed). + +The stored keyless submission must fit within 8 KiB (8192 UTF-8 bytes), including server defaults and verification flags. Each job accepts one submission, and retrying returns the original feedback ID. Submission attempts are rate limited. Submit within 24 hours from the same caller IP. Contract and example: https://docs.firecrawl.dev/api-reference/endpoint/feedback. + +If the saved Search response is unavailable, otherwise valid observations are accepted and stored with metadata.unverified: true because their positions could not be checked. Job ownership and requested sources are still checked. Available results must contain every referenced position. + +Reason definitions: + +- aggregator_over_official: An intermediary was returned where the task needed an available official or primary source. +- off_topic: The result addresses a different topic from the task. +- stale: The content is outdated for the time or version the task requires. +- wrong_content_type: The destination has the wrong content type for the task, such as a discussion instead of a reference. +- snippet_misleading: The returned description misrepresents source content already inspected. +- blocked_or_paywalled: Access to the destination was observed to be blocked or require a subscription; do not infer this from its URL or snippet. +- blocked_shell: The successful response contains a bot challenge or access-blocking shell instead of the requested content. +- login_required: The successful response contains a login requirement instead of the requested content. +- paywall: The successful response contains a subscription barrier instead of the requested content. +- empty: The successful response contains no meaningful requested content. +- wrong_page: The successful response contains a different page or resource. +- wrong_locale: The response uses the wrong language or region for the task. +- partial_content: Only part of the expected content was returned, without a more specific known cause. +- dynamic_content: Content loaded by client-side rendering or interaction is missing. +- pagination: Expected content on additional pages is missing. +- main_content_stripped: Content filtering removed requested primary content. +- format_lost: Text is present, but meaningful structure such as headings, lists, or code formatting was lost. +- wrong: Returned facts or values conflict with the inspected source. +- hallucinated: The output asserts content unsupported by the inspected source. +- missing_fields: Requested fields are absent from the structured output. +- misread_chars: Characters were recognized incorrectly. +- garbled: Extracted text is corrupted or unreadable. +- missing_text: Visible source text was omitted. +- structure: Table rows, columns, or header relationships were reconstructed incorrectly. +- cells_glued: Distinct table cells were merged. +- digits: Numeric table values were recognized incorrectly. +- pages_missing: Source pages are absent from the output. +- truncated_at_max_pages: Extraction ended at the configured page limit; this does not by itself imply a parser error. +- sections_dropped: Sections within processed pages were omitted. +- timeout: The operation explicitly reported a timeout. +- transport_error: The operation explicitly reported a network, connection, or TLS failure. +- proxy_error: The operation explicitly reported a proxy failure. +- other: Another operation failure was reported; describe the returned error without guessing its cause. + +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 includes a pointer on every eligible keyless job response. Feedback is requested in exchange for free keyless use; continued keyless access does not depend on it. #### 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 3cae0bf9b1..f28e31244d 100644 --- a/skills/firecrawl-search/SKILL.md +++ b/skills/firecrawl-search/SKILL.md @@ -86,9 +86,30 @@ Keep large search responses in `--json -o` output and select the relevant result - 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) +## 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 feedback is available for successful and failed jobs when the response includes a job reference. For an explicitly failed job, use observation `kind: "failure"` and `reason: "timeout"`, `"transport_error"`, `"proxy_error"`, or `"other"`; report only the error already returned. Keep the submission under 8 KiB including server defaults. Run `firecrawl feedback --help` for reason definitions and the complete contract. + +### 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` and one-based `position` within the delivered group. `source` (`web`, `images`, or `news`) is required for multi-source jobs and otherwise defaults to `web`. Irrelevant results also require `reason`; see command help for allowed values. +- Missing information: `kind: "missing"` and `vertical`; `topic` is optional. `vertical` is optional on useful and irrelevant results. See command help for allowed verticals. +- Missing and irrelevant observations may include `knownSources`: up to 20 HTTP(S) URLs, only when already known. These identify absent content or the source that should have ranked instead. Unmentioned results are unassessed; a full ranking is not required. +- Every observation requires `detail` and `basis`: `output`, `source_comparison`, or `expectation`. A source comparison also requires `comparison: {reference, detail}`, with the correct content in `comparison.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. + +Each job accepts one submission, and retrying returns the original feedback ID. Job references expire after 24 hours. Feedback does not consume or restore operation allowance. Keyless use is free in exchange for feedback: submit it for each invited job where you have specific evidence, and do not retry a rate-limit rejection in a loop. Client feedback flags do not suppress keyless invitations or submissions. + +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 290bffbdf0..9698a7f620 100644 --- a/skills/firecrawl/SKILL.md +++ b/skills/firecrawl/SKILL.md @@ -115,11 +115,15 @@ 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). +Keyless use is free in exchange for feedback. For keyless Search, Scrape, or Parse jobs, submit it with `firecrawl feedback ` with `--rating`, `--task`, `--assessment`, and `--observations-file`. Use the job reference and invitation returned in metadata or stderr. Run `firecrawl feedback --help` for category-specific observations. After an Alexandria task (a tool ran, or you looked for one and nothing covered the site), send `firecrawl alexandria feedback` once per website you needed data from. It is free and has no job ID; the pattern and issue codes live in [firecrawl-alexandria](../firecrawl-alexandria/SKILL.md). -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. Each keyless job accepts one submission, and 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" \ @@ -134,7 +138,9 @@ 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. +Keyless feedback is available for successful and failed jobs when the response includes a job reference. For an explicitly failed job, use observation `kind: "failure"` and `reason: "timeout"`, `"transport_error"`, `"proxy_error"`, or `"other"`; report only the error already returned. Keep the submission under 8 KiB including server defaults. Run `firecrawl feedback --help` for reason definitions and the complete contract. + +**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 139c926bd1..4c40554166 100644 --- a/src/__tests__/cli-argv.test.ts +++ b/src/__tests__/cli-argv.test.ts @@ -7,6 +7,32 @@ 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', + 'one submission', + ]) { + expect(result.stdout).toContain(field); + } + expect(result.stdout).not.toContain('UTC day'); + } + ); + testWithBuiltCli('rejects invalid PDF page caps before scraping', () => { for (const value of ['0', '10001', '2.5', '3pages']) { const result = spawnSync( diff --git a/src/__tests__/commands/feedback.test.ts b/src/__tests__/commands/feedback.test.ts index 45e86f4779..80edccac8d 100644 --- a/src/__tests__/commands/feedback.test.ts +++ b/src/__tests__/commands/feedback.test.ts @@ -1,23 +1,19 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { executeEndpointFeedback, + parseEndpointFeedbackCliOptions, handleEndpointFeedbackCommand, parseEndpointFeedbackEndpoint, parseFeedbackListArg, parsePageNumbersArg, } from '../../commands/feedback'; import { parseAlexandriaFeedbackArray } from '../../commands/alexandria-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; @@ -36,10 +32,97 @@ 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('preserves replacement sources on keyless irrelevant Search observations', async () => { + vi.stubEnv('FIRECRAWL_API_KEY', ''); + initializeConfig({ + apiKey: undefined, + apiUrl: 'https://api.firecrawl.dev', + }); + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ success: true, feedbackId: 'feedback-1' }), + }); + const observations = [ + { + kind: 'irrelevant', + reason: 'aggregator_over_official', + position: 1, + knownSources: ['https://example.com/official'], + basis: 'output', + detail: 'The official reference should rank before this aggregator.', + }, + ]; + await executeEndpointFeedback({ + endpoint: 'search', + jobId: '00000000-0000-4000-8000-000000000001', + rating: 'partial', + task: 'Find the official retry reference', + assessment: 'An aggregator ranked above the official reference.', + observations, + }); + const [, init] = mockFetch.mock.calls[0]; + expect(init.headers.Authorization).toBeUndefined(); + expect(JSON.parse(init.body).observations).toEqual(observations); + }); + it('posts Alexandria session feedback without job fields or legacy metadata', async () => { mockFetch.mockResolvedValue({ ok: true, @@ -112,10 +195,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', @@ -197,7 +276,6 @@ describe('executeEndpointFeedback', () => { creditsRefunded: 0, }); - expect(getClient).not.toHaveBeenCalled(); expect(mockFetch).not.toHaveBeenCalled(); }); @@ -226,7 +304,6 @@ describe('executeEndpointFeedback', () => { expect(stderrSpy).not.toHaveBeenCalled(); expect(stdoutSpy).not.toHaveBeenCalled(); - expect(getClient).not.toHaveBeenCalled(); expect(mockFetch).not.toHaveBeenCalled(); } finally { exitSpy.mockRestore(); @@ -257,6 +334,26 @@ describe('feedback parsing', () => { }); }); +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(); + }); +}); + describe('parseAlexandriaFeedbackArray capability issues', () => { const base = { name: 'attachments', 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__/commands/search.test.ts b/src/__tests__/commands/search.test.ts index 632e9d5384..b39cde0d15 100644 --- a/src/__tests__/commands/search.test.ts +++ b/src/__tests__/commands/search.test.ts @@ -9,6 +9,10 @@ import { initializeConfig } from '../../utils/config'; import { writeOutput } from '../../utils/output'; import { setupTest, teardownTest } from '../utils/mock-client'; +vi.mock('../../utils/credentials', () => ({ + loadCredentials: vi.fn(() => null), +})); + vi.mock('../../utils/output', () => ({ writeOutput: vi.fn() })); // Mock the Firecrawl client module @@ -875,3 +879,48 @@ describe('executeSearch', () => { }); }); }); + +describe('keyless Search failure feedback', () => { + it('prints the returned job and invitation when Search fails', async () => { + setupTest(); + vi.stubEnv('FIRECRAWL_API_KEY', ''); + initializeConfig({ + apiKey: undefined, + apiUrl: 'https://api.firecrawl.dev', + }); + const stderr = vi + .spyOn(process.stderr, 'write') + .mockImplementation(() => true); + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: false, + status: 500, + json: async () => ({ + success: false, + error: 'Search transport failed', + metadata: { + jobId: 'failed-search-job', + feedback: { + jobId: 'failed-search-job', + message: 'Optional feedback is available.', + }, + }, + }), + }) + ); + try { + const result = await executeSearch({ query: 'retry reference' }); + expect(result.success).toBe(false); + expect(result.error).toBe('Search transport failed'); + const printed = stderr.mock.calls.map((call) => call[0]).join(''); + expect(printed).toContain('Feedback job (search): failed-search-job'); + expect(printed).toContain('firecrawl feedback search failed-search-job'); + } finally { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + stderr.mockRestore(); + teardownTest(); + } + }); +}); diff --git a/src/__tests__/utils/feedback-invitation.test.ts b/src/__tests__/utils/feedback-invitation.test.ts new file mode 100644 index 0000000000..cfff1d91b9 --- /dev/null +++ b/src/__tests__/utils/feedback-invitation.test.ts @@ -0,0 +1,47 @@ +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 a short optional reminder 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: 'Server feedback guidance.' }, + }, + 'parse' + ); + expect(stdout).not.toHaveBeenCalled(); + const printed = stderr.mock.calls.flat().join(''); + expect(printed).toBe( + 'Feedback job (parse): job-1\n' + + 'Feedback requested in exchange for free keyless use: firecrawl feedback parse job-1 --help\n' + ); + expect(printed).not.toContain('Server feedback guidance.'); + expect(printed).not.toContain('--observations-file'); + }); + 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 20dabae661..4a60c2a325 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, @@ -20,6 +24,10 @@ export interface EndpointFeedbackOptions { providerFeedback?: Record[]; capabilityFeedback?: Record[]; rating: SearchFeedbackRating; + task?: string; + assessment?: string; + docClass?: 'born_digital' | 'scanned' | 'mixed' | 'unknown'; + observations?: Record[]; issues?: string[]; tags?: string[]; note?: string; @@ -38,6 +46,7 @@ export interface EndpointFeedbackOptions { } export type EndpointFeedbackErrorCode = + | 'FEEDBACK_UNAVAILABLE' | 'JOB_NOT_FOUND' | 'SEARCH_NOT_FOUND' | 'FEEDBACK_WINDOW_EXPIRED' @@ -64,12 +73,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[] = [ @@ -192,16 +195,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: { @@ -213,8 +225,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'), @@ -228,29 +255,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, @@ -275,6 +294,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 5407275df6..43d6591604 100644 --- a/src/commands/scrape.ts +++ b/src/commands/scrape.ts @@ -1,3 +1,4 @@ +import { reportFeedbackInvitation } from '../utils/feedback-invitation'; /** * Scrape command implementation */ @@ -162,6 +163,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 d3346864ec..e09e41a6ad 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -1,3 +1,4 @@ +import { reportFeedbackInvitation } from '../utils/feedback-invitation'; /** * Search command implementation */ @@ -118,6 +119,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( @@ -144,6 +146,7 @@ export async function executeSearch( warning: envelope.warning, id: envelope.id, creditsUsed: envelope.creditsUsed, + metadata: envelope.metadata, }; } catch (error) { return { @@ -371,6 +374,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 d9416f6284..be53790fa5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -95,7 +95,6 @@ const AUTH_REQUIRED_COMMANDS = [ 'download', 'crawl', 'map', - 'feedback', 'search-feedback', 'agent', 'browser', @@ -436,6 +435,10 @@ function createScrapeCommand(): Command { .option('--actions-file ', 'Path to JSON actions file') .option('--proxy ', 'Proxy mode for scraping (e.g., auto, basic)') + .addHelpText( + 'after', + '\nKeyless feedback, requested in exchange for free keyless use: 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) => { const target = resolveScrapeTarget(positionalArgs ?? [], options); if (target.kind === 'alexandria') { @@ -878,6 +881,10 @@ Supported file types: .html, .htm, .pdf, .docx, .doc, .odt, .rtf, .xlsx, .xls Max upload size: 50 MB ` ) + .addHelpText( + 'after', + '\nKeyless feedback, requested in exchange for free keyless use: 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) { @@ -989,6 +996,10 @@ function createSearchCommand(): Command { // false // ) .option('--json', 'Output as compact JSON', false) + .addHelpText( + 'after', + '\nKeyless feedback, requested in exchange for free keyless use: 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, toolQuery, options) => { const alexandriaOnly = toolQuery !== undefined; if (alexandriaOnly && query !== 'alexandria') { @@ -1480,7 +1491,9 @@ function createSearchFeedbackCommand(): Command { */ function createFeedbackCommand(): Command { const cmd = new Command('feedback') - .description('Send feedback on a Firecrawl endpoint job.') + .description( + 'Send evidence about a job. Keyless Search, Scrape, and Parse feedback is requested in exchange for free keyless use; each job accepts one submission 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') @@ -1493,6 +1506,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' @@ -1527,6 +1560,51 @@ 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 for multi-source jobs. Omission defaults to web, so images-only and news-only jobs must explicitly name their source. 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). missing and irrelevant may include knownSources (up to 20 HTTP(S) URLs): where absent content lives or the source that should have ranked instead. Unmentioned results are unassessed; a full ranking is not required. Do not submit engine attribution.\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. hallucinated applies only to json, deterministicJson, summary, question, highlights, and changeTracking in json mode; missing_fields applies only to json and deterministicJson. For incomplete and incorrect, prefer source_comparison when the source is already available.\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. incorrect applies to json and summary outputs. For text_ocr and table, include the correct text or cell values in comparison.detail when already known. Parse feedback does not automatically retain the document, extracted output, page images, or layout blocks; submitted observations and corrections are retained.\n' + + 'Scrape and Parse observations other than failure: 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}. comparison.detail contains the correct content from the inspected source.\n' + + 'Failed Search, Scrape, or Parse jobs: use kind failure with reason timeout, transport_error, proxy_error, or other. Accepted only for a failed job. Include detail and basis; do not supply position, source, format, location, or page. Parse still requires docClass (unknown is allowed).\n' + + 'If the saved Search response is unavailable, otherwise valid observations are accepted and stored with metadata.unverified: true because their positions could not be checked. Job ownership and requested sources are still checked. Available results must contain every referenced position.\n' + + 'Reason definitions:\n' + + '- aggregator_over_official: An intermediary was returned where the task needed an available official or primary source.\n' + + '- off_topic: The result addresses a different topic from the task.\n' + + '- stale: The content is outdated for the time or version the task requires.\n' + + '- wrong_content_type: The destination has the wrong content type for the task, such as a discussion instead of a reference.\n' + + '- snippet_misleading: The returned description misrepresents source content already inspected.\n' + + '- blocked_or_paywalled: Access to the destination was observed to be blocked or require a subscription; do not infer this from its URL or snippet.\n' + + '- blocked_shell: The successful response contains a bot challenge or access-blocking shell instead of the requested content.\n' + + '- login_required: The successful response contains a login requirement instead of the requested content.\n' + + '- paywall: The successful response contains a subscription barrier instead of the requested content.\n' + + '- empty: The successful response contains no meaningful requested content.\n' + + '- wrong_page: The successful response contains a different page or resource.\n' + + '- wrong_locale: The response uses the wrong language or region for the task.\n' + + '- partial_content: Only part of the expected content was returned, without a more specific known cause.\n' + + '- dynamic_content: Content loaded by client-side rendering or interaction is missing.\n' + + '- pagination: Expected content on additional pages is missing.\n' + + '- main_content_stripped: Content filtering removed requested primary content.\n' + + '- format_lost: Text is present, but meaningful structure such as headings, lists, or code formatting was lost.\n' + + '- wrong: Returned facts or values conflict with the inspected source.\n' + + '- hallucinated: The output asserts content unsupported by the inspected source.\n' + + '- missing_fields: Requested fields are absent from the structured output.\n' + + '- misread_chars: Characters were recognized incorrectly.\n' + + '- garbled: Extracted text is corrupted or unreadable.\n' + + '- missing_text: Visible source text was omitted.\n' + + '- structure: Table rows, columns, or header relationships were reconstructed incorrectly.\n' + + '- cells_glued: Distinct table cells were merged.\n' + + '- digits: Numeric table values were recognized incorrectly.\n' + + '- pages_missing: Source pages are absent from the output.\n' + + '- truncated_at_max_pages: Extraction ended at the configured page limit; this does not by itself imply a parser error.\n' + + '- sections_dropped: Sections within processed pages were omitted.\n' + + '- timeout: The operation explicitly reported a timeout.\n' + + '- transport_error: The operation explicitly reported a network, connection, or TLS failure.\n' + + '- proxy_error: The operation explicitly reported a proxy failure.\n' + + '- other: Another operation failure was reported; describe the returned error without guessing its cause.\n' + + 'Use only evidence already available. The stored keyless submission must fit within 8 KiB (8192 UTF-8 bytes), including server defaults and verification flags. Each job accepts one submission, and retrying returns the original feedback ID. Submission attempts are rate limited. Submit within 24 hours from the same caller IP. Contract and example: https://docs.firecrawl.dev/api-reference/endpoint/feedback.' + ) .action(async (endpointArg: string, jobId: string, options: any) => { let endpoint; try { @@ -1551,6 +1629,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 c8a094d65c..143163903c 100644 --- a/src/types/search.ts +++ b/src/types/search.ts @@ -124,6 +124,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..0b4578687e --- /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?.jobId === 'string') { + process.stderr.write( + `Feedback requested in exchange for free keyless use: firecrawl feedback ${endpoint} ${metadata.feedback.jobId} --help\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() ?? '') + ); +}