@tensorpass/aiconnect 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.js +2 -1
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mcpToolSource.d.ts +6 -1
- package/dist/mcpToolSource.js +7 -2
- package/dist/mcpToolSource.js.map +1 -1
- package/dist/visitorBrowser.d.ts +17 -1
- package/dist/visitorBrowser.js +26 -4
- package/dist/visitorBrowser.js.map +1 -1
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -58,7 +58,8 @@ export class AiConnect {
|
|
|
58
58
|
get browser() {
|
|
59
59
|
return visitorBrowser();
|
|
60
60
|
}
|
|
61
|
-
// Where a visitor without the wallet adds it to this browser,
|
|
61
|
+
// Where a visitor without the wallet adds it to this browser, its store listing or the wallet's page, for
|
|
62
|
+
// the connect window's link.
|
|
62
63
|
get installUrl() {
|
|
63
64
|
return walletInstallUrl(this.browser);
|
|
64
65
|
}
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,iGAAiG;AACjG,gGAAgG;AAChG,kGAAkG;AAClG,0FAA0F;AAC1F,yGAAyG;AACzG,wGAAwG;AACxG,iFAAiF;AACjF,kFAAkF;AAIlF,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAErE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAIrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAoBnE,MAAM,WAAW,GAAG,UAAU,CAAC;AAE/B,oFAAoF;AACpF,MAAM,Q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AAK,CAAC,MAAM,EAAE,IAAkB,CAAC,CAAC;IACzC,CAAC;IAEO,UAAU;QAChB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;IAClC,CAAC;IAEO,UAAU;QAChB,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,MAAsB,EAAE,IAAgB;QACpD,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC;YAC1C,OAAO;QACT,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC;YACZ,MAAM,EAAE,WAAW;YACnB,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,OAAO,EAAE,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC;SACrC,CAAC,CAAC;IACL,CAAC;IAEO,QAAQ,CAAC,KAAsB;QACrC,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACtC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;CACF","sourcesContent":["// A site's connection to the visitor's AI, through the AI Wallet extension that holds the visitor's\n// accounts. The site asks the wallet to connect, and the wallet asks the visitor the first time;\n// the site then chats through the wallet, which answers with the account the visitor picked for\n// this site. The site never sees a credential. A site the visitor approved connects on its own on\n// later visits, and its state follows the account the visitor picks for it in the wallet.\n// In a browser without the wallet, the visitor can sign in on the page to OpenRouter, or to TensorPass's\n// plan when the site gave its site key (see webAccounts/webAccountSource.ts). The credential of such an\n// account lives in the site's own storage, where the site's scripts can read it.\n// `fetch` lets the AI SDK a site already uses answer through the same connection.\n\nimport type { ConnectionState } from './connectionState.ts';\nimport type { ChatRequest, ChatResponse, ProviderSession, WalletLink } from './types.ts';\nimport { findWallet, WalletRequestError } from './walletProvider.ts';\nimport type { ChatEvent, WalletChatParams, WalletProvider, WalletRefusal } from './walletProvider.ts';\nimport { visitorBrowser, walletInstallUrl } from './visitorBrowser.ts';\nimport type { VisitorBrowser } from './visitorBrowser.ts';\nimport { WebAccountSource } from './webAccounts/webAccountSource.ts';\nimport type { WebAccountOptions } from './webAccounts/webAccountSource.ts';\nimport type { PlanAccess } from './webAccounts/tensorPassPlan.ts';\nimport type { WebAccountId } from './webAccounts/webAccountStore.ts';\nimport { createWalletFetch } from './wireProtocols/walletFetch.ts';\nimport type { WalletFetch } from './wireProtocols/walletFetch.ts';\n\nexport type { ConnectionState, WebSignInFailure } from './connectionState.ts';\n\n// What a site sets on its client: its TensorPass site key, which offers the TensorPass plan's sign in to a\n// visitor without the wallet, and the models the web accounts answer with.\nexport type AiConnectOptions = WebAccountOptions;\n\n// The options an OpenAI or Anthropic SDK client takes to answer through the wallet. The SDKs\n// require an API key; the wallet never reads it, and the browser guard they keep for real keys\n// does not apply, since none reaches the page.\nexport interface SdkOptions {\n apiKey: string;\n fetch: WalletFetch;\n dangerouslyAllowBrowser: true;\n}\n\ntype Listener = (state: ConnectionState) => void;\n\nconst SDK_API_KEY = 'aiwallet';\n\n// The states a request waits through before it knows whether the site is connected.\nconst SETTLING = new Set<ConnectionState['status']>(['checking', 'connecting', 'signingIn']);\n\nconst NOT_CONNECTED: Record<string, string> = {\n noWallet: 'AI Wallet is not installed in this browser, and no account is signed in on this site',\n disconnected: 'AI Wallet is not connected on this site',\n};\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nconst REFUSALS = new Set<unknown>(['declined', 'closed', 'interrupted'] satisfies WalletRefusal[]);\n\n// The error state of a connection that did not go through, with the reason the wallet gave. The\n// error comes from the wallet's own copy of `WalletRequestError`, so its reason is read as a field.\nfunction connectError(error: unknown): ConnectionState {\n const reason = (error as { reason?: unknown } | null)?.reason;\n return {\n status: 'error',\n message: errorMessage(error),\n ...(REFUSALS.has(reason) ? { reason: reason as WalletRefusal } : {}),\n };\n}\n\n// Hands each event the wallet streams to the request's hook for it.\nfunction chatListener(request: ChatRequest): (event: ChatEvent) => void {\n return (event) => {\n if (event.kind === 'start') {\n request.onStart?.({ providerName: event.providerName, model: event.model });\n } else {\n request.onText?.(event.delta);\n }\n };\n}\n\nfunction walletSession(wallet: WalletProvider, link: Extract<WalletLink, { connected: true }>): ProviderSession {\n return {\n providerId: 'aiwallet',\n model: link.model ?? '',\n chat: async (request) => {\n const params: WalletChatParams = { messages: request.messages, tools: request.tools, options: request.options };\n return (await wallet.request('chat', params, chatListener(request), request.signal)) as ChatResponse;\n },\n };\n}\n\nexport class AiConnect {\n // The visitor's browser, which names the install button.\n get browser(): VisitorBrowser {\n return visitorBrowser();\n }\n\n // Where a visitor without the wallet adds it to this browser, for the connect window's link.\n get installUrl(): string {\n return walletInstallUrl(this.browser);\n }\n\n // A `fetch` for the AI SDKs: it answers their requests through the wallet, in their own protocol.\n readonly fetch: WalletFetch = createWalletFetch(() => this.connectedSession());\n readonly sdkOptions: SdkOptions = { apiKey: SDK_API_KEY, fetch: this.fetch, dangerouslyAllowBrowser: true };\n private readonly listeners = new Set<Listener>();\n private current: ConnectionState = { status: 'checking' };\n private wallet: Promise<WalletProvider | null> | null = null;\n private readonly web: WebAccountSource;\n // Set once the page knows the wallet is missing: the web accounts then make the state.\n private walletMissing = false;\n\n constructor(options: AiConnectOptions = {}) {\n this.web = new WebAccountSource({ options, onChange: () => this.webChanged() });\n // A client built during a server render stays in the checking state, and so does a sign in's popup,\n // which hands its answer to the page that opened it and closes.\n if (typeof window !== 'undefined' && this.web.takeCallback() !== 'window') {\n this.reconnect();\n }\n }\n\n // The accounts a visitor without the wallet can sign in to on this site: TensorPass with a site key,\n // then OpenRouter.\n get webAccounts(): WebAccountId[] {\n return this.web.ids;\n }\n\n // Signs the visitor in to a web account in a popup, or in the page where the browser blocks popups. Call\n // it from the visitor's click. The state goes through `signingIn` to `connected`, or back to `noWallet`\n // with the reason the sign in failed.\n signIn(account: WebAccountId): Promise<void> {\n return this.web.signIn(account);\n }\n\n cancelSignIn(): void {\n this.web.cancel();\n }\n\n // The TensorPass plan of the web account that answers, for the chat's offer to subscribe when the account\n // has no plan yet; null for any other account.\n planAccess(): PlanAccess | null {\n return this.web.planAccess();\n }\n\n // Removes the web account's credential from the site's storage, and ends a TensorPass sign in.\n signOut(): Promise<void> {\n return this.web.signOut();\n }\n\n get state(): ConnectionState {\n return this.current;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n // Asks the wallet to let this site use the visitor's AI. The wallet asks the visitor the first time.\n async connect(): Promise<void> {\n const wallet = await this.findWallet();\n if (!wallet) {\n this.walletGone();\n return;\n }\n this.setState({ status: 'connecting' });\n try {\n this.apply(wallet, (await wallet.request('connect')) as WalletLink);\n } catch (error) {\n this.setState(connectError(error));\n }\n }\n\n // Disconnects the wallet from this site, or signs the visitor out of the web account that answers.\n async disconnect(): Promise<void> {\n if (this.current.status === 'connected' && this.current.account) {\n await this.signOut();\n return;\n }\n const wallet = await this.findWallet();\n await wallet?.request('disconnect');\n if (wallet) {\n this.setState({ status: 'disconnected' });\n } else {\n this.walletGone();\n }\n }\n\n // The session of the connected site, once the status check or the visitor's approval is over.\n private async connectedSession(): Promise<ProviderSession> {\n if (typeof window === 'undefined') {\n throw new WalletRequestError('AI Wallet answers in the browser only', 401);\n }\n const state = await this.settled();\n if (state.status === 'connected') {\n return state.session;\n }\n throw new WalletRequestError(state.status === 'error' ? state.message : NOT_CONNECTED[state.status], 401);\n }\n\n private settled(): Promise<ConnectionState> {\n if (!SETTLING.has(this.current.status)) {\n return Promise.resolve(this.current);\n }\n return new Promise((resolve) => {\n const unsubscribe = this.subscribe((state) => {\n if (!SETTLING.has(state.status)) {\n unsubscribe();\n resolve(state);\n }\n });\n });\n }\n\n private findWallet(): Promise<WalletProvider | null> {\n this.wallet ??= findWallet().then((wallet) => {\n wallet?.onLink((link) => this.apply(wallet, link));\n return wallet;\n });\n return this.wallet;\n }\n\n // A site the visitor already approved connects without asking anything.\n private async reconnect(): Promise<void> {\n const wallet = await this.findWallet();\n if (!wallet) {\n this.walletGone();\n return;\n }\n const link = await wallet.request('status').catch((): WalletLink => ({ connected: false }));\n this.apply(wallet, link as WalletLink);\n }\n\n private walletGone(): void {\n this.walletMissing = true;\n this.setState(this.web.state());\n }\n\n private webChanged(): void {\n if (this.walletMissing) {\n this.setState(this.web.state());\n }\n }\n\n private apply(wallet: WalletProvider, link: WalletLink): void {\n if (!link.connected) {\n this.setState({ status: 'disconnected' });\n return;\n }\n this.setState({\n status: 'connected',\n providerName: link.providerName,\n model: link.model,\n session: walletSession(wallet, link),\n });\n }\n\n private setState(state: ConnectionState): void {\n this.current = state;\n for (const listener of this.listeners) {\n listener(state);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,iGAAiG;AACjG,gGAAgG;AAChG,kGAAkG;AAClG,0FAA0F;AAC1F,yGAAyG;AACzG,wGAAwG;AACxG,iFAAiF;AACjF,kFAAkF;AAIlF,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAErE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAIrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAoBnE,MAAM,WAAW,GAAG,UAAU,CAAC;AAE/B,oFAAoF;AACpF,MAAM,QAAQ,GAAG,IAAI,GAAG,CA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MAAM,EAAE,IAAkB,CAAC,CAAC;IACzC,CAAC;IAEO,UAAU;QAChB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;IAClC,CAAC;IAEO,UAAU;QAChB,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,MAAsB,EAAE,IAAgB;QACpD,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC;YAC1C,OAAO;QACT,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC;YACZ,MAAM,EAAE,WAAW;YACnB,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,OAAO,EAAE,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC;SACrC,CAAC,CAAC;IACL,CAAC;IAEO,QAAQ,CAAC,KAAsB;QACrC,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACtC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;CACF","sourcesContent":["// A site's connection to the visitor's AI, through the AI Wallet extension that holds the visitor's\n// accounts. The site asks the wallet to connect, and the wallet asks the visitor the first time;\n// the site then chats through the wallet, which answers with the account the visitor picked for\n// this site. The site never sees a credential. A site the visitor approved connects on its own on\n// later visits, and its state follows the account the visitor picks for it in the wallet.\n// In a browser without the wallet, the visitor can sign in on the page to OpenRouter, or to TensorPass's\n// plan when the site gave its site key (see webAccounts/webAccountSource.ts). The credential of such an\n// account lives in the site's own storage, where the site's scripts can read it.\n// `fetch` lets the AI SDK a site already uses answer through the same connection.\n\nimport type { ConnectionState } from './connectionState.ts';\nimport type { ChatRequest, ChatResponse, ProviderSession, WalletLink } from './types.ts';\nimport { findWallet, WalletRequestError } from './walletProvider.ts';\nimport type { ChatEvent, WalletChatParams, WalletProvider, WalletRefusal } from './walletProvider.ts';\nimport { visitorBrowser, walletInstallUrl } from './visitorBrowser.ts';\nimport type { VisitorBrowser } from './visitorBrowser.ts';\nimport { WebAccountSource } from './webAccounts/webAccountSource.ts';\nimport type { WebAccountOptions } from './webAccounts/webAccountSource.ts';\nimport type { PlanAccess } from './webAccounts/tensorPassPlan.ts';\nimport type { WebAccountId } from './webAccounts/webAccountStore.ts';\nimport { createWalletFetch } from './wireProtocols/walletFetch.ts';\nimport type { WalletFetch } from './wireProtocols/walletFetch.ts';\n\nexport type { ConnectionState, WebSignInFailure } from './connectionState.ts';\n\n// What a site sets on its client: its TensorPass site key, which offers the TensorPass plan's sign in to a\n// visitor without the wallet, and the models the web accounts answer with.\nexport type AiConnectOptions = WebAccountOptions;\n\n// The options an OpenAI or Anthropic SDK client takes to answer through the wallet. The SDKs\n// require an API key; the wallet never reads it, and the browser guard they keep for real keys\n// does not apply, since none reaches the page.\nexport interface SdkOptions {\n apiKey: string;\n fetch: WalletFetch;\n dangerouslyAllowBrowser: true;\n}\n\ntype Listener = (state: ConnectionState) => void;\n\nconst SDK_API_KEY = 'aiwallet';\n\n// The states a request waits through before it knows whether the site is connected.\nconst SETTLING = new Set<ConnectionState['status']>(['checking', 'connecting', 'signingIn']);\n\nconst NOT_CONNECTED: Record<string, string> = {\n noWallet: 'AI Wallet is not installed in this browser, and no account is signed in on this site',\n disconnected: 'AI Wallet is not connected on this site',\n};\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nconst REFUSALS = new Set<unknown>(['declined', 'closed', 'interrupted'] satisfies WalletRefusal[]);\n\n// The error state of a connection that did not go through, with the reason the wallet gave. The\n// error comes from the wallet's own copy of `WalletRequestError`, so its reason is read as a field.\nfunction connectError(error: unknown): ConnectionState {\n const reason = (error as { reason?: unknown } | null)?.reason;\n return {\n status: 'error',\n message: errorMessage(error),\n ...(REFUSALS.has(reason) ? { reason: reason as WalletRefusal } : {}),\n };\n}\n\n// Hands each event the wallet streams to the request's hook for it.\nfunction chatListener(request: ChatRequest): (event: ChatEvent) => void {\n return (event) => {\n if (event.kind === 'start') {\n request.onStart?.({ providerName: event.providerName, model: event.model });\n } else {\n request.onText?.(event.delta);\n }\n };\n}\n\nfunction walletSession(wallet: WalletProvider, link: Extract<WalletLink, { connected: true }>): ProviderSession {\n return {\n providerId: 'aiwallet',\n model: link.model ?? '',\n chat: async (request) => {\n const params: WalletChatParams = { messages: request.messages, tools: request.tools, options: request.options };\n return (await wallet.request('chat', params, chatListener(request), request.signal)) as ChatResponse;\n },\n };\n}\n\nexport class AiConnect {\n // The visitor's browser, which names the install button.\n get browser(): VisitorBrowser {\n return visitorBrowser();\n }\n\n // Where a visitor without the wallet adds it to this browser, its store listing or the wallet's page, for\n // the connect window's link.\n get installUrl(): string {\n return walletInstallUrl(this.browser);\n }\n\n // A `fetch` for the AI SDKs: it answers their requests through the wallet, in their own protocol.\n readonly fetch: WalletFetch = createWalletFetch(() => this.connectedSession());\n readonly sdkOptions: SdkOptions = { apiKey: SDK_API_KEY, fetch: this.fetch, dangerouslyAllowBrowser: true };\n private readonly listeners = new Set<Listener>();\n private current: ConnectionState = { status: 'checking' };\n private wallet: Promise<WalletProvider | null> | null = null;\n private readonly web: WebAccountSource;\n // Set once the page knows the wallet is missing: the web accounts then make the state.\n private walletMissing = false;\n\n constructor(options: AiConnectOptions = {}) {\n this.web = new WebAccountSource({ options, onChange: () => this.webChanged() });\n // A client built during a server render stays in the checking state, and so does a sign in's popup,\n // which hands its answer to the page that opened it and closes.\n if (typeof window !== 'undefined' && this.web.takeCallback() !== 'window') {\n this.reconnect();\n }\n }\n\n // The accounts a visitor without the wallet can sign in to on this site: TensorPass with a site key,\n // then OpenRouter.\n get webAccounts(): WebAccountId[] {\n return this.web.ids;\n }\n\n // Signs the visitor in to a web account in a popup, or in the page where the browser blocks popups. Call\n // it from the visitor's click. The state goes through `signingIn` to `connected`, or back to `noWallet`\n // with the reason the sign in failed.\n signIn(account: WebAccountId): Promise<void> {\n return this.web.signIn(account);\n }\n\n cancelSignIn(): void {\n this.web.cancel();\n }\n\n // The TensorPass plan of the web account that answers, for the chat's offer to subscribe when the account\n // has no plan yet; null for any other account.\n planAccess(): PlanAccess | null {\n return this.web.planAccess();\n }\n\n // Removes the web account's credential from the site's storage, and ends a TensorPass sign in.\n signOut(): Promise<void> {\n return this.web.signOut();\n }\n\n get state(): ConnectionState {\n return this.current;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n // Asks the wallet to let this site use the visitor's AI. The wallet asks the visitor the first time.\n async connect(): Promise<void> {\n const wallet = await this.findWallet();\n if (!wallet) {\n this.walletGone();\n return;\n }\n this.setState({ status: 'connecting' });\n try {\n this.apply(wallet, (await wallet.request('connect')) as WalletLink);\n } catch (error) {\n this.setState(connectError(error));\n }\n }\n\n // Disconnects the wallet from this site, or signs the visitor out of the web account that answers.\n async disconnect(): Promise<void> {\n if (this.current.status === 'connected' && this.current.account) {\n await this.signOut();\n return;\n }\n const wallet = await this.findWallet();\n await wallet?.request('disconnect');\n if (wallet) {\n this.setState({ status: 'disconnected' });\n } else {\n this.walletGone();\n }\n }\n\n // The session of the connected site, once the status check or the visitor's approval is over.\n private async connectedSession(): Promise<ProviderSession> {\n if (typeof window === 'undefined') {\n throw new WalletRequestError('AI Wallet answers in the browser only', 401);\n }\n const state = await this.settled();\n if (state.status === 'connected') {\n return state.session;\n }\n throw new WalletRequestError(state.status === 'error' ? state.message : NOT_CONNECTED[state.status], 401);\n }\n\n private settled(): Promise<ConnectionState> {\n if (!SETTLING.has(this.current.status)) {\n return Promise.resolve(this.current);\n }\n return new Promise((resolve) => {\n const unsubscribe = this.subscribe((state) => {\n if (!SETTLING.has(state.status)) {\n unsubscribe();\n resolve(state);\n }\n });\n });\n }\n\n private findWallet(): Promise<WalletProvider | null> {\n this.wallet ??= findWallet().then((wallet) => {\n wallet?.onLink((link) => this.apply(wallet, link));\n return wallet;\n });\n return this.wallet;\n }\n\n // A site the visitor already approved connects without asking anything.\n private async reconnect(): Promise<void> {\n const wallet = await this.findWallet();\n if (!wallet) {\n this.walletGone();\n return;\n }\n const link = await wallet.request('status').catch((): WalletLink => ({ connected: false }));\n this.apply(wallet, link as WalletLink);\n }\n\n private walletGone(): void {\n this.walletMissing = true;\n this.setState(this.web.state());\n }\n\n private webChanged(): void {\n if (this.walletMissing) {\n this.setState(this.web.state());\n }\n }\n\n private apply(wallet: WalletProvider, link: WalletLink): void {\n if (!link.connected) {\n this.setState({ status: 'disconnected' });\n return;\n }\n this.setState({\n status: 'connected',\n providerName: link.providerName,\n model: link.model,\n session: walletSession(wallet, link),\n });\n }\n\n private setState(state: ConnectionState): void {\n this.current = state;\n for (const listener of this.listeners) {\n listener(state);\n }\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,8 +4,9 @@ export { AiConnect } from './client.ts';
|
|
|
4
4
|
export type { AiConnectOptions, ConnectionState, SdkOptions, WebSignInFailure } from './client.ts';
|
|
5
5
|
export * from './guards/index.ts';
|
|
6
6
|
export { McpToolSource } from './mcpToolSource.ts';
|
|
7
|
-
export {
|
|
8
|
-
export
|
|
7
|
+
export type { McpFetch, McpToolSourceOptions } from './mcpToolSource.ts';
|
|
8
|
+
export { BROWSER_NAMES, browserOf, visitorBrowser, walletInstallUrl, walletStore, WALLET_STORES, } from './visitorBrowser.ts';
|
|
9
|
+
export type { BrowserSignals, VisitorBrowser, WalletStore } from './visitorBrowser.ts';
|
|
9
10
|
export { finalAnswer, runConversation } from './toolLoop.ts';
|
|
10
11
|
export type { ConversationHooks, ConversationOptions } from './toolLoop.ts';
|
|
11
12
|
export type * from './types.ts';
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ export { contentParts, dataUrl, inlineData, textOf } from "./chatContent.js";
|
|
|
6
6
|
export { AiConnect } from "./client.js";
|
|
7
7
|
export * from "./guards/index.js";
|
|
8
8
|
export { McpToolSource } from "./mcpToolSource.js";
|
|
9
|
-
export { BROWSER_NAMES, browserOf, visitorBrowser, walletInstallUrl } from "./visitorBrowser.js";
|
|
9
|
+
export { BROWSER_NAMES, browserOf, visitorBrowser, walletInstallUrl, walletStore, WALLET_STORES, } from "./visitorBrowser.js";
|
|
10
10
|
export { finalAnswer, runConversation } from "./toolLoop.js";
|
|
11
11
|
export { WalletRequestError } from "./walletProvider.js";
|
|
12
12
|
export { finishSignIn } from "./webAccounts/finishSignIn.js";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,2GAA2G;AAC3G,6GAA6G;AAC7G,wDAAwD;AAExD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE7E,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,2GAA2G;AAC3G,6GAA6G;AAC7G,wDAAwD;AAExD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE7E,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EACL,aAAa,EAAE,SAAS,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,GACvF,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAG7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAGzD,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAE7D,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAGlE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC","sourcesContent":["// The site's side of AI Connect: the connection to the visitor's AI through the AI Wallet or, without it,\n// through an account the visitor signs in to on the page, the conversation loop that runs the site's tools\n// under the chat's guards, the site's tools read from its MCP server, and the `fetch` that lets the AI SDK a\n// site already uses answer through the same connection.\n\nexport { contentParts, dataUrl, inlineData, textOf } from './chatContent.ts';\nexport type { InlineData } from './chatContent.ts';\nexport { AiConnect } from './client.ts';\nexport type { AiConnectOptions, ConnectionState, SdkOptions, WebSignInFailure } from './client.ts';\nexport * from './guards/index.ts';\nexport { McpToolSource } from './mcpToolSource.ts';\nexport type { McpFetch, McpToolSourceOptions } from './mcpToolSource.ts';\nexport {\n BROWSER_NAMES, browserOf, visitorBrowser, walletInstallUrl, walletStore, WALLET_STORES,\n} from './visitorBrowser.ts';\nexport type { BrowserSignals, VisitorBrowser, WalletStore } from './visitorBrowser.ts';\nexport { finalAnswer, runConversation } from './toolLoop.ts';\nexport type { ConversationHooks, ConversationOptions } from './toolLoop.ts';\nexport type * from './types.ts';\nexport { WalletRequestError } from './walletProvider.ts';\nexport type { ChatEvent, WalletChatParams, WalletProvider, WalletRefusal } from './walletProvider.ts';\nexport type { WalletFetch } from './wireProtocols/walletFetch.ts';\nexport { finishSignIn } from './webAccounts/finishSignIn.ts';\nexport type { SignInReturn } from './webAccounts/finishSignIn.ts';\nexport { isSignInReturn } from './webAccounts/signInWindow.ts';\nexport { PLAN_GATEWAY } from './webAccounts/tensorPassAccount.ts';\nexport type { PlanAccess, PlanOffer, PlanPrice, PlanSubscription } from './webAccounts/tensorPassPlan.ts';\nexport type { PlanLevel } from './webAccounts/tensorPassAccount.ts';\nexport { WEB_ACCOUNT_NAMES } from './webAccounts/webAccount.ts';\nexport type { WebAccountId } from './webAccounts/webAccountStore.ts';\n"]}
|
package/dist/mcpToolSource.d.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import type { ToolDefinition, ToolSource } from './types.ts';
|
|
2
|
+
export type McpFetch = (url: string | URL, init?: RequestInit) => Promise<Response>;
|
|
3
|
+
export interface McpToolSourceOptions {
|
|
4
|
+
fetch?: McpFetch;
|
|
5
|
+
}
|
|
2
6
|
export declare class McpToolSource implements ToolSource {
|
|
3
7
|
private readonly url;
|
|
4
8
|
private readonly clientName;
|
|
9
|
+
private readonly fetch;
|
|
5
10
|
private client;
|
|
6
11
|
private definitions;
|
|
7
|
-
constructor(url: string | URL, clientName?: string);
|
|
12
|
+
constructor(url: string | URL, clientName?: string, options?: McpToolSourceOptions);
|
|
8
13
|
private connected;
|
|
9
14
|
private connect;
|
|
10
15
|
listTools(): Promise<ToolDefinition[]>;
|
package/dist/mcpToolSource.js
CHANGED
|
@@ -2,15 +2,20 @@
|
|
|
2
2
|
// Claude or ChatGPT, so one tool catalog serves the in page AI mode and the provider apps. The client
|
|
3
3
|
// asks the server which protocol revision it serves: a server of the 2026-07-28 revision, such as a
|
|
4
4
|
// Mastra `MCPServer`, answers in it, and a server of the 2025 revisions gets the 2025 handshake.
|
|
5
|
+
// A request from the page carries the site's cookies, so a site whose login is a cookie needs no
|
|
6
|
+
// option. A site whose login is a token the page sends itself, such as `Authorization: Bearer`,
|
|
7
|
+
// passes `fetch`, which adds it to each request.
|
|
5
8
|
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
|
|
6
9
|
export class McpToolSource {
|
|
7
10
|
url;
|
|
8
11
|
clientName;
|
|
12
|
+
fetch;
|
|
9
13
|
client = null;
|
|
10
14
|
definitions = null;
|
|
11
|
-
constructor(url, clientName = 'aiconnect') {
|
|
15
|
+
constructor(url, clientName = 'aiconnect', options = {}) {
|
|
12
16
|
this.url = new URL(url, globalThis.location?.href);
|
|
13
17
|
this.clientName = clientName;
|
|
18
|
+
this.fetch = options.fetch;
|
|
14
19
|
}
|
|
15
20
|
// The connection and the catalog are kept once read. A failed attempt is forgotten, so the next
|
|
16
21
|
// call asks the server again.
|
|
@@ -23,7 +28,7 @@ export class McpToolSource {
|
|
|
23
28
|
}
|
|
24
29
|
async connect() {
|
|
25
30
|
const client = new Client({ name: this.clientName, version: '0.1.0' }, { versionNegotiation: { mode: 'auto' } });
|
|
26
|
-
await client.connect(new StreamableHTTPClientTransport(this.url));
|
|
31
|
+
await client.connect(new StreamableHTTPClientTransport(this.url, { fetch: this.fetch }));
|
|
27
32
|
return client;
|
|
28
33
|
}
|
|
29
34
|
listTools() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcpToolSource.js","sourceRoot":"","sources":["../src/mcpToolSource.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,sGAAsG;AACtG,oGAAoG;AACpG,iGAAiG;
|
|
1
|
+
{"version":3,"file":"mcpToolSource.js","sourceRoot":"","sources":["../src/mcpToolSource.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,sGAAsG;AACtG,oGAAoG;AACpG,iGAAiG;AACjG,iGAAiG;AACjG,gGAAgG;AAChG,iDAAiD;AAEjD,OAAO,EAAE,MAAM,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAerF,MAAM,OAAO,aAAa;IACP,GAAG,CAAM;IACT,UAAU,CAAS;IACnB,KAAK,CAAuB;IACrC,MAAM,GAA2B,IAAI,CAAC;IACtC,WAAW,GAAqC,IAAI,CAAC;IAE7D,YAAY,GAAiB,EAAE,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I,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,EAAE,CAAC;QAC7D,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YAC1B,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,WAAW,IAAI,EAAE;YACnC,WAAW,EAAE,IAAI,CAAC,WAAW;SAC9B,CAAC,CAAC,CAAC;IACN,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,IAAY,EAAE,IAA6B;QACxD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACtC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAChE,MAAM,IAAI,GAAI,MAAM,CAAC,OAAyB;aAC3C,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;aACtC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;aACxB,IAAI,CAAC,IAAI,CAAC,CAAC;QACd,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACvD,CAAC;CACF","sourcesContent":["// The site's tools, read from its own MCP server. The same server is the connector users add in\n// Claude or ChatGPT, so one tool catalog serves the in page AI mode and the provider apps. The client\n// asks the server which protocol revision it serves: a server of the 2026-07-28 revision, such as a\n// Mastra `MCPServer`, answers in it, and a server of the 2025 revisions gets the 2025 handshake.\n// A request from the page carries the site's cookies, so a site whose login is a cookie needs no\n// option. A site whose login is a token the page sends itself, such as `Authorization: Bearer`,\n// passes `fetch`, which adds it to each request.\n\nimport { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';\nimport type { ToolDefinition, ToolSource } from './types.ts';\n\n// The fetch the client sends its requests with, called with the server's address and the request.\nexport type McpFetch = (url: string | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface McpToolSourceOptions {\n fetch?: McpFetch;\n}\n\ninterface TextContent {\n type: string;\n text?: string;\n}\n\nexport class McpToolSource implements ToolSource {\n private readonly url: URL;\n private readonly clientName: string;\n private readonly fetch: McpFetch | undefined;\n private client: Promise<Client> | null = null;\n private definitions: Promise<ToolDefinition[]> | null = null;\n\n constructor(url: string | URL, clientName = 'aiconnect', options: McpToolSourceOptions = {}) {\n this.url = new URL(url, globalThis.location?.href);\n this.clientName = clientName;\n this.fetch = options.fetch;\n }\n\n // The connection and the catalog are kept once read. A failed attempt is forgotten, so the next\n // call asks the server again.\n private connected(): Promise<Client> {\n this.client ??= this.connect().catch((error: unknown) => {\n this.client = null;\n throw error;\n });\n return this.client;\n }\n\n private async connect(): Promise<Client> {\n const client = new Client({ name: this.clientName, version: '0.1.0' }, { versionNegotiation: { mode: 'auto' } });\n await client.connect(new StreamableHTTPClientTransport(this.url, { fetch: this.fetch }));\n return client;\n }\n\n listTools(): Promise<ToolDefinition[]> {\n this.definitions ??= this.readTools().catch((error: unknown) => {\n this.definitions = null;\n throw error;\n });\n return this.definitions;\n }\n\n private async readTools(): Promise<ToolDefinition[]> {\n const { tools } = await (await this.connected()).listTools();\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description ?? '',\n inputSchema: tool.inputSchema,\n }));\n }\n\n async callTool(name: string, args: Record<string, unknown>): Promise<string> {\n const client = await this.connected();\n const result = await client.callTool({ name, arguments: args });\n const text = (result.content as TextContent[])\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n return result.isError ? `Tool error: ${text}` : text;\n }\n}\n"]}
|
package/dist/visitorBrowser.d.ts
CHANGED
|
@@ -6,6 +6,20 @@ export interface BrowserSignals {
|
|
|
6
6
|
brave: boolean;
|
|
7
7
|
mobile: boolean;
|
|
8
8
|
}
|
|
9
|
+
export interface WalletStore {
|
|
10
|
+
name: string;
|
|
11
|
+
url: string;
|
|
12
|
+
}
|
|
13
|
+
export declare const WALLET_STORES: {
|
|
14
|
+
readonly chromeWebStore: {
|
|
15
|
+
readonly name: "Chrome Web Store";
|
|
16
|
+
readonly url: "https://chromewebstore.google.com/detail/ai-wallet/gkmgamdkmlidbjfmheeghkcjdofdafge";
|
|
17
|
+
};
|
|
18
|
+
readonly firefoxAddOns: {
|
|
19
|
+
readonly name: "Firefox Add-ons";
|
|
20
|
+
readonly url: "https://addons.mozilla.org/en-US/firefox/addon/ai-wallet/";
|
|
21
|
+
};
|
|
22
|
+
};
|
|
9
23
|
/**
|
|
10
24
|
* The browser the signals describe. Safari is named on a Mac, an iPhone and an iPad, where the wallet runs
|
|
11
25
|
* in it; any other browser of a phone or a tablet, or a browser the wallet does not name, is `other`.
|
|
@@ -13,5 +27,7 @@ export interface BrowserSignals {
|
|
|
13
27
|
export declare function browserOf({ userAgent, brands, brave, mobile }: BrowserSignals): VisitorBrowser;
|
|
14
28
|
/** The browser this page runs in, or `other` where there is no browser, as on a server. */
|
|
15
29
|
export declare function visitorBrowser(): VisitorBrowser;
|
|
16
|
-
/**
|
|
30
|
+
/** The store that adds AI Wallet to `browser`, or null where no store lists it. */
|
|
31
|
+
export declare function walletStore(browser: VisitorBrowser): WalletStore | null;
|
|
32
|
+
/** Where a visitor on this browser adds AI Wallet: its store listing, or the wallet's page without one. */
|
|
17
33
|
export declare function walletInstallUrl(browser: VisitorBrowser): string;
|
package/dist/visitorBrowser.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The visitor's browser, which names the button that adds AI Wallet and picks where it installs from.
|
|
2
|
-
// This is the one place that knows where each browser gets the wallet:
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// This is the one place that knows where each browser gets the wallet: Chrome, Edge, Brave and Opera add it
|
|
3
|
+
// from its Chrome Web Store listing and Firefox from its Firefox Add-ons listing, public since 18 November
|
|
4
|
+
// 2026. Safari and the browsers of phones have no listing yet and go to the wallet's page.
|
|
5
5
|
// The browsers' own names, in Latin script in every language.
|
|
6
6
|
export const BROWSER_NAMES = {
|
|
7
7
|
chrome: 'Chrome',
|
|
@@ -12,6 +12,20 @@ export const BROWSER_NAMES = {
|
|
|
12
12
|
safari: 'Safari',
|
|
13
13
|
};
|
|
14
14
|
const WALLET_PAGE = 'https://tensorpass.app/wallet';
|
|
15
|
+
export const WALLET_STORES = {
|
|
16
|
+
chromeWebStore: {
|
|
17
|
+
name: 'Chrome Web Store',
|
|
18
|
+
url: 'https://chromewebstore.google.com/detail/ai-wallet/gkmgamdkmlidbjfmheeghkcjdofdafge',
|
|
19
|
+
},
|
|
20
|
+
firefoxAddOns: { name: 'Firefox Add-ons', url: 'https://addons.mozilla.org/en-US/firefox/addon/ai-wallet/' },
|
|
21
|
+
};
|
|
22
|
+
const STORE_OF = {
|
|
23
|
+
chrome: WALLET_STORES.chromeWebStore,
|
|
24
|
+
edge: WALLET_STORES.chromeWebStore,
|
|
25
|
+
brave: WALLET_STORES.chromeWebStore,
|
|
26
|
+
opera: WALLET_STORES.chromeWebStore,
|
|
27
|
+
firefox: WALLET_STORES.firefoxAddOns,
|
|
28
|
+
};
|
|
15
29
|
const MOBILE = /Mobi|Android|iPhone|iPad|iPod/;
|
|
16
30
|
// Safari's user agent, on a Mac as on an iPhone or an iPad, and the other browsers that carry Safari's
|
|
17
31
|
// tokens: Chromium's, Android's own, and the other browsers of iOS, which run on Safari's engine and take
|
|
@@ -65,8 +79,16 @@ export function visitorBrowser() {
|
|
|
65
79
|
mobile: nav.userAgentData?.mobile === true,
|
|
66
80
|
});
|
|
67
81
|
}
|
|
68
|
-
/**
|
|
82
|
+
/** The store that adds AI Wallet to `browser`, or null where no store lists it. */
|
|
83
|
+
export function walletStore(browser) {
|
|
84
|
+
return STORE_OF[browser] ?? null;
|
|
85
|
+
}
|
|
86
|
+
/** Where a visitor on this browser adds AI Wallet: its store listing, or the wallet's page without one. */
|
|
69
87
|
export function walletInstallUrl(browser) {
|
|
88
|
+
const store = walletStore(browser);
|
|
89
|
+
if (store) {
|
|
90
|
+
return store.url;
|
|
91
|
+
}
|
|
70
92
|
return browser === 'other' ? WALLET_PAGE : `${WALLET_PAGE}?browser=${browser}`;
|
|
71
93
|
}
|
|
72
94
|
//# sourceMappingURL=visitorBrowser.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"visitorBrowser.js","sourceRoot":"","sources":["../src/visitorBrowser.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,
|
|
1
|
+
{"version":3,"file":"visitorBrowser.js","sourceRoot":"","sources":["../src/visitorBrowser.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,4GAA4G;AAC5G,2GAA2G;AAC3G,2FAA2F;AAI3F,8DAA8D;AAC9D,MAAM,CAAC,MAAM,aAAa,GAAqD;IAC7E,MAAM,EAAE,QAAQ;IAChB,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,OAAO;IACd,KAAK,EAAE,OAAO;IACd,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;CACjB,CAAC;AAWF,MAAM,WAAW,GAAG,+BAA+B,CAAC;AAQpD,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,cAAc,EAAE;QACd,IAAI,EAAE,kBAAkB;QACxB,GAAG,EAAE,qFAAqF;KAC3F;IACD,aAAa,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,GAAG,EAAE,2DAA2D,EAAE;CAC9D,CAAC;AAEjD,MAAM,QAAQ,GAAiD;IAC7D,MAAM,EAAE,aAAa,CAAC,cAAc;IACpC,IAAI,EAAE,aAAa,CAAC,cAAc;IAClC,KAAK,EAAE,aAAa,CAAC,cAAc;IACnC,KAAK,EAAE,aAAa,CAAC,cAAc;IACnC,OAAO,EAAE,aAAa,CAAC,aAAa;CACrC,CAAC;AACF,MAAM,MAAM,GAAG,+BAA+B,CAAC;AAC/C,uGAAuG;AACvG,0GAA0G;AAC1G,gBAAgB;AAChB,MAAM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adds AI Wallet and picks where it installs from.\n// This is the one place that knows where each browser gets the wallet: Chrome, Edge, Brave and Opera add it\n// from its Chrome Web Store listing and Firefox from its Firefox Add-ons listing, public since 18 November\n// 2026. Safari and the browsers of phones have no listing yet and go to the wallet's page.\n\nexport type VisitorBrowser = 'chrome' | 'edge' | 'brave' | 'opera' | 'firefox' | 'safari' | 'other';\n\n// The browsers' own names, in Latin script in every language.\nexport const BROWSER_NAMES: Record<Exclude<VisitorBrowser, 'other'>, string> = {\n chrome: 'Chrome',\n edge: 'Edge',\n brave: 'Brave',\n opera: 'Opera',\n firefox: 'Firefox',\n safari: 'Safari',\n};\n\n// What a page can read of its browser: the user agent, the brands of `navigator.userAgentData` where the\n// browser gives them, Brave's own `navigator.brave`, and whether the device is a phone or a tablet.\nexport interface BrowserSignals {\n userAgent: string;\n brands: string[];\n brave: boolean;\n mobile: boolean;\n}\n\nconst WALLET_PAGE = 'https://tensorpass.app/wallet';\n\n// A store that lists AI Wallet, by the name it gives itself.\nexport interface WalletStore {\n name: string;\n url: string;\n}\n\nexport const WALLET_STORES = {\n chromeWebStore: {\n name: 'Chrome Web Store',\n url: 'https://chromewebstore.google.com/detail/ai-wallet/gkmgamdkmlidbjfmheeghkcjdofdafge',\n },\n firefoxAddOns: { name: 'Firefox Add-ons', url: 'https://addons.mozilla.org/en-US/firefox/addon/ai-wallet/' },\n} as const satisfies Record<string, WalletStore>;\n\nconst STORE_OF: Partial<Record<VisitorBrowser, WalletStore>> = {\n chrome: WALLET_STORES.chromeWebStore,\n edge: WALLET_STORES.chromeWebStore,\n brave: WALLET_STORES.chromeWebStore,\n opera: WALLET_STORES.chromeWebStore,\n firefox: WALLET_STORES.firefoxAddOns,\n};\nconst MOBILE = /Mobi|Android|iPhone|iPad|iPod/;\n// Safari's user agent, on a Mac as on an iPhone or an iPad, and the other browsers that carry Safari's\n// tokens: Chromium's, Android's own, and the other browsers of iOS, which run on Safari's engine and take\n// no extension.\nconst SAFARI = /\\bVersion\\/[\\d.]+.*\\bSafari\\//;\nconst NOT_SAFARI = /\\b(Chrome|Chromium|CriOS|FxiOS|EdgiOS|OPiOS)\\/|\\bAndroid\\b/;\n\n// The brand that names each Chromium browser in `userAgentData`, then the token of its user agent.\nconst CHROMIUM: { browser: VisitorBrowser; brand: string; token: RegExp }[] = [\n { browser: 'edge', brand: 'Microsoft Edge', token: /\\bEdg\\// },\n { browser: 'opera', brand: 'Opera', token: /\\bOPR\\// },\n { browser: 'brave', brand: 'Brave', token: /\\bBrave\\// },\n];\n\n/**\n * The browser the signals describe. Safari is named on a Mac, an iPhone and an iPad, where the wallet runs\n * in it; any other browser of a phone or a tablet, or a browser the wallet does not name, is `other`.\n */\nexport function browserOf({ userAgent, brands, brave, mobile }: BrowserSignals): VisitorBrowser {\n if (!brave && SAFARI.test(userAgent) && !NOT_SAFARI.test(userAgent)) {\n return 'safari';\n }\n if (mobile || MOBILE.test(userAgent)) {\n return 'other';\n }\n if (brave) {\n return 'brave';\n }\n const chromium = CHROMIUM.find(({ brand, token }) => brands.includes(brand) || token.test(userAgent));\n if (chromium) {\n return chromium.browser;\n }\n // Chromium itself, and the browsers built on it that name no brand of their own, install from the\n // Chrome Web Store as Chrome does.\n if (brands.includes('Google Chrome') || brands.includes('Chromium') || /\\bChrome\\//.test(userAgent)) {\n return /\\b(Vivaldi|YaBrowser|SamsungBrowser)\\//.test(userAgent) ? 'other' : 'chrome';\n }\n if (/\\bFirefox\\//.test(userAgent)) {\n return 'firefox';\n }\n return 'other';\n}\n\ninterface NavigatorSignals {\n userAgent?: string;\n userAgentData?: { brands?: { brand: string }[]; mobile?: boolean };\n brave?: unknown;\n}\n\n/** The browser this page runs in, or `other` where there is no browser, as on a server. */\nexport function visitorBrowser(): VisitorBrowser {\n const nav = (globalThis as { navigator?: NavigatorSignals }).navigator;\n if (!nav?.userAgent) {\n return 'other';\n }\n return browserOf({\n userAgent: nav.userAgent,\n brands: nav.userAgentData?.brands?.map((entry) => entry.brand) ?? [],\n brave: nav.brave !== undefined,\n mobile: nav.userAgentData?.mobile === true,\n });\n}\n\n/** The store that adds AI Wallet to `browser`, or null where no store lists it. */\nexport function walletStore(browser: VisitorBrowser): WalletStore | null {\n return STORE_OF[browser] ?? null;\n}\n\n/** Where a visitor on this browser adds AI Wallet: its store listing, or the wallet's page without one. */\nexport function walletInstallUrl(browser: VisitorBrowser): string {\n const store = walletStore(browser);\n if (store) {\n return store.url;\n }\n return browser === 'other' ? WALLET_PAGE : `${WALLET_PAGE}?browser=${browser}`;\n}\n"]}
|