跳转到主体内容

Official CLI ​

Use Node 24.15+ and a built package. The packaged launcher needs no global installation:

sh
node "<skill_dir>/scripts/nb-search.mjs" --help
node "<skill_dir>/scripts/nb-search.mjs" --version

In a checkout, run pnpm build first and use node scripts/nb-search.mjs. An installed nb-search command accepts identical arguments. The only business commands are search, fetch, and capabilities. All examples below abbreviate the launcher as nb-search.

Local and remote profiles ​

Local is the default. Global options precede the command:

sh
nb-search --profile local capabilities
nb-search --profile cloud capabilities
nb-search --profile cloud --doctor

--doctor is an offline configuration/credential-presence and semantic check, never a provider probe or remote health check. Its local guide groups configured lanes into onboarding/general, specialist/on-demand, research/synthesis or unclassified custom operations, using actual provider/operation/output identity rather than lane spelling. Groups are not quality rankings. Cost/latency remain relative; guide readiness is not_evaluated unless supplied from a real runtime catalog, and live_verified is false. Start with one configured general results source instead of enabling every research lane. Local capabilities also performs no provider probe. Remote capabilities sends one authenticated catalog request, not a search/provider request.

The CLI reads profiles.json under NB_SEARCH_HOME (default OS home .nb-search):

json
{"schema_version":"1","profiles":{"cloud":{"kind":"remote","base_url":"https://search.example/","token_env":"NB_SEARCH_CLOUD_TOKEN","timeout_ms":120000}}}

Supply the service key through that env reference or protected remote-secrets.json:

json
{"schema_version":"1","values":{"NB_SEARCH_CLOUD_TOKEN":"<service-access-key>"}}

Never put a token in argv, a URL, or profiles.json. Remote selection does not open canonical provider config or local provider secrets. local is reserved; no remote default is inferred. Unknown profiles fail. HTTPS is required; allow_loopback_http:true permits HTTP only for literal localhost/127.0.0.1/::1 development services. Optional profile limits mirror the remote factory: timeout_ms, max_request_bytes, max_response_bytes. No redirects, automatic retries, uploads, or silent local fallback.

Local canonical configuration follows the SDK's normal precedence. Protected secrets.json has the same versioned values-map format, optionally with private imported-key binding metadata generated by migration. File values fill only absent process-env names; empty existing env entries intentionally disable a key. The CLI does not modify process.env, global environment, or shell startup files. Its runtime and detached worker receive the same private env copy; snapshots retain only grants, not secret values. SDK/MCP hosts remain responsible for providing their own env.

Queries and complete JSON input ​

sh
nb-search search "query" --lane exa.search
nb-search search "facet one" --query "facet two" --lanes exa.search,tavily.search
nb-search search "research brief" --lane gma.research
nb-search search --query=--leading-dashes
nb-search search -- --help
nb-search fetch "https://example.com/" --pipeline direct.fetch

--lane can repeat; lane, lanes, and preset forms are mutually exclusive. Search also supports freshness (pd/pw/pm/py), max-results, timeout-ms, execution, and idempotency-key. Fetch supports pipeline, representation (markdown/text), timeout-ms, max-content-chars, execution, and idempotency-key. Numbers are decimal safe integers within input-schema bounds. No hidden query-based routing, automatic full-source expansion, or implicit GMA replacement occurs. Timeout resolution is request-level timeout_ms > explicit execution.search_timeout_ms > default; when neither is supplied, the grok-multi-agent/research provider defaults to 600000 ms (10 minutes), while ordinary search remains 30000 ms.

For portable Unicode, quotes, and local file/inline input, pipe one UTF-8 JSON document to search --stdin or fetch --stdin. For example, the stdin bytes may be:

json
{"action":"run","query":"Compare A and B — one complete brief","lane":"gma.research","execution":"async","idempotency_key":"brief-1"}
json
{"action":"run","source":{"kind":"inline_text","content":"Local evidence to normalize.","media_type":"text/plain"},"pipeline":"direct.local"}
json
{"action":"run","source":{"kind":"file","scope":"papers","path":"paper.txt"},"pipeline":"direct.local"}

File scope papers must already be configured; input JSON grants no arbitrary file access. Remote v1 rejects all inline/file sources before HTTP IO, even if a catalog advertises them. capabilities --stdin accepts exactly {}.

Do not combine stdin with positional/shorthand request fields. Profile and applicable helpers (--wait, --all) may accompany it. A leading BOM/whitespace is allowed; malformed UTF-8/JSON, trailing documents, unknown schema fields, or input exceeding 4 MiB is rejected before runtime construction. The CLI bound does not change the local SDK contract.

Async receipt, wait, and complete reads ​

sh
nb-search search "brief" --lane gma.research --execution async --idempotency-key brief-1 --wait 240000
nb-search search get <job_id> --wait 240000
nb-search search read <job_id> --all
nb-search search read <job_id> --page-size 8
nb-search search cancel <job_id>

The same get/read/cancel forms apply to fetch. Follow-up job actions default to the local connection; remote follow-ups require an explicit --profile <name>. The CLI records async receipt connection identities in immutable job-connections/<job_id>.json files and still checks legacy job-connections.json; known mismatches fail before contacting another endpoint. Unknown SDK job IDs require a deliberately chosen profile when remote, with no cross-profile discovery. Service ACLs remain authoritative, including after key rotation.

--wait MS accepts 1–3,600,000 ms only for async run or get; it never converts sync to async. It controls client-side command polling duration without altering server or provider execution timeouts. It respects poll_after_ms, bounds HTTP and sleep by remaining budget, and does not call cancel on timeout. Successful completion reads the entire artifact. Failed/cancelled completion returns its receipt/metadata. If a start succeeds but local connection recording fails, stdout retains the safe receipt and stderr explains the recording failure; preserve that receipt and original profile.

Raw read still returns the original page envelope (artifact, chunks, optional next_cursor). read --all cannot combine with cursor/page-size. It checks canonical base64, contiguous chunk indices/offsets and lengths, stable artifact metadata, cursor progress, total byte length, SHA-256, fatal UTF-8, JSON and logical output schema. Limits: 64 MiB reconstructed artifact and 10,000 pages. Nothing is silently truncated. Never ask a model to assemble base64 manually.

A complete search read/wait prints the stored logical output: results-channel rows or typed-channel data, status and lane outcomes. A complete fetch read/wait prints its stored sync fetch envelope. These are intentionally not raw page envelopes. Expired artifacts are not regenerated. Wait budget exhaustion prints:

json
{"cli_schema_version":"1","status":"timed_out","job_id":"...","last":{"action":"get","state":"running"},"cancel_requested_by_cli":false}

last is the full last-received receipt/envelope, abbreviated above for readability. Failure of the initial HTTP operation instead uses the normal stderr error path. Timeout/abort never implies upstream cancellation or a refund.

Output and exits ​

Normal stdout is one JSON value plus newline; help/version are text exceptions. Diagnostics and thrown errors use stderr. No raw credential JSON, token, upstream body, stack, or network exception is included in diagnostics.

ExitMeaning
0succeeded, capabilities, offline doctor success, import success, or cancel-request acknowledgement
2invocation/configuration/transport/protocol/integrity error, failed result/job, blocked migration
3partial logical result or partial migration
4empty result
5timeout or exhausted wait budget
6cancelled result/job or caller cancellation
7pending queued/running job

A succeeded get means metadata was obtained, not that a stored partial/empty result is logically succeeded. Cancel exit 0 acknowledges the request only; inspect state and cancel_requested. Unlike the earlier CLI, empty/partial/pending are not generally exit 0.

Explicit search-layer import ​

Migration is an explicit operator action, not SDK legacy lookup:

sh
nb-search --import-search-layer --dry-run
nb-search --import-search-layer --apply
nb-search --doctor

Use --source PATH to select a source explicitly. Otherwise the first existing file wins: SEARCH_LAYER_CREDENTIALS, OS home .openclaw/credentials/search.json, cwd credentials/search.json. The selected malformed file blocks; there is no fallback to a lower-priority source. BOM is accepted. Dry-run has zero writes and no network calls; apply never modifies the source.

Reports contain source path, provider/status/reason categories, and target created/merged/unchanged state, not keys, key fragments/hashes, raw endpoints/models, or source JSON. Existing identical values are no-ops; conflicting values block rather than overwrite. Migration can write to any configured NB_SEARCH_CONFIG path, including locations outside the home directory or targets reached through filesystem links, with the exception of reserved metadata leaf names (.config-access.lock, .config-revision.json, .<basename>.nb-search.lock, and .<basename>.nb-search-revision.json) which cannot be used as configuration files or redirected via metadata leaf symlinks. Temporary staging files are created adjacent to each resolved target and replace files atomically without replacing links. Canonical process environment variables continue to take precedence over saved files according to the SDK resolution order, without blocking the import from saving. Configuration schema validation and non-destructive merge rules remain strictly enforced.

  • Exa/Tavily preserve direct provider/proxy URL semantics and exact search suffix handling. Compatible configured results lanes form research-evidence; Exa then Tavily is the default preference. SDK built-in defaults are unchanged.
  • Grok Chat Completions does not prove Responses support. Imported Grok stays disabled with a compatibility reason.
  • GMA keeps its independently resolved key in NB_SEARCH_GROK_MULTI_AGENT_API_KEY via an explicit credential slot. Missing own JSON key/URL follows resolved Grok inheritance. Legacy env supports GROK_API_KEY/URL and GROK_MULTI_AGENT_MODEL/EFFORT/API_MODE; it does not support independent GROK_MULTI_AGENT_API_KEY/URL env names. No new legacy aliases are inferred.
  • The existing GMA provider now accepts explicit options.api_mode: "chat_completions" | "messages", defaulting to chat when omitted. Both known modes with a valid base/matching suffix can be compatible-but-unverified. Reports expose only normalized_protocol: chat_completions | messages | unknown plus reasons such as API_MODE_UNKNOWN, ENDPOINT_MISSING, ENDPOINT_PROTOCOL_CONFLICT, or CREDENTIAL_MISSING. Unknown modes and cross-protocol endpoint suffixes remain disabled; no URL switching or mode fallback occurs.
  • Both GMA modes send stream: true to the provider and require an SSE-capable gateway. Messages implements the observed relay contract: POST /messages, top-level system, Bearer plus x-api-key and anthropic-version, reasoning.effort, and bounded JSON text blocks in the SSE response. Thinking/tool blocks are not evidence. stream: true describes provider-side transport; sync/async describes the local job lifecycle. The public SDK and CLI still return the completed typed result as JSON, not a user token stream. This is not a claim of generic native Anthropic compatibility. The typed research output and CLI paths are unchanged; data.api_mode reflects the selected protocol. GMA adapter version is now 2: finish version-1 in-flight GMA jobs before upgrading, because old execution snapshots cannot be rebuilt by the new worker. No compatibility provider or snapshot-fingerprint bypass is added.
  • Both local GMA modes reject every HTTP 3xx before following it or forwarding credentials/body. The redirect response stream is cancelled and the fixed error is non-retryable, even if an execution retry budget is configured. Supply the final authorized endpoint explicitly; do not rely on relay redirects. Custom host HTTP transports must honor the request's manual redirect policy. Other providers' default transport redirect behavior is unchanged.
  • Aggregate gateway credentials cannot become vendor keys. Per-provider timeout settings that cannot map to the shared runtime budget are reported unsupported. Migration sets local retry_count to zero without changing SDK defaults.
  • Imported file keys populate private provider credential slots. The runtime verifies current configuration syntax and provider-operation references without enforcing legacy endpoint or slot binding metadata. If an imported credential file contains obsolete binding entries, they are accepted for backward compatibility without acting as admission gates.

A partial report means useful compatible providers may be configured while optional/incompatible/missing providers remain. It is not full search-layer parity, verified credentials, or authorization to make paid calls. No importer operation calls providers.

Permissions, coordinated publication, and recovery ​

The CLI creates new configuration files with 0600 mode and directories with 0700 mode, respecting the user's selected file locations and filesystem links. It does not inspect or alter existing file permissions or execute operating-system ACL management commands. If an underlying filesystem operation fails with a permission or I/O error, the CLI reports the error directly.

Ordinary local readers no longer take or create .config-access.lock: same-home capabilities, searches, fetches and job follow-ups can run concurrently, including overlapping provider execution. Readers capture one bounded configuration/secret snapshot between two revision observations and two absent-writer-marker checks. They construct the runtime from that in-memory snapshot without a later canonical re-read. A configuration change permits only a small bounded snapshot retry, never provider replay. Missing-home capabilities, doctor, sync inline fetch and unknown-job reads leave the home missing.

Only importer/config writers take persistent transaction locks. In addition to the home-level .config-access.lock and .config-revision.json, each resolved data target file X is protected by adjacent sidecars: .<basename(X)>.nb-search.lock and .<basename(X)>.nb-search-revision.json. This coordinates writers and prevents collision even when distinct home directories share a custom configuration file target. Writers publish complete configuration pairs, atomically advance their target revision UUIDs, and remove their transaction locks; revisions are preserved. Readers observe consistent snapshot pairs across all targets without blocking concurrent operations.

First async admission initializes home and job receipt storage before JobStore writes or dispatches work. Job connection bindings use immutable per-job files under job-connections/ with atomic no-replace publication. Different jobs do not share a configuration lock; same-ID conflicting bindings are rejected. Existing job-connections.json is still honored read-only and is not deleted or overwritten. A local provider write marker does not prevent authorized remote job get/read/cancel.

Writer publication failures or crashes retain their transaction markers, causing subsequent operations to report the specific busy or recovery marker path. Locks record a transaction descriptor listing home, data, lock, and revision paths without sensitive credential values. Do not remove any marker based only on PID or age, and do not remove only a single lock while leaving partial state behind. To recover: stop cooperating writer processes, inspect the protected .migration-*-backup.json and staged files locally without printing secrets, restore the complete configuration and secrets pair, publish fresh revision UUIDs across all target revisions recorded in the transaction, and then remove all corresponding transaction locks. Never delete revision files back to an uninitialized state. If completeness cannot be established, leave storage blocked. There is no automatic recovery switch. Old reader-crash locks from earlier versions still require deliberate recovery; do not assume they are safe to erase.

Routine user edits to configuration files are read directly without requiring manual revision updates. The CLI ensures atomic pairs and transaction coordination specifically for cooperating importer and writer commands; uncoordinated concurrent manual modifications to multiple files are outside this transactional guarantee. Only an interrupted transaction or crash recovery requires following the formal restoration steps. Stop older CLI/importer writer processes before upgrading: they do not publish commit revisions and must not race new writes. No serial invocation workaround is required for ordinary reader concurrency.

基于 MIT 协议开源 · AI 索引: /nb-search/llms.txt