Augeo AI Docs
SDKsSearch SDK

Host integration

Connect host results, ranked catalog reads, program chat availability, measurement, the results banner, product navigation, and chat.

Choose where results render, then connect product selection and optional chat handoff. The SDK measures submissions before delegating to the host, including query-only callbacks. The completion integration below is optional when you also need confirmed result counts and outcomes. That result measurement needs a SPA route that keeps this shell and the SDK mounted. An optional results banner uses the same shell. The host owns its placement and the submitted-search facts. The Search SDK does not create that route or invent the total.

Prerequisites

  • Load the Search SDK bundle and provide a mount element.
  • Supply a current member bearer through your host session accessor.
  • Save the release declarations as vendor/search-sdk/index.d.ts.
  • Define host results and product routes before wiring those callbacks.
  • Add a results container, such as #search-results, when enabling the results banner.
  • Load the Chat SDK bundle when enabling Search-to-chat handoff.
  • Supply the program chat snapshot when the host has resolved it.

SDK API and host integration

SDK API in these examples: createAugeoSearch, createTheoSearchBanner, SearchSubmitHandler, SearchExecution, SearchPresentedResults, TheoSearchResultsSnapshot, ProgramChatAvailability, ProgramChatScope, searchCatalog, SearchCatalogRequest, SearchCatalogPage, and SearchCatalogContext. Host integration: searches, rewardsHubSearchAdapter, theoResultsHandoff, sharedSearchResultsHandoff, navigateToSearch, loadCatalogPage, showResultsPage, showSearchFailure, currentProgramChat, applyProgramChat, replaceProgramScope, hostRelevance, paintCatalog, and navigateToReturnedPath. Those host functions are not SDK exports. sharedSearchResultsHandoff is the host adapter to the shared contextual handoff. It is not a Search SDK method, and it is not the product-detail handoff. Do not pass a search snapshot to that product-detail API. Implement them against your router, catalog loader, and results view. Copy the TypeScript fences on this page in order. They are one module. These fences import only the standalone Search declarations. They do not import chat or common-ui.

onSearchSubmit is (query: string, execution: SearchExecution) => void. A callback that accepts only query still compiles and still runs. It receives automatic search.submitted measurement without using the execution argument. Use that argument only to report presentation for the separate search.performed event. The callback query is the executed search string. Use it unchanged for the request, route, and display. Do not lowercase, redact, or cap that string. The SDK sanitizes only the analytics keyword.

Lifetime

These handle restrictions apply only to optional search.performed result measurement. Automatic search.submitted measurement does not require a retained handle or host completion adapter.

Keep the completion handle in application memory. Pass only the execution id through router state. In-app navigation must leave the shell and the SDK mounted. Full document navigation drops the in-memory handle. If a flow unloads the SDK, add an explicit transfer before production use. Do not claim that flow works until that transfer exists. Do not assign window.location when retaining result measurement eligibility. That unloads the SDK and drops the handle.

Closing the panel must not cancel a pending host execution. Leaving the results route cancels only the id that route captured. An old route cleanup must not read mutable navigation state. Member or program changes cancel pending work, then destroy the SDK.

Host adapter

rewardsHubSearchAdapter is host integration, not an SDK method. navigateToSearch must check cancellation before it commits the route. A new execution id must load again even when the path text matches. loadCatalogPage is the initial catalog read. This controller is the owner of that first read. If your route loader already owns that request, join that exact request instead. Do not fetch the initial page twice. showResultsPage calls onCommitted only after the matching products or empty state commit. showSearchFailure shows the error state and does not report an empty success.

import type {
  AugeoSearchInstance,
  CreateAugeoSearchOptions,
  ProgramChatAvailability,
  ProgramChatScope,
  SearchCatalogContext,
  SearchCatalogItem,
  SearchCatalogPage,
  SearchCatalogRequest,
  SearchExecution,
  SearchPresentedResults,
  SearchResult,
  SearchSubmitHandler,
  TheoSearchBannerInstance,
  TheoSearchBannerSearch,
  TheoSearchCriteriaV1,
  TheoSearchEligibility,
  TheoSearchResultsHandoff,
  TheoSearchResultsSnapshot,
} from './vendor/search-sdk/index';

interface CatalogProduct {
  readonly productId: number;
}

interface CatalogPage {
  readonly products: readonly CatalogProduct[];
  readonly totalResultCount: number;
  readonly categoryId?: string;
  readonly productType?: string;
}

interface SearchRouteState {
  readonly query: string;
  readonly searchExecutionId: string;
}

interface SearchFailure {
  readonly executionId: string;
  readonly message: string;
}

interface RewardsHubSearchAdapter {
  navigate(query: string, executionId: string, signal: AbortSignal): Promise<SearchRouteState>;
  load(query: string, signal: AbortSignal): Promise<CatalogPage>;
  present(page: CatalogPage, executionId: string, onCommitted: () => void): void;
  showError(error: SearchFailure): void;
}

declare function currentMemberToken(): string;

declare function currentProgramChat(): ProgramChatAvailability;

declare function replaceCredentialScope(scope: ProgramChatScope): void;

const unresolvedProgramChat: ProgramChatAvailability = { status: 'unresolved', scope: null };

declare function navigateToSearch(
  path: string,
  state: { readonly searchExecutionId: string },
  signal: AbortSignal,
): Promise<SearchRouteState>;

declare function loadCatalogPage(input: {
  readonly query: string;
  readonly page: number;
  readonly signal: AbortSignal;
}): Promise<CatalogPage>;

declare function showResultsPage(input: {
  readonly page: CatalogPage;
  readonly executionId: string;
  readonly onCommitted: () => void;
}): void;

declare function showSearchFailure(error: SearchFailure): void;

declare function rememberLegacyQuery(query: string): void;

interface SharedSearchResultsHandoff {
  open(snapshot: TheoSearchResultsSnapshot, signal: AbortSignal): void;
}

declare const sharedSearchResultsHandoff: SharedSearchResultsHandoff;

const theoResultsHandoff: TheoSearchResultsHandoff = (snapshot, signal) => {
  if (signal.aborted) return;
  sharedSearchResultsHandoff.open(snapshot, signal);
};

const rewardsHubSearchAdapter: RewardsHubSearchAdapter = {
  navigate: (query, executionId, signal) =>
    navigateToSearch(`/search/${encodeURIComponent(query)}`, { searchExecutionId: executionId }, signal),
  load: (query, signal) => loadCatalogPage({ query, page: 1, signal }),
  present: (page, executionId, onCommitted) => showResultsPage({ page, executionId, onCommitted }),
  showError: (error) => showSearchFailure(error),
};

Application controller

Keep searches in the application shell, outside the search panel. start receives the exact callback query and the SDK handle. Clear the active reference before abort, cancel, or presented. A listener may start a newer search during that call. Check the execution id before committing navigation, after the fetch, and in the view callback. Ignore a late callback whose id is no longer current. Starting tea cancels pending coffee and ignores its late navigation, fetch, and commit.

Report presentation only after the matching products or empty state commit. Router completion, fetch completion, loading placeholders, and retained cards are not presentation. Use the displayed item count, not the total match count. Omit categoryId and productType when the page did not apply them. page.totalResultCount is a separate authoritative total for the results banner. Do not copy products.length, totalPages, or hasMore into that field. A positive count becomes outcome success. Zero becomes outcome empty. The host does not send keyword or outcome. Invalid page, count, or filter facts throw TypeError and leave the handle pending. Call presented again with corrected facts.

A recoverable failure shows the error state and emits nothing. Retry that request on the same execution. A later valid commit emits once. A terminal failure calls cancel and must not report an empty success. After cancellation, submit again to obtain a new execution. The SDK has no programmatic retry method.

Keystrokes, unselected suggestions, product clicks, Ask AI, pagination, and direct visits do not call searches.start. A generated suggestion in a non-chat program does call searches.start. Its query is the selected term, unchanged. Pagination and a direct route visit keep their existing loader behavior.

type RunPhase = 'loading' | 'error' | 'presented' | 'cancelled';

interface ActiveSearch {
  readonly id: string;
  readonly query: string;
  readonly execution: SearchExecution;
  readonly generation: number;
  controller: AbortController;
  phase: RunPhase;
}

const RESULTS_PLACEMENT_ID = 'rewards-results';

let generation = 1;
let active: ActiveSearch | null = null;
const routeCleanups = new Map<string, () => void>();
const bannerLeases = new Map<string, TheoSearchBannerSearch>();
let banner: TheoSearchBannerInstance | null = null;
let search: AugeoSearchInstance;

function isCurrent(run: ActiveSearch): boolean {
  return (
    active?.id === run.id &&
    run.generation === generation &&
    run.phase !== 'cancelled' &&
    run.phase !== 'presented'
  );
}

function retire(run: ActiveSearch): void {
  if (run.phase === 'cancelled' || run.phase === 'presented') return;
  run.phase = 'cancelled';
  if (active?.id === run.id) active = null;
  run.controller.abort();
  run.execution.cancel();
}

function presentedFacts(page: CatalogPage): SearchPresentedResults {
  const facts: SearchPresentedResults = {
    page: 1,
    resultCount: page.products.length,
  };
  if (page.categoryId !== undefined) facts.categoryId = page.categoryId;
  if (page.productType !== undefined) facts.productType = page.productType;
  return facts;
}

function bannerEligibility(page: CatalogPage): TheoSearchEligibility {
  const categoryId = page.categoryId;
  const productType = page.productType;
  if (categoryId !== undefined && categoryId.trim() === '') return { status: 'unsupported' };
  if (
    productType !== undefined &&
    productType !== 'standalone' &&
    productType !== 'configurable' &&
    productType !== 'gift_card'
  ) {
    return { status: 'unsupported' };
  }
  const criteria: TheoSearchCriteriaV1 = {
    ...(categoryId !== undefined ? { categoryId } : {}),
    ...(productType !== undefined ? { productType } : {}),
  };
  return { status: 'supported', criteria };
}

function presentBanner(run: ActiveSearch, page: CatalogPage): void {
  const lease = bannerLeases.get(run.id);
  if (!lease) return;
  lease.present({
    searchId: run.id,
    placementId: RESULTS_PLACEMENT_ID,
    query: run.query,
    eligibility: bannerEligibility(page),
    totalResultCount: page.totalResultCount,
  });
}

function commitPresented(run: ActiveSearch, page: CatalogPage): void {
  if (!isCurrent(run)) return;
  presentBanner(run, page);
  const facts = presentedFacts(page);
  active = null;
  try {
    run.execution.presented(facts);
    run.phase = 'presented';
  } catch (error) {
    if (active === null && run.generation === generation && run.phase === 'loading') active = run;
    throw error;
  }
}

function isAbortError(error: unknown): boolean {
  return error instanceof Error && error.name === 'AbortError';
}

async function runSearch(run: ActiveSearch): Promise<void> {
  const attempt = run.controller;
  try {
    const route = await rewardsHubSearchAdapter.navigate(run.query, run.id, attempt.signal);
    if (!isCurrent(run) || route.searchExecutionId !== run.id || run.controller !== attempt) return;
    const page = await rewardsHubSearchAdapter.load(run.query, attempt.signal);
    if (!isCurrent(run) || run.controller !== attempt) return;
    rewardsHubSearchAdapter.present(page, run.id, () => {
      if (run.controller !== attempt) return;
      commitPresented(run, page);
    });
  } catch (error) {
    if (!isCurrent(run) || run.controller !== attempt || isAbortError(error)) return;
    run.phase = 'error';
    rewardsHubSearchAdapter.showError({ executionId: run.id, message: 'Search failed' });
  }
}

function start(query: string, execution: SearchExecution): void {
  if (!query.trim()) {
    execution.cancel();
    return;
  }
  const lease = banner?.beginSearch(execution.id);
  if (lease) bannerLeases.set(execution.id, lease);
  const previous = active;
  const run: ActiveSearch = {
    id: execution.id,
    query,
    execution,
    generation,
    controller: new AbortController(),
    phase: 'loading',
  };
  active = run;
  routeCleanups.set(run.id, () => {
    if (active?.id === run.id) retire(run);
  });
  if (previous && previous.id !== run.id) retire(previous);
  if (active?.id !== run.id) return;
  void runSearch(run);
}

function retryRecoverable(): void {
  const run = active;
  if (!run || run.phase !== 'error' || run.generation !== generation) return;
  run.controller.abort();
  run.controller = new AbortController();
  run.phase = 'loading';
  void runSearch(run);
}

function cancelTerminal(): void {
  if (active) retire(active);
}

function abandonRoute(executionId: string): void {
  const lease = bannerLeases.get(executionId);
  bannerLeases.delete(executionId);
  lease?.invalidate();
  const cleanup = routeCleanups.get(executionId);
  routeCleanups.delete(executionId);
  cleanup?.();
}

function onMemberOrProgramChange(): void {
  generation += 1;
  for (const lease of bannerLeases.values()) lease.invalidate();
  bannerLeases.clear();
  banner?.destroy();
  banner = null;
  if (active) retire(active);
  search.destroy();
}

function closePanel(): void {
  search.update({ open: false });
}

function beginCategoryRevision(categoryId: string, totalResultCount: number): void {
  if (!banner || categoryId.trim() === '') return;
  const searchId = crypto.randomUUID();
  const lease = banner.beginSearch(searchId);
  bannerLeases.set(searchId, lease);
  lease.present({
    searchId,
    placementId: RESULTS_PLACEMENT_ID,
    query: '',
    eligibility: { status: 'supported', criteria: { categoryId } },
    totalResultCount,
  });
}

function disableTheo(): void {
  banner?.update({ handoff: null });
}

function enableTheo(): void {
  banner?.update({ handoff: theoResultsHandoff });
}

const searches = {
  start,
  retry: retryRecoverable,
  cancel: cancelTerminal,
  abandonRoute,
  onMemberOrProgramChange,
  closePanel,
  beginCategoryRevision,
  disableTheo,
  enableTheo,
  applyProgramChat,
  replaceProgramScope,
};

SDK initialization

Add onSearchSubmit only when the host will fetch and display results. A callback that merely logs the query also disables panel catalog results. Wire that callback to searches.start. The panel then requests closure and makes no catalog request. That closure does not cancel the handle.

const target = document.getElementById('search-host');
if (!target) throw new Error('Search mount container is missing.');

const legacySubmit: SearchSubmitHandler = (query) => {
  rememberLegacyQuery(query);
};

const placement = document.getElementById('search-results');
const createBanner = window.AugeoSearchSdk.createTheoSearchBanner;
if (placement && typeof createBanner === 'function') {
  banner = createBanner({
    target: placement,
    placementId: RESULTS_PLACEMENT_ID,
    handoff: theoResultsHandoff,
  });
}

const options: CreateAugeoSearchOptions = {
  target,
  auth: { getToken: () => currentMemberToken() },
  open: false,
  capabilities: { programChat: currentProgramChat() },
  onOpenChange: (open) => {
    search.update({ open });
  },
  onSearchSubmit: (query, execution) => {
    searches.start(query, execution);
  },
};
search = window.AugeoSearchSdk.createAugeoSearch(options);

function applyProgramChat(programChat: ProgramChatAvailability): void {
  search.update({ capabilities: { programChat } });
}

function replaceProgramScope(next: ProgramChatAvailability): void {
  if (next.scope === null) return;
  search.update({ capabilities: { programChat: unresolvedProgramChat } });
  searches.onMemberOrProgramChange();
  replaceCredentialScope(next.scope);
  search = window.AugeoSearchSdk.createAugeoSearch({
    ...options,
    capabilities: { programChat: next },
  });
}

Pass currentProgramChat() at creation. Call searches.applyProgramChat for a same-scope change. Call searches.replaceProgramScope only when the scope itself changes. See Program chat availability.

The /search page belongs to your application. The SDK does not create that route or the #search-results container. Omit onSearchSubmit if you want the widget to perform and render catalog search. Feature-detect createTheoSearchBanner before mounting the banner. An older bundle without that factory still renders host results. searches.disableTheo passes handoff: null when the shared handoff is unavailable. That hides the banner and leaves routing, results, and adjacent controls usable. searches.enableTheo installs the adapter again. It does not retry a CTA by itself. searches.beginCategoryRevision is a host revision outside onSearchSubmit. Use it for a blank query with a supported nonblank categoryId. A blank query with empty criteria, or a product type alone, is not eligible. Call beginSearch synchronously when the revision starts, before asynchronous work. Call present only after the matching results view commits. abandonRoute invalidates only the lease id that route captured. Closing the panel does not invalidate it. Member or program changes destroy the binding. A disconnected mount is not reused. Create a new binding for the next lifetime. The callback receives the frozen snapshot and an AbortSignal. Supersession, invalidation, handoff: null, and destroy abort outstanding signals. Do not also launch from an event listener. Callback resolution is not admission, an automatic turn, or recommendation state. Those remain in the shared contextual handoff.

Outcomes

Each deliberate submit or suggestion selection gets a fresh execution id. An identical query still gets a new id. Selecting a catalog suggestion submits its keyword, not the typed prefix. A prefix such as coff must not replace coffee maker. 834 matches do not set the displayed count.

execution.presented({
  page: 1,
  resultCount: displayedProducts.length,
});
execution.presented({ page: 1, resultCount: 0 });

displayedProducts is the committed page, not the match total. resultCount 15 with 535 total matches is success, not 535. A fully redacted term still searches with the callback query. It emits no performed event. A long query still searches in full. Its event keyword is the canonical value capped at 200. Telemetry failure does not replace the committed result.

CaseMeasurement
Typed coffee, 535 matches, 15 shownkeyword coffee, page 1, resultCount 15, outcome success
Type coff, select coffee makerMeasure coffee maker, not coff. 834 matches do not set the count
Committed empty pagepresented({ page: 1, resultCount: 0 }) yields empty
Failed load, then retryNo event on error. Same execution emits once after commit
Cancel, then submit againOld handle stays inert. A new submission creates a new id
Pending coffee, then teaCancel coffee. Ignore its late navigation, fetch, and commit
Submit coffee againNew id may emit again on the same path text
Duplicate commit, rerender, page 2No additional performed event
Close panel while loadingPending host measurement stays eligible
Leave the results routeCancel that route's captured id, not a newer search
Mixed case, padding, redactable, or longSearch uses the callback query. The event keyword is canonical and at most 200
Whitespace-only or fully redactedNo performed event. A blank submit does not call the host

The banner does not read that measurement. For 15 shown and 535 matches, pass totalResultCount: 535 on the banner snapshot and keep resultCount at 15. For the coffee maker row, pass totalResultCount: 834. Page 2 does not change the banner snapshot. Supported criteria are an optional nonblank categoryId and an optional productType of standalone, configurable, or gift_card. An unfiltered search uses criteria: {}. Unknown criteria are unsupported. A missing total is null, not the page length. Omitted minResultCount means 45, compared inclusively. The published Design System TheoSearchBanner owns desktop and mobile layout, the accessible name, and keyboard operation. Search pins @kigo-digital/design-system@1.0.0. The qualification record is packages/search-sdk/docs/theo-search-banner-compatibility.md. Do not restyle the banner or add a second CTA. Denied banner observations do not disable that CTA.

Observe panel results

In panel mode, use onCatalogComplete to observe a successful catalog page. Its payload is { products, totalPages, hasMore }. products is a readonly list of SearchProduct values. There is no query field, total-count field, or public next-page method in this payload. onCatalogComplete does not complete a host-owned search.

const target = document.getElementById('search-host');
if (!target) throw new Error('Search mount container is missing.');
const status = document.getElementById('search-status');
if (!status) throw new Error('Search status element is missing.');
const search = window.AugeoSearchSdk.createAugeoSearch({
  target,
  auth: { getToken: () => window.hostSession.getMemberToken() },
  open: false,
  onOpenChange: (open) => search.update({ open }),
  onCatalogComplete: ({ products, hasMore }) => {
    status.textContent =
      `${products.length} products shown${hasMore ? '; more results exist' : ''}.`;
  },
  onResultSelect: (product) => {
    window.location.assign(`/products/${encodeURIComponent(product.productId)}`);
  },
});

Mount search-status in your host page when using this example. Do not add onSearchSubmit to this instance unless transferring results ownership to the host.

Product payload

productId and name are required; all other product fields are optional. Callbacks use camelCase names, rather than the API's wire field names. Handle absent metadata without inferring a checkout decision.

FieldsMeaning
productId, nameStable numeric product identifier and display name
brand, imageUrl, reason, badgeOptional display metadata
pointsPrice, minPointsPrice, maxPointsPriceOptional points price or range
productTypestandalone, configurable, or gift_card
ctaadd_to_cart, view_details, or select_amount
actioncart.add or product.view
requiresSelection, hasVariants, denominationCountSelection and denomination metadata
wishlistEnabled, inWishlistOptional wishlist metadata
splitTenderPotential eligibility, with optional cash amount and currency

Treat action and cta as recommendation metadata. A selected product still requires host validation before cart, denomination, or variant actions. splitTender.status is potentially_eligible; it does not guarantee a payable cash amount or completed eligibility check.

Ranked catalog reads

searchCatalog is a read on the mounted instance. Feature-detect it. An older bundle still mounts without that method. The result is the existing SearchResult union: success, empty, failure, or cancelled. The read does not create a SearchExecution. It does not record a recent, and it does not mean the host painted results. Ordinary search still uses execution.presented only after paint. Do not emit a second execution for the public catalog read.

Authentication is unchanged. The same auth.getToken and optional auth.onFailure apply, including the single retry. A final authentication failure uses the existing sign-in notice. Do not treat it as an empty page or as a Relevance fallback. Other failures keep SearchFailure codes: unavailable, category_unavailable, rate_limited, http, network, and invalid_response. Non-2xx responses are not catalog pages. There is no second error protocol.

At request start, capture query, page, limit, and context. An explicit request.catalogContext replaces the instance snapshot for that read. catalogContext: {} clears it. Omitting the field uses the instance snapshot. update({ catalogContext }) replaces the previous context, so removed filters and location do not stick. A later update must not mutate an in-flight snapshot. destroy, a member or program change, and a newer query, page, filter set, or location invalidate older results. Pass an AbortSignal for the host deadline. That deadline is a host setting, not an SDK option and not a shared server budget.

catalog is optional analytics metadata. Admitted events copy it to data.context.theo.catalog. Accepted values are kigo and rewards_hub. Omitted catalog preserves existing product-catalog semantics. Do not send catalog as a provider selector, and do not branch the widget on the string kigo.

Host fieldWire query
latitude, longitude, radiussame names
searchRadiusUnitsearch_radius_unit
categoryIdscategory_ids
catalogFilterIdscatalog_filter_ids
redemptionTypesredemption_types
offerTypesoffer_types
merchantIdsmerchant_ids
singleOfferPerMerchantsingle_offer_per_merchant
lightningDeallightning_deal
trendingtrending
catalognot sent

Serialize arrays as comma-separated lists. Omit empty arrays. Booleans are true or false. Location is the complete four-value tuple or absent. trending: true requires location. Accepted redemption values are in_store, print, online, purchase, and spend_and_get. clickthrough can appear on an offer and is not an accepted input filter. Pre-search and typeahead forward only location and catalogFilterIds. Keep the submitted query unchanged, within 200 characters. Forward the host page and limit. Kigo page sizes are 1–25. Do not invent an offset from a different limit.

Render returned order. rankingSource: "kigo" on success or empty is already the fallback order. Use it. Do not fetch that page again. totalCount is absent when a legacy product response lacks it. An offer is never a product. onCatalogComplete and onResultSelect stay product-only. onCatalogItemsComplete receives the generic page, including empty, and is not a result-view event. onCatalogItemSelect receives the typed entry. Navigate once. If a product handler is also installed, do not navigate that same selection twice. The SDK validates next_action.kind of view_details and a nonblank path, then forwards that path unchanged. It does not construct a provider route. Offer rows omit points, product cart actions, a why line, and a save control when wallet status is unavailable. Do not infer a percentage from max_discount, invent a price, or use a merchant, token, or location id as the item id.

Best for you calls searchCatalog with the captured page, limit, and filters. On an API error after the existing auth retry, or on the host deadline, call hostRelevance with the same filters, location, and page. The SDK does not implement that upstream call. Other sorts and browse stay on host paths. Disregard a late response after a newer query or scope.

Explicit ordinary search posts { query, submission_id } once. submission_id is execution.id. An auth retry reuses that body. recorded: true and recorded: false are both acknowledgements. The boolean does not select a provider. A history failure does not block navigation or ranking. Focus, typing, prefetch, page changes, Ask AI, and searchCatalog do not post. Dismissal does not submit.

The host supplies the token getter, location, filters, and deadline. window.Kigo.onSearch({ searchText, latitude, longitude }) is a host notification. Coordinates may be null. Calling it does not navigate. uiuxOverride['offer-search'].preventDefaultNavigation only suppresses the shell's own navigation. The adapter must still produce one navigation. Do not place a raw Kigo credential in an SDK global. Marketplace placement, token exchange, map, browse, and live acceptance stay with the host. A controlled fixture is not that acceptance.

hostRelevance, paintCatalog, navigateToReturnedPath, and notifyHostSearch are host functions. They are not SDK exports. hostDeadlineMs is an example host setting.

const offerCatalogContext: SearchCatalogContext = {
  catalog: 'kigo',
  latitude: 41.88,
  longitude: -87.63,
  radius: 10,
  searchRadiusUnit: 'MI',
  categoryIds: [12],
  catalogFilterIds: ['11111111-1111-4111-8111-111111111111'],
  redemptionTypes: ['in_store', 'print', 'online', 'purchase', 'spend_and_get'],
  offerTypes: [
    'bogo',
    'free_with_purchase',
    'percentage_savings',
    'dollars_off',
    'price_point',
    'cash_back',
    'merchandise',
    'digital_gift_card',
    'physical_gift_card',
    'spend_and_get',
    'affiliate',
  ],
  merchantIds: [7],
  singleOfferPerMerchant: true,
  lightningDeal: false,
  trending: true,
};

interface RelevanceQuery {
  readonly query: string;
  readonly page: number;
  readonly limit: number;
  readonly catalogContext: SearchCatalogContext;
}

declare function hostRelevance(
  query: RelevanceQuery,
  signal: AbortSignal,
): Promise<SearchCatalogPage>;

declare function paintCatalog(page: SearchCatalogPage): void;

declare function navigateToReturnedPath(path: string): void;

declare function notifyHostSearch(input: {
  readonly searchText: string;
  readonly latitude: number | null;
  readonly longitude: number | null;
}): void;

const hostDeadlineMs = 8000;
let catalogGeneration = 0;
let catalogController: AbortController | null = null;

function openCatalogItem(entry: SearchCatalogItem): void {
  if (entry.kind !== 'offer') return;
  if (entry.offer.next_action.kind !== 'view_details') return;
  navigateToReturnedPath(entry.offer.next_action.path);
}

function observeCatalogPage(page: SearchCatalogPage): void {
  const total: number | undefined = page.totalCount;
  const source: SearchCatalogPage['rankingSource'] = page.rankingSource;
  void total;
  void source;
}

search.update({ catalogContext: {} });
search.update({
  catalogContext: offerCatalogContext,
  onCatalogItemsComplete: observeCatalogPage,
  onCatalogItemSelect: openCatalogItem,
});

const clearedRead: SearchCatalogRequest = {
  query: 'pizza',
  catalogContext: {},
};
const inheritedRead: SearchCatalogRequest = {
  query: 'pizza',
  page: 2,
  limit: 20,
};
void clearedRead;
void inheritedRead;

function authFailed(result: SearchResult<SearchCatalogPage>): boolean {
  return (
    result.phase === 'failure' &&
    (result.code === 'token' ||
      result.code === 'unauthorized' ||
      result.code === 'SESSION_INVALID' ||
      result.code === 'SESSION_EXPIRED' ||
      result.code === 'SESSION_REVOKED')
  );
}

async function bestForYou(query: string, page: number, limit: number): Promise<void> {
  catalogController?.abort();
  const controller = new AbortController();
  catalogController = controller;
  const generation = ++catalogGeneration;
  const timer = setTimeout(() => controller.abort(), hostDeadlineMs);
  const request: SearchCatalogRequest = {
    query,
    page,
    limit,
    catalogContext: offerCatalogContext,
  };
  notifyHostSearch({
    searchText: query,
    latitude: offerCatalogContext.latitude ?? null,
    longitude: offerCatalogContext.longitude ?? null,
  });
  try {
    if (!search.searchCatalog) return;
    const result = await search.searchCatalog(request, { signal: controller.signal });
    if (generation !== catalogGeneration) return;
    if (result.phase === 'success' || result.phase === 'empty') {
      paintCatalog(result.data);
      return;
    }
    if (authFailed(result)) return;
    const deadline = controller.signal.aborted;
    const rankingFailure = result.phase === 'failure';
    if (!deadline && !rankingFailure) return;
    const fallback = await hostRelevance(
      {
        query,
        page,
        limit,
        catalogContext: request.catalogContext ?? {},
      },
      new AbortController().signal,
    );
    if (generation !== catalogGeneration) return;
    paintCatalog(fallback);
  } finally {
    clearTimeout(timer);
  }
}

void bestForYou('pizza', 2, 20);

bestForYou paints a successful rankingSource of kigo or model without a second SDK read. A deadline aborts the captured signal and then uses hostRelevance. A newer call aborts the previous signal and ignores its late page. notifyHostSearch does not navigate. openCatalogItem forwards the returned path. Product selection stays on onResultSelect.

Program chat availability

The catalog host owns the presentation snapshot. Map the resolved showRewardsAgent flag through the existing bootstrap helper. Literal true is enabled. Literal false is disabled. Loading, missing, invalid, or failed resolution is explicit unresolved. Pass that same snapshot to Search and to the personalized widget. Do not add an entitlement endpoint. onAskAi does not establish availability. Chat authorization stays a separate check.

Create Search with capabilities.programChat. Omit it only for an existing integration. Omission keeps legacy Ask actions and is not an entitlement. A new integration must pass enabled, disabled, or unresolved.

InputPresentationGenerated row
enabled with the bound scopeExisting Ask actionsExisting chat handoff
disabled with the bound scopeAsk actions hiddenOrdinary submit of that term
Explicit unresolvedAsk actions hiddenOrdinary submit. Do not queue chat
Malformed valueAsk actions hiddenOrdinary submit
Omitted at creationLegacy Ask actionsLegacy handoff, not an entitlement

When presentation is enabled, a generated row keeps the existing chat handoff. When it is disabled, unresolved, or invalid, that row calls ordinary submit. The query is the selected term, unchanged. Enter of the same phrase uses this same callback and results page. Do not open chat for that selection. Do not add a second results route. Panel catalog fallback still applies when onSearchSubmit is omitted. That fallback does not satisfy results-page acceptance. Predictive rows and recent searches keep their existing selection behavior.

searches.applyProgramChat changes availability only. An omitted programChat keeps the previous snapshot. It cannot restore omission. Same-scope changes apply at the next activation, without a remount. A null unresolved update keeps the original binding. searches.replaceProgramScope publishes unresolved, then uses member-change cleanup. It replaces credentials and creates a new instance with the new snapshot. Pass a snapshot whose scope is non-null. A null scope is not a remount. A token refresh with the same scope does not remount. A new token alone is not enabled. Mount Search when chat is disabled. Do not require the chat bundle for that program.

Compare generated selection and Enter on an authoritative disabled program. Then exercise an enabled program and a program or auth switch. Record the existing route, host request, committed results, and chat behavior. A controlled fixture is not that acceptance. A ticket link does not supply the snapshot.

Connect Search to chat

Search and chat are separate instances and bundles. Chat uses the loyalty-concierge CDN segment; Search uses loyalty. The Chat SDK token accessor must return a string synchronously. Keep a current token in the host session when sharing authentication with chat.

<div id="search-host"></div>
<div id="chat-host"></div>
<script src="https://sdks.augeoai.net/chat-sdk/loyalty-concierge/latest/index.js"></script>
<script src="https://sdks.augeoai.net/search-sdk/loyalty/latest/index.js"></script>
<script>
  const assistant = new window.AugeoChatSdkLoyaltyConcierge.AugeoAssistant({
    container: '#chat-host',
    auth: { getToken: () => window.hostSession.memberToken },
    surface: { type: 'modal', openOnMount: false, fab: false },
  });

  const target = document.getElementById('search-host');
  if (!target) throw new Error('Search mount container is missing.');
  const search = window.AugeoSearchSdk.createAugeoSearch({
    target,
    auth: { getToken: () => window.hostSession.memberToken },
    open: false,
    capabilities: { programChat: window.hostSession.programChat },
    onOpenChange: (open) => search.update({ open }),
    onResultSelect: (product) => {
      window.location.assign(`/products/${encodeURIComponent(product.productId)}`);
    },
    onAskAi: (query) => assistant.open({ seed: query, autoSubmit: true }),
  });

  window.addEventListener('pagehide', () => {
    search.destroy();
    assistant.destroy();
  }, { once: true });
</script>

hostSession.memberToken is a host-managed string, refreshed by your application. hostSession.programChat is the same snapshot passed to other consumers. This example is the enabled path. A disabled snapshot must not use this handoff for a generated row. A disabled program can still pass the callback. That callback must not run for a generated row. The snapshot, not the callback, selects the path. assistant.open({ seed: query, autoSubmit: true }) opens chat and submits that exact query once. Search itself does not call the agent chat endpoint. Do not also open chat from the launcher event when onAskAi already opens it. That would process the same handoff twice. That pagehide listener is for full page unload. Do not destroy the SDK when an in-app results route changes.

For production, replace both latest paths with the release URLs chosen for each SDK. Their versions and API origins are configured independently.

Rollout

The Search API stays on the loyalty IIFE and types/index.d.ts. Hosts do not import React, the design system, or the chat SDK to mount this banner. createTheoSearchBanner is optional. If it is missing, keep the results page.

The controlled harness at /?theoBanner=on demonstrates this recipe. It commits two page items and an authoritative total of 45, records the handoff callback, and does not open an assistant. This fixture does not verify host placement or integrated acceptance. A search harness fixture is also not host acceptance. Compare a generated suggestion with Enter on the existing results page. Both must use the same query, route, and committed view. No chat panel may open for a disabled program. Record that comparison for the authoritative disabled program. Repeat it for an enabled program and a scope change.

Require the real desktop and mobile container before rollout. Require the submitted query, supported criteria, placement identity, and authoritative total. The CTA must enter the released shared contextual handoff. A fixture spy does not prove opening, admission, automatic turn submission, or recommendation state.