Augeo AI Docs
SDKsSearch SDK

Configuration

Factory options, catalog context, completion handles, analytics, recovery, and branding.

Pass CreateAugeoSearchOptions to window.AugeoSearchSdk.createAugeoSearch(). The factory requires target; usable interactive search also needs authentication and host-controlled visibility.

Prerequisites

  • Complete Quick start.
  • Choose whether the panel or host owns catalog results.

Options

OptionType or defaultBehavior
targetHTMLElement, required at creationAppend the custom element inside this container
apiBaseUrlAbsolute HTTP(S) URL; bundle defaultOverride the API base when required by your environment
auth.getToken() => string or () => Promise<string>Read the cached THEO bearer. Do not mint here
openboolean, default falseControl panel visibility
onOpenChange(open: boolean) => voidApply visibility requests through update
onSearchSubmitSearchSubmitHandler, optionalHost owns results and receives an execution handle
onCatalogComplete(result: SearchCatalogCompletion) => void, optionalObserve the current successful panel product page. Offers are not passed here
onResultSelect(product: SearchProduct) => void, optionalHandle a selected product. Offers are not passed here
catalogContextSearchCatalogContext, optionalSnapshot for catalog, pre-search, and typeahead. See Catalog context
onCatalogItemsComplete(page: SearchCatalogPage) => void, optionalObserve the current successful generic page, including empty. Not a measurement signal
onCatalogItemSelect(entry: SearchCatalogItem) => void, optionalHandle a selected offer or product entry. The host owns navigation
onAskAi(query: string) => void, optionalOpen a conversation with the selected seed text
auth.onFailure(failure: SearchAuthFailure) => void or Promise, optionalAwait before the single retry. Omit to keep the getter reread
onAuthError(error: SearchAuthError) => void, optionalFinal authentication notice after recovery stops
labels.searchLabelstring, default SearchAccessible name for the field and panel
labels.placeholderstring, default SearchField and panel placeholder
presentationoverlay or sheet, optionalOverride automatic viewport presentation
branding.themeSearchThemeOverride, optionalPartner theme input, including palette.primary or colors.partner.primary, plus header tone
capabilities.analyticsSearchAnalyticsCapabilityOptions, optional, create onlyForward admitted events through host adapters. Omit it to stay on the event bus
capabilities.programChatProgramChatAvailability, optionalHost presentation snapshot. See Program chat availability

Blank label strings fall back to Search. Omitting presentation follows the viewport: sheet at 767 pixels or below, overlay above 767 pixels. Omitting apiBaseUrl uses the origin built into the selected bundle. An override changes requests, not the bundle's diagnostic .apiBaseUrl value. Pass https://api.augeoai.net for production. Named stage and development builds need their matching API base. The supported recovery build is revision b7909e4564933080f7dbc92e6c4915147906ab60. Its self-hosted script is /vendor/search-sdk/loyalty/index.js. Self-hosted production pages allow script-src 'self' and connect-src 'self' https://api.augeoai.net. A verified CDN script instead allows https://sdks.augeoai.net in script-src. Use only the script origin you actually load.

Search completion

onSearchSubmit is (query: string, execution: SearchExecution) => void. A callback that accepts only query still compiles and still runs. It cannot report host presentation until it uses the second argument. The SDK keeps the original nonblank query for search, navigation, and display. Do not trim, lowercase, or slice that query before requesting results. A disabled or unresolved program submits a generated term through this callback. That term matches Enter of the same phrase. Do not add another results route for it.

MemberContract
idReadonly identity. Each deliberate submit gets a new id
presented(results)Report committed page facts. Idempotent after success
cancel()End eligibility with no performed event

SearchPresentedResults requires page and resultCount. categoryId and productType are optional nonempty filter codes. Omit a filter the committed page did not apply. Do not pass keyword, outcome, or total matches. The SDK derives outcome from the displayed count. A positive count means success. Zero means empty. Invalid page, count, or filter facts throw TypeError. That error leaves the handle pending. Call presented again with corrected facts.

Panel mode does not need this callback. The panel completes through the same handle after its products or empty state commit. onCatalogComplete still observes that panel page. It does not complete a host search.

Keep the handle in application memory. Pass only the execution id through router state. Closing the panel must not cancel a pending host execution. Full document navigation drops the in-memory handle. A host that unloads the SDK must transfer that lifetime before production use. See Host integration and Events.

Catalog context

searchCatalog is a method on a current mounted instance. Feature-detect it. An older bundle still mounts without it. The read returns SearchResult<SearchCatalogPage>: success, empty, failure, or cancelled. It uses the same auth.getToken, auth.onFailure, and single retry as other requests. It does not create a SearchExecution, record a recent, or mean the host painted results. There is no second error protocol. A final authentication failure still uses onAuthError and the sign-in notice.

if (search.searchCatalog) {
  const result = await search.searchCatalog(
    { query, page, limit, catalogContext },
    { signal },
  );
}

query, page, and limit are captured with the context at request start. Pass the host page size explicitly. Keep the query within 200 characters. Kigo page sizes are 1–25. The SDK forwards those values and does not compute an offset from a different limit. An explicit request.catalogContext replaces the instance snapshot for that read. {} clears it. Omitting it uses the instance snapshot.

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

Arrays are comma-separated. Omit empty arrays. Booleans are true or false. Location is all four fields or absent. trending: true requires location. Pre-search and typeahead forward only location and catalogFilterIds. catalog is kigo or rewards_hub. It is analytics metadata for data.context.theo.catalog. It is not a provider selector and does not authorize a program. The widget does not branch on the string kigo.

rankingSource: "kigo" on a successful or empty page is the order to render. Do not fetch that page again. totalCount is absent when a legacy product response has no total. Offers are a separate item variant. Do not cast an offer into SearchProduct. onCatalogComplete and onResultSelect stay product-only. Navigate from onCatalogItemSelect for an offer, using next_action.path unchanged. Do not also navigate that same selection from a legacy handler. The SDK validates view_details and a nonblank path. It does not construct a provider URL.

Pass AbortSignal for the host deadline. That deadline is not an SDK option. destroy, a member or program change, and a newer query, page, filter set, or location invalidate older results. Do not commit a stale callback. The typed replacement, fallback, and ownership recipe is in Host integration.

Host exchange

The browser calls your authenticated host endpoint. The host server, not the browser, calls POST /api/token. Authorization is Basic credential id and mint secret. That secret never reaches the browser. Content type is application/x-www-form-urlencoded. There is no refresh token. Use expires_in from the response.

FieldValue
grant_typeurn:ietf:params:oauth:grant-type:token-exchange
subject_tokenVerified Kigo account_id
subject_token_typeurn:augeo-ai:params:oauth:token-type:external-account-id
scopeagent:offers-concierge member when sharing the bearer with Offers Chat; member for Search alone
session_handleCurrent account-space token, without Bearer

Do not send a profile id, email, or Kigo JWT as subject_token. Reject browser account, program, and provider overrides. programId on the SDK is a hint, not authorization. THEO finds or creates the identity in the host credential's program. An existing identity in another program or tenant is rejected. The host credential and principal must allow each requested scope. member alone does not grant Chat access. Refresh the Kigo session before reminting after an upstream rejection. Otherwise the new bearer still carries the rejected session. The response contains access_token, token_type, issued_token_type, expires_in, and scope. Return only those fields to the browser, with caching disabled. The access token is an opaque eus_ bearer. Send that bearer to the configured API. Never send the Kigo token or mint secret. Kigo session refresh, embed wiring, and logout handoff remain host-owned. This SDK does not mint tokens and does not add an Offers SDK.

import type { CachedTheoToken } from './vendor/kigo-auth/tokenBroker';

const TOKEN_PATH = '/api/token';
const GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';
const SUBJECT_TYPE = 'urn:augeo-ai:params:oauth:token-type:external-account-id';

function hostTokenUrl(origin: string): string {
  return new URL(TOKEN_PATH, origin).toString();
}

function exchangeBody(accountId: string, sessionHandle: string): string {
  return new URLSearchParams({
    grant_type: GRANT_TYPE,
    subject_token: accountId,
    subject_token_type: SUBJECT_TYPE,
    scope: 'agent:offers-concierge member',
    session_handle: sessionHandle,
  }).toString();
}

function serverAuthorization(credentialId: string, mintSecret: string): string {
  return `Basic ${btoa(`${credentialId}:${mintSecret}`)}`;
}

function cacheUntil(token: CachedTheoToken, nowMs: number): number {
  return nowMs + token.expires_in * 1000;
}

function theoBearer(token: CachedTheoToken): string {
  return token.access_token;
}

serverAuthorization runs only on the host server. The browser caches theoBearer and never sees mintSecret.

Authentication and recovery

The SDK reads auth.getToken before each request. A recognized recoverable 401 awaits optional auth.onFailure, then reads getToken once. That read is the existing single retry. onAuthError runs only after recovery fails to replace the token. Omitting onFailure keeps one getter reread and does not signal host renewal. A rejected callback, blank token, or unchanged token stops without another retry. A second 401 on the replacement reports onAuthError and stops. Only a later user action or a new session starts another cycle. Chat getToken returns a string, not a promise. Chat awaits onFailure and does not automatically retry the turn. Search awaits onFailure before its one retry.

CodeMeaning
tokenThe accessor failed or returned a blank token
unauthorizedAuthentication failed without a recognized session code
SESSION_INVALIDThe API rejected the session
SESSION_EXPIREDThe API reported an expired session
SESSION_REVOKEDThe API reported a revoked session

Recoverable HTTP 401 uses SESSION_EXPIRED, SESSION_REVOKED, or SESSION_INVALID. The message is Please sign in again. and recoverable is true. Chat can also receive that object in a transient data-auth-failure stream event. Search recovery uses the HTTP envelope only. Malformed bodies, recoverable: false, 403, 404, and outages do not renew. SearchAuthError contains code only. Show members Please sign in again. Do not show error codes, bearers, or provider bodies. Repeated final notices stay suppressed until a request succeeds. Updating credentials alone does not retry a failed section. After a new session, activate its recovery control or reopen the panel.

import type { AugeoAssistantAuth, AuthFailure } from './vendor/chat-sdk/index';
import type {
  CreateAugeoSearchOptions,
  SearchAuthError,
  SearchAuthFailure,
} from './vendor/search-sdk/index';
import type { TokenBroker } from './vendor/kigo-auth/tokenBroker';

const SIGN_IN_TEXT = 'Please sign in again.';

function searchAuth(broker: TokenBroker): CreateAugeoSearchOptions['auth'] {
  return {
    getToken: () => broker.readToken(),
    onFailure: async (failure: SearchAuthFailure) => {
      await broker.onFailure(failure);
    },
  };
}

function omittedRecovery(broker: TokenBroker): CreateAugeoSearchOptions['auth'] {
  return {
    getToken: () => broker.readToken(),
  };
}

function chatAuth(broker: TokenBroker): AugeoAssistantAuth {
  return {
    getToken: () => broker.getToken(),
    onFailure: async (failure: AuthFailure) => {
      await broker.onFailure(failure);
    },
  };
}

function finalAuthNotice(status: HTMLElement, _error: SearchAuthError): void {
  status.textContent = SIGN_IN_TEXT;
}

At most one host renewal runs for a failed credential across Chat and Search. Search issues at most one retry for that logical request. Failed renewal shows one sign-in action. Logout, member replacement, and program changes clear the cache and call destroy(). A late result must not restore the previous member's credentials or panel. Same-member renewal does not change authScopeKey and does not remount. The next intentional request reads the replacement bearer.

import type { AugeoSearchInstance } from './vendor/search-sdk/index';
import type { BrokerSession, TokenBroker } from './vendor/kigo-auth/tokenBroker';

const SIGN_IN_TEXT = 'Please sign in again.';

async function endSession(search: AugeoSearchInstance, broker: TokenBroker): Promise<void> {
  await broker.logout();
  search.destroy();
}

async function switchMember(
  search: AugeoSearchInstance,
  broker: TokenBroker,
  session: BrokerSession,
  scopeKey: string,
): Promise<AugeoSearchInstance> {
  search.destroy();
  await broker.changeSession(session);
  const target = document.getElementById('search-host');
  if (!target) throw new Error('Search mount container is missing.');
  return window.AugeoSearchSdk.createAugeoSearch({
    target,
    apiBaseUrl: 'https://api.augeoai.net',
    auth: {
      getToken: () => broker.readToken(),
    },
    capabilities: {
      programChat: {
        status: 'enabled',
        scope: { programId: session.programId, authScopeKey: scopeKey },
      },
    },
  });
}

function keepMountedRenewal(broker: TokenBroker): Promise<void> {
  broker.noteUserAction();
  return broker.signIn();
}

function showFailedRenewal(status: HTMLElement, broker: TokenBroker): void {
  const prompt = broker.signInPrompt();
  status.textContent = prompt === null ? SIGN_IN_TEXT : prompt.message;
}

Update and branding

update(options) merges defined top-level fields of SearchHostOptions and SearchCatalogHostOptions. Analytics adapters stay fixed at creation. capabilities.programChat is the only capability update accepts. Omit programChat, or pass undefined, to keep the current snapshot. An explicit snapshot replaces only availability. It does not reinstall analytics. Omitted fields and undefined keep their current values. Nested objects are replaced; include every nested value you want to retain. catalogContext follows that rule. Pass {} to clear filters and location. Omitting catalogContext keeps the previous snapshot. A later update does not change an in-flight request's captured snapshot. Passing undefined cannot remove an existing callback or restore automatic presentation. Recreate the instance to change back to an omitted callback or presentation. Recreate the instance to return to an omitted chat snapshot.

search.update({
  labels: {
    searchLabel: 'Search rewards',
    placeholder: 'Find a reward',
  },
  branding: {
    theme: {
      palette: { primary: '#0057b8' },
      colors: {
        partner: { primary: '#0057b8' },
        brand: { DEFAULT: '#0057b8', emphasis: '#003e83', muted: '#e6f0fa' },
      },
      headingFontFamily: 'Arial, sans-serif',
      bodyFontFamily: 'Arial, sans-serif',
      buttonRadius: 'rounded',
      headerTone: 'on-light',
    },
  },
});

SearchThemeOverride is the design system's partner theme input plus headerTone. Set the partner color as palette.primary or colors.partner.primary. Either form is enough. A hex value seeds the brand ramp. Omit branding.theme to keep Augeo defaults. Explicit brandRamp, brandRoles, brandRolesDark, brandOnPrimary, brandOnPrimaryDark, typography, and radius values win over derived ones. On an on-dark header, the Ask AI label and sparkle use the resolved partner-readable foreground. Changing only the primary fill does not set that color. headerTone is search-bar presentation and is not passed to theme resolution. It also supports surface, text, border, feedback, accent, and partner color groups. Heading weights are regular, medium, semi-bold, or bold. Radius accepts sharp, default, soft, rounded, or pixel, rem, and percentage strings. headerTone matches the closed search bar to the header behind it: on-dark (default) for a dark or brand-colored header, on-light for a white one. Unknown values fall back to on-dark. The closed search bar fills the width of its parent, and the open overlay matches the field and Ask AI button together. The SDK includes its own Shadow DOM styling and reset. Load any custom font resources on the host page before selecting those font families.

Program chat availability

The host owns this snapshot. Pass the same value to Search and to other chat consumers. Do not infer it from onAskAi, an assistant, or a token. Chat authorization stays independent. 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. Do not add an entitlement endpoint.

programId is the program id, not a catalog id. authScopeKey is an opaque host generation, never a bearer token. Change that key on logout, member replacement, or an authorization-scope change. Keep the key when only the token rotates. A new token alone is not enabled.

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

Supply enabled, disabled, or unresolved for a new integration. Omission cannot satisfy host acceptance. Explicit unresolved never restores legacy chat. Validation accepts a non-array record and those exact status strings. Enabled and disabled require nonblank programId and authScopeKey. Unresolved may use scope: null. Booleans, numbers, and string booleans are rejected. Invalid input is non-chat and has no usable scope. The SDK copies known fields. A host cannot set origin.

Same-scope updates may move among all three statuses. They do not remount the widget. Activation reads the latest snapshot, including on an open panel. A downgrade routes the next generated row to ordinary search. An already completed chat handoff is not revoked. The first valid non-null scope binds the instance. A different non-null scope does not enable that program in place. Publish unresolved, cancel pending search work, and destroy the instance. Replace the credential scope, then create a new instance with the new snapshot. A null unresolved update keeps the original binding. Destroyed instances ignore later updates. Mount Search when chat is disabled. Do not require the chat bundle for that program.

Standalone declarations inline this type. Do not import chat or common-ui to pass it. A one-argument onSearchSubmit remains valid.

import type { ProgramChatAvailability, ProgramChatScope } from './vendor/search-sdk/index';

declare function currentProgramScope(): ProgramChatScope;

const disabledChat: ProgramChatAvailability = {
  status: 'disabled',
  scope: currentProgramScope(),
};

search.update({ capabilities: { programChat: disabledChat } });

currentProgramScope is your host accessor. search is the instance from creation. That update does not replace analytics adapters.

Host analytics

capabilities.analytics is optional and read only by createAugeoSearch. Omitting it publishes nothing to a destination. Search still dispatches augeo.event on the widget root. The runtime subscribes on that root only. Do not add a document or window listener. That listener also sees chat events and would send them again.

FieldDefaultBehavior
adaptersrequiredHost writers with id and send. The SDK does not load gtag
mappingunsetDestination names and params. A null event drops the name
identityunsetOptional userId accessor for mapping. It is not copied onto the bus event
consentomitted, treated as grantedgranted, denied, callback, cookie, or localStorage
allowunset, unrestrictedGlob list. Set it to the host mapping's event keys
denyunsetGlob list. A match declines even when allow also matches
classesmeasuredmeasured and/or observed. An empty list stays measured
enrichunsetExtra mapping context. It does not mutate the bus event
onDeclineunsetCalled with the event and a decline reason when a write is skipped

Derive allow from the mapping keys you populated. The SDK does not turn mapping keys into an allow list. Unmapped measured names stay off the wire only when allow lists those keys. A name outside allow declines as not_allowlisted and does not call send. readCachedBearer returns the cached THEO bearer, not the Kigo member token.

const target = document.getElementById('search-host');
if (!target) throw new Error('Search mount container is missing.');
const mapping = {
  events: {
    'com.augeo.conversation.launcher.activated': {
      event: 'theo_launcher_activated',
      params: { activation_source: { from: 'data.occurrence.activationSource' } },
    },
    'com.augeo.conversation.launcher.viewed': {
      event: 'theo_launcher_viewed',
    },
    'com.augeo.engagement.search.submitted': {
      event: 'search_submitted',
    },
    'com.augeo.engagement.search.performed': {
      event: 'search_performed',
      params: {
        page: { from: 'data.occurrence.page' },
        result_count: { from: 'data.occurrence.resultCount' },
        outcome: { from: 'data.occurrence.outcome' },
      },
    },
  },
};
const search = window.AugeoSearchSdk.createAugeoSearch({
  target,
  auth: { getToken: () => readCachedBearer() },
  capabilities: {
    analytics: {
      adapters: [
        {
          id: 'gtag',
          ready: () => typeof window.gtag === 'function',
          send(dispatch) {
            window.gtag('event', dispatch.mapped.event, dispatch.mapped.params);
          },
        },
      ],
      mapping,
      allow: Object.keys(mapping.events),
    },
  },
});

Do not map data.occurrence.keyword into a destination param. The bus event still carries the sanitized keyword. Add com.augeo.engagement.search.submitted to allow to forward automatic submission counts. Include com.augeo.engagement.search.performed separately when you also track confirmed results. Forwarding uses this same root listener. Do not add a second document listener for search measurement.

Call gtag('event', name, params) with no send_to. The page's existing measurement ids then receive the event. Do not change that tag configuration in the host template.

An older search bundle ignores capabilities and still mounts. A newer bundle that is created without capabilities.analytics stays event-bus only. A bundle that accepts capabilities.programChat still mounts when that field is omitted. Destroy and create a new instance to change adapters.

Storefront mount

In mountAugeoSearch, pass the storefront's existing host capability. Include the submitted event in the shared mapping and allow list when forwarding submission counts. That factory already derives allow from mapping keys whose destination event is non-null, and its gtag adapter already omits send_to.

import { analyticsCapability } from './host/analytics';

capabilities: { analytics: analyticsCapability() },

Do not add a document-level augeo.event listener in that mount. Chat already forwards its own root. A second listener would send those events again. That snippet omits programChat and therefore keeps legacy presentation. Pass the resolved snapshot beside analytics for a new integration.

TypeScript hosts

The SDK source includes a standalone types/index.d.ts; the build emits the same declarations beside the local IIFE. Obtain that file from the source distribution matching your chosen release. Save it as vendor/search-sdk/index.d.ts in your host project. Use a type-only import; the runtime still comes from the script tag.

host-project/
  vendor/search-sdk/index.d.ts
  search-host.ts
import type { AugeoSearchInstance, CreateAugeoSearchOptions } from './vendor/search-sdk/index';

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

const options: CreateAugeoSearchOptions = {
  target,
  auth: { getToken: () => readCachedBearer() },
  open: false,
  onOpenChange: (open) => search.update({ open }),
};
const search: AugeoSearchInstance = window.AugeoSearchSdk.createAugeoSearch(options);

readCachedBearer returns the cached THEO bearer, not the Kigo member token.

import type {
  SearchExecution,
  SearchPresentedResults,
  SearchSubmitHandler,
} from './vendor/search-sdk/index';

const pending = new Map<string, SearchExecution>();

const onSearchSubmit: SearchSubmitHandler = (
  query: string,
  execution: SearchExecution,
) => {
  pending.set(execution.id, execution);
  void query;
};

function onViewCommit(executionId: string, displayedCount: number): void {
  const execution = pending.get(executionId);
  if (!execution) return;
  const facts: SearchPresentedResults = {
    page: 1,
    resultCount: displayedCount,
  };
  pending.delete(executionId);
  try {
    execution.presented(facts);
  } catch (error) {
    pending.set(executionId, execution);
    throw error;
  }
}

Call onViewCommit from the committed products or empty state. Release the active handle before calling presented. If presented throws, keep that handle and correct the facts. Do not call presented from the submit callback. Keep query for the request and route. One-argument handlers remain assignable to SearchSubmitHandler. The declarations include the window global and custom-element tag mapping. The CDN deployment publishes JavaScript; it does not publish a declarations download or installable npm package. Do not import createAugeoSearch as a JavaScript export from the declarations.

packages/chat-sdk/harness/kigo-auth/README.md