@tensorpass/aiconnect-react 0.0.0-stage → 0.1.1

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.
Files changed (123) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +15 -2
  4. package/dist/AboutView.d.ts +1 -0
  5. package/dist/AboutView.js +8 -0
  6. package/dist/AboutView.js.map +1 -0
  7. package/dist/AiConnectProvider.d.ts +26 -0
  8. package/dist/AiConnectProvider.js +44 -0
  9. package/dist/AiConnectProvider.js.map +1 -0
  10. package/dist/BrandMark.d.ts +3 -0
  11. package/dist/BrandMark.js +8 -0
  12. package/dist/BrandMark.js.map +1 -0
  13. package/dist/ConnectButton.d.ts +4 -0
  14. package/dist/ConnectButton.js +15 -0
  15. package/dist/ConnectButton.js.map +1 -0
  16. package/dist/ConnectModal.d.ts +1 -0
  17. package/dist/ConnectModal.js +68 -0
  18. package/dist/ConnectModal.js.map +1 -0
  19. package/dist/ConnectRing.d.ts +3 -0
  20. package/dist/ConnectRing.js +8 -0
  21. package/dist/ConnectRing.js.map +1 -0
  22. package/dist/WebAccountStep.d.ts +13 -0
  23. package/dist/WebAccountStep.js +34 -0
  24. package/dist/WebAccountStep.js.map +1 -0
  25. package/dist/index.d.ts +23 -0
  26. package/dist/index.js +12 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/launcher.d.ts +11 -0
  29. package/dist/launcher.js +46 -0
  30. package/dist/launcher.js.map +1 -0
  31. package/dist/launchers.css +150 -0
  32. package/dist/messages.d.ts +15 -0
  33. package/dist/messages.js +46 -0
  34. package/dist/messages.js.map +1 -0
  35. package/dist/moduleMessages.d.ts +29 -0
  36. package/dist/moduleMessages.js +147 -0
  37. package/dist/moduleMessages.js.map +1 -0
  38. package/dist/modules/AiChatInline.d.ts +3 -0
  39. package/dist/modules/AiChatInline.js +18 -0
  40. package/dist/modules/AiChatInline.js.map +1 -0
  41. package/dist/modules/AiChatPage.d.ts +4 -0
  42. package/dist/modules/AiChatPage.js +23 -0
  43. package/dist/modules/AiChatPage.js.map +1 -0
  44. package/dist/modules/AiChatPanel.d.ts +4 -0
  45. package/dist/modules/AiChatPanel.js +22 -0
  46. package/dist/modules/AiChatPanel.js.map +1 -0
  47. package/dist/modules/AiChatPopup.d.ts +4 -0
  48. package/dist/modules/AiChatPopup.js +21 -0
  49. package/dist/modules/AiChatPopup.js.map +1 -0
  50. package/dist/modules/AiSearch.d.ts +3 -0
  51. package/dist/modules/AiSearch.js +76 -0
  52. package/dist/modules/AiSearch.js.map +1 -0
  53. package/dist/modules/Launcher.d.ts +9 -0
  54. package/dist/modules/Launcher.js +8 -0
  55. package/dist/modules/Launcher.js.map +1 -0
  56. package/dist/modules/parts/AccountBadge.d.ts +3 -0
  57. package/dist/modules/parts/AccountBadge.js +15 -0
  58. package/dist/modules/parts/AccountBadge.js.map +1 -0
  59. package/dist/modules/parts/AnswerText.d.ts +8 -0
  60. package/dist/modules/parts/AnswerText.js +43 -0
  61. package/dist/modules/parts/AnswerText.js.map +1 -0
  62. package/dist/modules/parts/ChatFrame.d.ts +12 -0
  63. package/dist/modules/parts/ChatFrame.js +16 -0
  64. package/dist/modules/parts/ChatFrame.js.map +1 -0
  65. package/dist/modules/parts/Composer.d.ts +13 -0
  66. package/dist/modules/parts/Composer.js +64 -0
  67. package/dist/modules/parts/Composer.js.map +1 -0
  68. package/dist/modules/parts/ConnectNote.d.ts +4 -0
  69. package/dist/modules/parts/ConnectNote.js +51 -0
  70. package/dist/modules/parts/ConnectNote.js.map +1 -0
  71. package/dist/modules/parts/ConnectStep.d.ts +4 -0
  72. package/dist/modules/parts/ConnectStep.js +17 -0
  73. package/dist/modules/parts/ConnectStep.js.map +1 -0
  74. package/dist/modules/parts/Conversation.d.ts +22 -0
  75. package/dist/modules/parts/Conversation.js +69 -0
  76. package/dist/modules/parts/Conversation.js.map +1 -0
  77. package/dist/modules/parts/PlanOffer.d.ts +3 -0
  78. package/dist/modules/parts/PlanOffer.js +79 -0
  79. package/dist/modules/parts/PlanOffer.js.map +1 -0
  80. package/dist/modules/parts/ToolActivity.d.ts +5 -0
  81. package/dist/modules/parts/ToolActivity.js +33 -0
  82. package/dist/modules/parts/ToolActivity.js.map +1 -0
  83. package/dist/modules/parts/accountModel.d.ts +2 -0
  84. package/dist/modules/parts/accountModel.js +13 -0
  85. package/dist/modules/parts/accountModel.js.map +1 -0
  86. package/dist/modules/parts/answerMarkdown.d.ts +32 -0
  87. package/dist/modules/parts/answerMarkdown.js +105 -0
  88. package/dist/modules/parts/answerMarkdown.js.map +1 -0
  89. package/dist/modules/parts/icons.d.ts +10 -0
  90. package/dist/modules/parts/icons.js +15 -0
  91. package/dist/modules/parts/icons.js.map +1 -0
  92. package/dist/modules/parts/moduleAnalytics.d.ts +5 -0
  93. package/dist/modules/parts/moduleAnalytics.js +9 -0
  94. package/dist/modules/parts/moduleAnalytics.js.map +1 -0
  95. package/dist/modules/parts/moduleClass.d.ts +1 -0
  96. package/dist/modules/parts/moduleClass.js +6 -0
  97. package/dist/modules/parts/moduleClass.js.map +1 -0
  98. package/dist/modules/parts/planPrice.d.ts +2 -0
  99. package/dist/modules/parts/planPrice.js +8 -0
  100. package/dist/modules/parts/planPrice.js.map +1 -0
  101. package/dist/modules/parts/useModuleChat.d.ts +24 -0
  102. package/dist/modules/parts/useModuleChat.js +117 -0
  103. package/dist/modules/parts/useModuleChat.js.map +1 -0
  104. package/dist/modules/parts/useModuleHandle.d.ts +3 -0
  105. package/dist/modules/parts/useModuleHandle.js +12 -0
  106. package/dist/modules/parts/useModuleHandle.js.map +1 -0
  107. package/dist/modules/types.d.ts +28 -0
  108. package/dist/modules/types.js +5 -0
  109. package/dist/modules/types.js.map +1 -0
  110. package/dist/modules/useOverlay.d.ts +20 -0
  111. package/dist/modules/useOverlay.js +102 -0
  112. package/dist/modules/useOverlay.js.map +1 -0
  113. package/dist/pickerMessages.d.ts +35 -0
  114. package/dist/pickerMessages.js +222 -0
  115. package/dist/pickerMessages.js.map +1 -0
  116. package/dist/styles.css +1721 -0
  117. package/dist/useAiChat.d.ts +33 -0
  118. package/dist/useAiChat.js +143 -0
  119. package/dist/useAiChat.js.map +1 -0
  120. package/dist/webAccountMessages.d.ts +24 -0
  121. package/dist/webAccountMessages.js +130 -0
  122. package/dist/webAccountMessages.js.map +1 -0
  123. package/package.json +53 -4
@@ -0,0 +1,117 @@
1
+ // The conversation a module runs: the chat on the visitor's AI with the site's tools, plus the
2
+ // question a visitor asks before their AI is connected. That question opens the connect window and
3
+ // stays on screen; it goes out on its own once the wallet connects the site or the visitor signs in on
4
+ // the page, and stays with the connection step while a sign in waits. Signing out of a web account
5
+ // starts the conversation again from the connection step.
6
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
7
+ import { McpToolSource } from '@tensorpass/aiconnect';
8
+ import { useAiConnect } from "../../AiConnectProvider.js";
9
+ import { useAiChat } from "../../useAiChat.js";
10
+ // The states in which the connection is still settling on its own, without the visitor.
11
+ const SETTLING = new Set(['checking', 'connecting']);
12
+ // The site's MCP tools, connected on the first question. The module also renders on the server,
13
+ // where a relative address has no page to resolve against.
14
+ function mcpTools(url) {
15
+ let source = null;
16
+ const connected = () => {
17
+ source ??= new McpToolSource(url);
18
+ return source;
19
+ };
20
+ return {
21
+ listTools: () => connected().listTools(),
22
+ callTool: (name, args) => connected().callTool(name, args),
23
+ };
24
+ }
25
+ // The states in which asking a question asks the wallet to connect.
26
+ const READY_TO_CONNECT = new Set(['disconnected', 'error']);
27
+ // Keeps the question asked before the connection and sends it once the site is connected. Asking is
28
+ // the visitor's one action: it asks the wallet to connect at once, or as soon as the first wallet
29
+ // check ends, and without the wallet the module's own install step shows with the question kept.
30
+ function usePendingQuestion(send) {
31
+ const { client } = useAiConnect();
32
+ const pending = useRef(null);
33
+ const connectAfterCheck = useRef(false);
34
+ const [pendingQuestion, setPendingQuestion] = useState(null);
35
+ const keep = useCallback((question) => {
36
+ pending.current = question;
37
+ setPendingQuestion(question);
38
+ }, []);
39
+ useEffect(() => client.subscribe((next) => {
40
+ const question = pending.current;
41
+ if (question === null || SETTLING.has(next.status)) {
42
+ return;
43
+ }
44
+ const afterCheck = connectAfterCheck.current;
45
+ connectAfterCheck.current = false;
46
+ if (next.status === 'connected') {
47
+ keep(null);
48
+ void send(question);
49
+ }
50
+ else if (afterCheck && next.status === 'disconnected') {
51
+ void client.connect();
52
+ }
53
+ }), [client, keep, send]);
54
+ const ask = useCallback((question) => {
55
+ const text = question.trim();
56
+ if (!text) {
57
+ return;
58
+ }
59
+ const { status } = client.state;
60
+ if (status === 'connected') {
61
+ void send(text);
62
+ return;
63
+ }
64
+ keep(text);
65
+ if (READY_TO_CONNECT.has(status)) {
66
+ void client.connect();
67
+ }
68
+ else if (status === 'checking') {
69
+ connectAfterCheck.current = true;
70
+ }
71
+ }, [client, keep, send]);
72
+ const forget = useCallback(() => keep(null), [keep]);
73
+ return { pendingQuestion, ask, forget };
74
+ }
75
+ // Starts the conversation again when the web account that answered it signs out, by the visitor or because
76
+ // its credential stopped opening the account: its answers and errors belong to that account.
77
+ function useResetOnSignOut(reset) {
78
+ const { client } = useAiConnect();
79
+ const previous = useRef(client.state);
80
+ useEffect(() => client.subscribe((next) => {
81
+ const before = previous.current;
82
+ previous.current = next;
83
+ if (before.status === 'connected' && before.account && next.status !== 'connected') {
84
+ reset();
85
+ }
86
+ }), [client, reset]);
87
+ }
88
+ export function useModuleChat({ system, tools, mcp, guards }) {
89
+ const toolSource = useMemo(() => tools ?? (mcp ? mcpTools(mcp) : undefined), [tools, mcp]);
90
+ const chat = useAiChat({ system, tools: toolSource, guards });
91
+ const { pendingQuestion, ask, forget } = usePendingQuestion(chat.send);
92
+ // The turns the visitor stopped, by their place in the conversation.
93
+ const [stopped, setStopped] = useState([]);
94
+ const { turns, stop: stopChat, reset: resetChat, busy, dropFailedTurn } = chat;
95
+ const stop = useCallback(() => {
96
+ if (busy) {
97
+ setStopped((current) => [...current, turns.length - 1]);
98
+ }
99
+ stopChat();
100
+ }, [busy, turns.length, stopChat]);
101
+ const reset = useCallback(() => {
102
+ resetChat();
103
+ forget();
104
+ setStopped([]);
105
+ }, [resetChat, forget]);
106
+ useResetOnSignOut(reset);
107
+ // Asks the last question again in place of its failed turn.
108
+ const retry = useCallback(() => {
109
+ const last = turns.at(-1);
110
+ if (last) {
111
+ dropFailedTurn();
112
+ ask(last.question);
113
+ }
114
+ }, [turns, ask, dropFailedTurn]);
115
+ return { ...chat, ask, stop, reset, retry, pendingQuestion, stopped };
116
+ }
117
+ //# sourceMappingURL=useModuleChat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useModuleChat.js","sourceRoot":"","sources":["../../../src/modules/parts/useModuleChat.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,mGAAmG;AACnG,uGAAuG;AACvG,mGAAmG;AACnG,0DAA0D;AAE1D,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA6B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAS/C,wFAAwF;AACxF,MAAM,QAAQ,GAAG,IAAI,GAAG,CAA4B,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC,CAAC;AAEhF,gGAAgG;AAChG,2DAA2D;AAC3D,SAAS,QAAQ,CAAC,GAAW;IAC3B,IAAI,MAAM,GAAyB,IAAI,CAAC;IACxC,MAAM,SAAS,GAAG,GAAG,EAAE;QACrB,MAAM,KAAK,IAAI,aAAa,CAAC,GAAG,CAAC,CAAC;QAClC,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,OAAO;QACL,SAAS,EAAE,GAAG,EAAE,CAAC,SAAS,EAAE,CAAC,SAAS,EAAE;QACxC,QAAQ,EAAE,CAAC,IAAI,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C,CAAC,GAAG,OAAO,EAAE,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;QAC1D,CAAC;QACD,QAAQ,EAAE,CAAC;IACb,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;IAEnC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,SAAS,EAAE,CAAC;QACZ,MAAM,EAAE,CAAC;QACT,UAAU,CAAC,EAAE,CAAC,CAAC;IACjB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;IACxB,iBAAiB,CAAC,KAAK,CAAC,CAAC;IAEzB,4DAA4D;IAC5D,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,MAAM,IAAI,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,IAAI,EAAE,CAAC;YACT,cAAc,EAAE,CAAC;YACjB,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACrB,CAAC;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC;IAEjC,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC;AACxE,CAAC","sourcesContent":["// The conversation a module runs: the chat on the visitor's AI with the site's tools, plus the\n// question a visitor asks before their AI is connected. That question opens the connect window and\n// stays on screen; it goes out on its own once the wallet connects the site or the visitor signs in on\n// the page, and stays with the connection step while a sign in waits. Signing out of a web account\n// starts the conversation again from the connection step.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { McpToolSource } from '@tensorpass/aiconnect';\nimport type { ConnectionState, GuardPolicy, ToolSource } from '@tensorpass/aiconnect';\nimport { useAiConnect } from '../../AiConnectProvider.tsx';\nimport { useAiChat } from '../../useAiChat.ts';\n\nexport interface ModuleChatOptions {\n system: string;\n tools?: ToolSource;\n mcp?: string;\n guards?: GuardPolicy;\n}\n\n// The states in which the connection is still settling on its own, without the visitor.\nconst SETTLING = new Set<ConnectionState['status']>(['checking', 'connecting']);\n\n// The site's MCP tools, connected on the first question. The module also renders on the server,\n// where a relative address has no page to resolve against.\nfunction mcpTools(url: string): ToolSource {\n let source: McpToolSource | null = null;\n const connected = () => {\n source ??= new McpToolSource(url);\n return source;\n };\n return {\n listTools: () => connected().listTools(),\n callTool: (name, args) => connected().callTool(name, args),\n };\n}\n\n// The states in which asking a question asks the wallet to connect.\nconst READY_TO_CONNECT = new Set<ConnectionState['status']>(['disconnected', 'error']);\n\n// Keeps the question asked before the connection and sends it once the site is connected. Asking is\n// the visitor's one action: it asks the wallet to connect at once, or as soon as the first wallet\n// check ends, and without the wallet the module's own install step shows with the question kept.\nfunction usePendingQuestion(send: (question: string) => Promise<void>) {\n const { client } = useAiConnect();\n const pending = useRef<string | null>(null);\n const connectAfterCheck = useRef(false);\n const [pendingQuestion, setPendingQuestion] = useState<string | null>(null);\n\n const keep = useCallback((question: string | null) => {\n pending.current = question;\n setPendingQuestion(question);\n }, []);\n\n useEffect(() => client.subscribe((next) => {\n const question = pending.current;\n if (question === null || SETTLING.has(next.status)) {\n return;\n }\n const afterCheck = connectAfterCheck.current;\n connectAfterCheck.current = false;\n if (next.status === 'connected') {\n keep(null);\n void send(question);\n } else if (afterCheck && next.status === 'disconnected') {\n void client.connect();\n }\n }), [client, keep, send]);\n\n const ask = useCallback((question: string) => {\n const text = question.trim();\n if (!text) {\n return;\n }\n const { status } = client.state;\n if (status === 'connected') {\n void send(text);\n return;\n }\n keep(text);\n if (READY_TO_CONNECT.has(status)) {\n void client.connect();\n } else if (status === 'checking') {\n connectAfterCheck.current = true;\n }\n }, [client, keep, send]);\n\n const forget = useCallback(() => keep(null), [keep]);\n return { pendingQuestion, ask, forget };\n}\n\n// Starts the conversation again when the web account that answered it signs out, by the visitor or because\n// its credential stopped opening the account: its answers and errors belong to that account.\nfunction useResetOnSignOut(reset: () => void) {\n const { client } = useAiConnect();\n const previous = useRef<ConnectionState>(client.state);\n useEffect(() => client.subscribe((next) => {\n const before = previous.current;\n previous.current = next;\n if (before.status === 'connected' && before.account && next.status !== 'connected') {\n reset();\n }\n }), [client, reset]);\n}\n\nexport function useModuleChat({ system, tools, mcp, guards }: ModuleChatOptions) {\n const toolSource = useMemo(() => tools ?? (mcp ? mcpTools(mcp) : undefined), [tools, mcp]);\n const chat = useAiChat({ system, tools: toolSource, guards });\n const { pendingQuestion, ask, forget } = usePendingQuestion(chat.send);\n // The turns the visitor stopped, by their place in the conversation.\n const [stopped, setStopped] = useState<number[]>([]);\n const { turns, stop: stopChat, reset: resetChat, busy, dropFailedTurn } = chat;\n\n const stop = useCallback(() => {\n if (busy) {\n setStopped((current) => [...current, turns.length - 1]);\n }\n stopChat();\n }, [busy, turns.length, stopChat]);\n\n const reset = useCallback(() => {\n resetChat();\n forget();\n setStopped([]);\n }, [resetChat, forget]);\n useResetOnSignOut(reset);\n\n // Asks the last question again in place of its failed turn.\n const retry = useCallback(() => {\n const last = turns.at(-1);\n if (last) {\n dropFailedTurn();\n ask(last.question);\n }\n }, [turns, ask, dropFailedTurn]);\n\n return { ...chat, ask, stop, reset, retry, pendingQuestion, stopped };\n}\n\nexport type ModuleChat = ReturnType<typeof useModuleChat>;\n"]}
@@ -0,0 +1,3 @@
1
+ import type { Ref } from 'react';
2
+ import type { AiModuleHandle } from '../types.ts';
3
+ export declare function useModuleHandle(ref: Ref<AiModuleHandle> | undefined, ask: (question: string) => void, show?: () => void): void;
@@ -0,0 +1,12 @@
1
+ // The handle a module gives the site through its `ref`: a question from the site's own field or button
2
+ // goes to the module as if the visitor had typed it there, and a module that floats opens first.
3
+ import { useImperativeHandle } from 'react';
4
+ export function useModuleHandle(ref, ask, show) {
5
+ useImperativeHandle(ref, () => ({
6
+ ask: (question) => {
7
+ show?.();
8
+ ask(question);
9
+ },
10
+ }), [ask, show]);
11
+ }
12
+ //# sourceMappingURL=useModuleHandle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useModuleHandle.js","sourceRoot":"","sources":["../../../src/modules/parts/useModuleHandle.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,iGAAiG;AAEjG,OAAO,EAAE,mBAAmB,EAAE,MAAM,OAAO,CAAC;AAI5C,MAAM,UAAU,eAAe,CAAC,GAAoC,EAAE,GAA+B,EACnG,IAAiB;IACjB,mBAAmB,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC;QAC9B,GAAG,EAAE,CAAC,QAAgB,EAAE,EAAE;YACxB,IAAI,EAAE,EAAE,CAAC;YACT,GAAG,CAAC,QAAQ,CAAC,CAAC;QAChB,CAAC;KACF,CAAC,EAAE,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;AACnB,CAAC","sourcesContent":["// The handle a module gives the site through its `ref`: a question from the site's own field or button\n// goes to the module as if the visitor had typed it there, and a module that floats opens first.\n\nimport { useImperativeHandle } from 'react';\nimport type { Ref } from 'react';\nimport type { AiModuleHandle } from '../types.ts';\n\nexport function useModuleHandle(ref: Ref<AiModuleHandle> | undefined, ask: (question: string) => void,\n show?: () => void) {\n useImperativeHandle(ref, () => ({\n ask: (question: string) => {\n show?.();\n ask(question);\n },\n }), [ask, show]);\n}\n"]}
@@ -0,0 +1,28 @@
1
+ import type { ReactNode, Ref } from 'react';
2
+ import type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';
3
+ import type { ChatTurn } from '../useAiChat.ts';
4
+ export interface AiModuleHandle {
5
+ ask: (question: string) => void;
6
+ }
7
+ export interface AiModuleProps {
8
+ system: string;
9
+ tools?: ToolSource;
10
+ mcp?: string;
11
+ title?: string;
12
+ intro?: string;
13
+ placeholder?: string;
14
+ suggestions?: string[];
15
+ toolLabels?: Record<string, string>;
16
+ guards?: GuardPolicy;
17
+ renderToolResults?: (turn: ChatTurn) => ReactNode;
18
+ analytics?: string;
19
+ ref?: Ref<AiModuleHandle>;
20
+ className?: string;
21
+ }
22
+ export interface AiOverlayProps {
23
+ open?: boolean;
24
+ defaultOpen?: boolean;
25
+ onOpenChange?: (open: boolean) => void;
26
+ hideLauncher?: boolean;
27
+ launcherLabel?: string;
28
+ }
@@ -0,0 +1,5 @@
1
+ // The props every interface module shares: what the visitor's AI is told, the site's tools, the copy
2
+ // the site sets for its own voice, the guards it tunes, how the site draws its tool results, and the
3
+ // handle its own controls ask through. The modules that float over the page add how they open.
4
+ export {};
5
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/modules/types.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,qGAAqG;AACrG,+FAA+F","sourcesContent":["// The props every interface module shares: what the visitor's AI is told, the site's tools, the copy\n// the site sets for its own voice, the guards it tunes, how the site draws its tool results, and the\n// handle its own controls ask through. The modules that float over the page add how they open.\n\nimport type { ReactNode, Ref } from 'react';\nimport type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';\nimport type { ChatTurn } from '../useAiChat.ts';\n\n// What a site's own controls can do with a module through its `ref`.\nexport interface AiModuleHandle {\n // Sends the question as if the visitor had typed it in the module. A module that floats opens first.\n ask: (question: string) => void;\n}\n\nexport interface AiModuleProps {\n // What the visitor's AI is told about the site and its tools before the first question.\n system: string;\n // The site's tools. Give `mcp` instead to read them from the site's MCP server.\n tools?: ToolSource;\n // The address of the site's MCP server, such as `/api/mcp`. The module connects to it when the\n // first question is sent.\n mcp?: string;\n // The heading of the module. The built in copy says \"Ask AI\" (or \"AI mode\" for the full page).\n title?: string;\n // The heading of an empty conversation.\n intro?: string;\n placeholder?: string;\n // Questions the visitor can send with one click before asking their own.\n suggestions?: string[];\n // A plain name for each tool, shown while it runs in place of the tool's own name.\n toolLabels?: Record<string, string>;\n // The site's own values for the guards the conversation runs under: its internal names, the hosts\n // and addresses its answers may give, the tools it shows, its safe answer. The guards run with their\n // defaults without it.\n guards?: GuardPolicy;\n // Draws a turn's tool results the site's way, such as its own result cards, under the answer.\n // The turn holds the answer and every tool call with its raw result.\n renderToolResults?: (turn: ChatTurn) => ReactNode;\n // A name for the module's actions in the site's click analytics: the install and connect buttons, the\n // send button and the suggestions carry `data-analytics` with it, such as `chat-install` or `chat-send`.\n analytics?: string;\n // Receives the module's handle, for a field or a button of the site's own that sends the module a\n // question, such as an ask bar in the page's opening that opens the side panel.\n ref?: Ref<AiModuleHandle>;\n className?: string;\n}\n\nexport interface AiOverlayProps {\n // Whether the module is open, when the site controls it. Leave it out to let the module keep it.\n open?: boolean;\n // Whether the module starts open, when the module keeps the state itself.\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n // Hides the module's own button, for a site that opens the module from a button of its own.\n hideLauncher?: boolean;\n // The text of the module's own button.\n launcherLabel?: string;\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import type { RefObject } from 'react';
2
+ import type { AiOverlayProps } from './types.ts';
3
+ export interface OverlayRefs {
4
+ layerRef: RefObject<HTMLElement | null>;
5
+ fieldRef: RefObject<HTMLTextAreaElement | null>;
6
+ launcherRef: RefObject<HTMLButtonElement | null>;
7
+ }
8
+ export declare function useFocusTrap(layerRef: RefObject<HTMLElement | null>, enabled: boolean): void;
9
+ export declare function useScrollLock(enabled: boolean): void;
10
+ export declare function useOverlay(props: AiOverlayProps): {
11
+ open: boolean;
12
+ show: () => void;
13
+ close: () => void;
14
+ toggle: () => void;
15
+ layerRef: RefObject<HTMLElement | null>;
16
+ fieldRef: RefObject<HTMLTextAreaElement | null>;
17
+ launcherRef: RefObject<HTMLButtonElement | null>;
18
+ titleId: string;
19
+ layerId: string;
20
+ };
@@ -0,0 +1,102 @@
1
+ // How a module that floats over the page opens and closes: the open state, kept by the site or by
2
+ // the module; Escape to close, which the connect window takes first while it is open; focus moved
3
+ // to the question box on open and back to the module's button on close. The full page mode also
4
+ // holds the page's scroll and keeps the focus inside while it is open.
5
+ import { useCallback, useEffect, useId, useRef, useState } from 'react';
6
+ import { useAiConnect } from "../AiConnectProvider.js";
7
+ const FOCUSABLE = 'a[href], button:not([disabled]), textarea, input, [tabindex]:not([tabindex="-1"])';
8
+ function useOpenState({ open, defaultOpen = false, onOpenChange }) {
9
+ const [own, setOwn] = useState(defaultOpen);
10
+ const setOpen = useCallback((next) => {
11
+ setOwn(next);
12
+ onOpenChange?.(next);
13
+ }, [onOpenChange]);
14
+ return [open ?? own, setOpen];
15
+ }
16
+ function useEscape(open, close) {
17
+ const { isPickerOpen } = useAiConnect();
18
+ useEffect(() => {
19
+ if (!open || isPickerOpen) {
20
+ return undefined;
21
+ }
22
+ const onKey = (event) => {
23
+ if (event.key === 'Escape') {
24
+ close();
25
+ }
26
+ };
27
+ document.addEventListener('keydown', onKey);
28
+ return () => document.removeEventListener('keydown', onKey);
29
+ }, [open, isPickerOpen, close]);
30
+ }
31
+ // On open the focus moves to the question box; on close it goes back to the module's button, or, for a
32
+ // module the site opened from its own control, to the element that held it before.
33
+ function useFocusOnOpen(open, { layerRef, fieldRef, launcherRef }) {
34
+ const wasOpen = useRef(open);
35
+ const opener = useRef(null);
36
+ useEffect(() => {
37
+ if (open === wasOpen.current) {
38
+ return;
39
+ }
40
+ wasOpen.current = open;
41
+ if (open) {
42
+ opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
43
+ (fieldRef.current ?? layerRef.current)?.focus();
44
+ }
45
+ else {
46
+ (launcherRef.current ?? opener.current)?.focus();
47
+ }
48
+ }, [open, layerRef, fieldRef, launcherRef]);
49
+ }
50
+ // The element with focus, read from the layer's own root so it works inside a shadow root too.
51
+ function activeElement(layer) {
52
+ return layer.getRootNode().activeElement;
53
+ }
54
+ export function useFocusTrap(layerRef, enabled) {
55
+ useEffect(() => {
56
+ const layer = layerRef.current;
57
+ if (!enabled || !layer) {
58
+ return undefined;
59
+ }
60
+ const onKey = (event) => {
61
+ const focusable = [...layer.querySelectorAll(FOCUSABLE)];
62
+ if (event.key !== 'Tab' || focusable.length === 0) {
63
+ return;
64
+ }
65
+ const edge = event.shiftKey ? focusable[0] : focusable[focusable.length - 1];
66
+ if (activeElement(layer) === edge) {
67
+ event.preventDefault();
68
+ (event.shiftKey ? focusable[focusable.length - 1] : focusable[0]).focus();
69
+ }
70
+ };
71
+ layer.addEventListener('keydown', onKey);
72
+ return () => layer.removeEventListener('keydown', onKey);
73
+ }, [layerRef, enabled]);
74
+ }
75
+ export function useScrollLock(enabled) {
76
+ useEffect(() => {
77
+ if (!enabled) {
78
+ return undefined;
79
+ }
80
+ const root = document.documentElement;
81
+ const previous = root.style.overflow;
82
+ root.style.overflow = 'hidden';
83
+ return () => {
84
+ root.style.overflow = previous;
85
+ };
86
+ }, [enabled]);
87
+ }
88
+ export function useOverlay(props) {
89
+ const [open, setOpen] = useOpenState(props);
90
+ const layerRef = useRef(null);
91
+ const fieldRef = useRef(null);
92
+ const launcherRef = useRef(null);
93
+ const titleId = useId();
94
+ const layerId = useId();
95
+ const show = useCallback(() => setOpen(true), [setOpen]);
96
+ const close = useCallback(() => setOpen(false), [setOpen]);
97
+ const toggle = useCallback(() => setOpen(!open), [setOpen, open]);
98
+ useEscape(open, close);
99
+ useFocusOnOpen(open, { layerRef, fieldRef, launcherRef });
100
+ return { open, show, close, toggle, layerRef, fieldRef, launcherRef, titleId, layerId };
101
+ }
102
+ //# sourceMappingURL=useOverlay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useOverlay.js","sourceRoot":"","sources":["../../src/modules/useOverlay.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,kGAAkG;AAClG,gGAAgG;AAChG,uEAAuE;AAEvE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAExE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAA0B,CAAC;AAGxD,MAAM,SAAS,GAAG,mFAAmF,CAAC;AAQtG,SAAS,Y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QAAQ,GAAG,MAAM,CAAc,IAAI,CAAC,CAAC;IAC3C,MAAM,QAAQ,GAAG,MAAM,CAAsB,IAAI,CAAC,CAAC;IACnD,MAAM,WAAW,GAAG,MAAM,CAAoB,IAAI,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,KAAK,EAAE,CAAC;IACxB,MAAM,OAAO,GAAG,KAAK,EAAE,CAAC;IACxB,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IACzD,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;IAClE,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACvB,cAAc,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC1D,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC1F,CAAC","sourcesContent":["// How a module that floats over the page opens and closes: the open state, kept by the site or by\n// the module; Escape to close, which the connect window takes first while it is open; focus moved\n// to the question box on open and back to the module's button on close. The full page mode also\n// holds the page's scroll and keeps the focus inside while it is open.\n\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport type { RefObject } from 'react';\nimport { useAiConnect } from '../AiConnectProvider.tsx';\nimport type { AiOverlayProps } from './types.ts';\n\nconst FOCUSABLE = 'a[href], button:not([disabled]), textarea, input, [tabindex]:not([tabindex=\"-1\"])';\n\nexport interface OverlayRefs {\n layerRef: RefObject<HTMLElement | null>;\n fieldRef: RefObject<HTMLTextAreaElement | null>;\n launcherRef: RefObject<HTMLButtonElement | null>;\n}\n\nfunction useOpenState({ open, defaultOpen = false, onOpenChange }: AiOverlayProps) {\n const [own, setOwn] = useState(defaultOpen);\n const setOpen = useCallback((next: boolean) => {\n setOwn(next);\n onOpenChange?.(next);\n }, [onOpenChange]);\n return [open ?? own, setOpen] as const;\n}\n\nfunction useEscape(open: boolean, close: () => void) {\n const { isPickerOpen } = useAiConnect();\n useEffect(() => {\n if (!open || isPickerOpen) {\n return undefined;\n }\n const onKey = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n close();\n }\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [open, isPickerOpen, close]);\n}\n\n// On open the focus moves to the question box; on close it goes back to the module's button, or, for a\n// module the site opened from its own control, to the element that held it before.\nfunction useFocusOnOpen(open: boolean, { layerRef, fieldRef, launcherRef }: OverlayRefs) {\n const wasOpen = useRef(open);\n const opener = useRef<HTMLElement | null>(null);\n useEffect(() => {\n if (open === wasOpen.current) {\n return;\n }\n wasOpen.current = open;\n if (open) {\n opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n (fieldRef.current ?? layerRef.current)?.focus();\n } else {\n (launcherRef.current ?? opener.current)?.focus();\n }\n }, [open, layerRef, fieldRef, launcherRef]);\n}\n\n// The element with focus, read from the layer's own root so it works inside a shadow root too.\nfunction activeElement(layer: HTMLElement): Element | null {\n return (layer.getRootNode() as Document | ShadowRoot).activeElement;\n}\n\nexport function useFocusTrap(layerRef: RefObject<HTMLElement | null>, enabled: boolean) {\n useEffect(() => {\n const layer = layerRef.current;\n if (!enabled || !layer) {\n return undefined;\n }\n const onKey = (event: KeyboardEvent) => {\n const focusable = [...layer.querySelectorAll<HTMLElement>(FOCUSABLE)];\n if (event.key !== 'Tab' || focusable.length === 0) {\n return;\n }\n const edge = event.shiftKey ? focusable[0] : focusable[focusable.length - 1];\n if (activeElement(layer) === edge) {\n event.preventDefault();\n (event.shiftKey ? focusable[focusable.length - 1] : focusable[0]).focus();\n }\n };\n layer.addEventListener('keydown', onKey);\n return () => layer.removeEventListener('keydown', onKey);\n }, [layerRef, enabled]);\n}\n\nexport function useScrollLock(enabled: boolean) {\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n const root = document.documentElement;\n const previous = root.style.overflow;\n root.style.overflow = 'hidden';\n return () => {\n root.style.overflow = previous;\n };\n }, [enabled]);\n}\n\nexport function useOverlay(props: AiOverlayProps) {\n const [open, setOpen] = useOpenState(props);\n const layerRef = useRef<HTMLElement>(null);\n const fieldRef = useRef<HTMLTextAreaElement>(null);\n const launcherRef = useRef<HTMLButtonElement>(null);\n const titleId = useId();\n const layerId = useId();\n const show = useCallback(() => setOpen(true), [setOpen]);\n const close = useCallback(() => setOpen(false), [setOpen]);\n const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n useEscape(open, close);\n useFocusOnOpen(open, { layerRef, fieldRef, launcherRef });\n return { open, show, close, toggle, layerRef, fieldRef, launcherRef, titleId, layerId };\n}\n"]}
@@ -0,0 +1,35 @@
1
+ import type { WalletRefusal } from '@tensorpass/aiconnect';
2
+ export interface RefusalStep {
3
+ title: string;
4
+ text: string;
5
+ action: string;
6
+ }
7
+ export interface PickerMessages {
8
+ dir: 'ltr' | 'rtl';
9
+ title: string;
10
+ close: string;
11
+ back: string;
12
+ help: string;
13
+ aboutTitle: string;
14
+ aboutPoints: string[];
15
+ checking: string;
16
+ connectTitle: string;
17
+ connectText: string;
18
+ connectButton: string;
19
+ waitingTitle: string;
20
+ waitingText: string;
21
+ installTitle: string;
22
+ installText: (browser: string | undefined) => string;
23
+ addToBrowser: (browser: string) => string;
24
+ installButton: string;
25
+ safariAlreadyAdded: string;
26
+ refusals: Record<WalletRefusal | 'failed', RefusalStep>;
27
+ }
28
+ export declare const builtInMessages: {
29
+ en: PickerMessages;
30
+ fr: PickerMessages;
31
+ he: PickerMessages;
32
+ ar: PickerMessages;
33
+ zh: PickerMessages;
34
+ };
35
+ export type Locale = keyof typeof builtInMessages;
@@ -0,0 +1,222 @@
1
+ // The copy of the connect window in each built in language. A site passes `locale`, or its own
2
+ // `messages`, to match its voice. `dir` sets the reading direction for the language.
3
+ const en = {
4
+ dir: 'ltr',
5
+ title: 'Connect your AI',
6
+ close: 'Close',
7
+ back: 'Back',
8
+ help: 'How it works',
9
+ aboutTitle: 'Your AI, on this site',
10
+ aboutPoints: [
11
+ 'Your AI accounts stay in the AI Wallet extension, on your computer.',
12
+ 'This site asks the wallet for answers and never sees your keys or your other conversations.',
13
+ 'You choose the account for each site, and switch the site off from the wallet at any time.',
14
+ ],
15
+ checking: 'Looking for AI Wallet',
16
+ connectTitle: 'Use your own AI here',
17
+ connectText: 'AI Wallet answers this site with the AI plan you already pay for.',
18
+ connectButton: 'Connect AI Wallet',
19
+ waitingTitle: 'Continue in AI Wallet',
20
+ waitingText: 'Its window is open. This page continues on its own.',
21
+ installTitle: 'Use your ChatGPT, Claude or Gemini plan here',
22
+ installText: (browser) => `Add AI Wallet to ${browser ?? 'your browser'} and this site answers with the AI plan `
23
+ + 'you already pay for: ChatGPT, Claude, Gemini, Grok and more.',
24
+ addToBrowser: (browser) => `Add to ${browser}`,
25
+ installButton: 'Install AI Wallet',
26
+ safariAlreadyAdded: 'Already added? Click AI Wallet in Safari\'s toolbar and choose Always Allow on Every '
27
+ + 'Website.',
28
+ refusals: {
29
+ declined: {
30
+ title: 'You declined this site',
31
+ text: 'To use your AI here, connect again and approve the site in AI Wallet.',
32
+ action: 'Connect again',
33
+ },
34
+ closed: {
35
+ title: 'AI Wallet\'s window was closed',
36
+ text: 'Open it again to finish connecting this site.',
37
+ action: 'Open AI Wallet',
38
+ },
39
+ interrupted: {
40
+ title: 'AI Wallet stopped before the end',
41
+ text: 'Open it again to finish connecting this site.',
42
+ action: 'Open AI Wallet',
43
+ },
44
+ failed: { title: 'AI Wallet could not connect', text: '', action: 'Try again' },
45
+ },
46
+ };
47
+ const fr = {
48
+ dir: 'ltr',
49
+ title: 'Connectez votre IA',
50
+ close: 'Fermer',
51
+ back: 'Retour',
52
+ help: 'Comment ça marche',
53
+ aboutTitle: 'Votre IA, sur ce site',
54
+ aboutPoints: [
55
+ 'Vos comptes d\'IA restent dans l\'extension AI Wallet, sur votre ordinateur.',
56
+ 'Ce site demande ses réponses au portefeuille et ne voit ni vos clés ni vos autres conversations.',
57
+ 'Vous choisissez le compte de chaque site, et vous coupez un site depuis le portefeuille à tout moment.',
58
+ ],
59
+ checking: 'Recherche d\'AI Wallet',
60
+ connectTitle: 'Utilisez votre propre IA ici',
61
+ connectText: 'AI Wallet répond à ce site avec l\'abonnement d\'IA que vous payez déjà.',
62
+ connectButton: 'Connecter AI Wallet',
63
+ waitingTitle: 'Continuez dans AI Wallet',
64
+ waitingText: 'Sa fenêtre est ouverte. Cette page continue toute seule.',
65
+ installTitle: 'Utilisez ici votre abonnement ChatGPT, Claude ou Gemini',
66
+ installText: (browser) => `Ajoutez AI Wallet à ${browser ?? 'votre navigateur'} et ce site répond avec `
67
+ + 'l\'abonnement d\'IA que vous payez déjà : ChatGPT, Claude, Gemini, Grok et d\'autres.',
68
+ addToBrowser: (browser) => `Ajouter à ${browser}`,
69
+ installButton: 'Installer AI Wallet',
70
+ safariAlreadyAdded: 'Déjà ajouté ? Cliquez sur AI Wallet dans la barre d\'outils de Safari et choisissez Toujours '
71
+ + 'autoriser sur tous les sites web.',
72
+ refusals: {
73
+ declined: {
74
+ title: 'Vous avez refusé ce site',
75
+ text: 'Pour utiliser votre IA ici, connectez à nouveau et approuvez le site dans AI Wallet.',
76
+ action: 'Connecter à nouveau',
77
+ },
78
+ closed: {
79
+ title: 'La fenêtre d\'AI Wallet a été fermée',
80
+ text: 'Rouvrez-la pour finir de connecter ce site.',
81
+ action: 'Ouvrir AI Wallet',
82
+ },
83
+ interrupted: {
84
+ title: 'AI Wallet s\'est arrêté avant la fin',
85
+ text: 'Rouvrez-le pour finir de connecter ce site.',
86
+ action: 'Ouvrir AI Wallet',
87
+ },
88
+ failed: { title: 'AI Wallet n\'a pas pu se connecter', text: '', action: 'Réessayer' },
89
+ },
90
+ };
91
+ const he = {
92
+ dir: 'rtl',
93
+ title: 'חברו את הבינה המלאכותית שלכם',
94
+ close: 'סגירה',
95
+ back: 'חזרה',
96
+ help: 'איך זה עובד',
97
+ aboutTitle: 'הבינה המלאכותית שלכם, באתר הזה',
98
+ aboutPoints: [
99
+ 'חשבונות הבינה המלאכותית שלכם נשארים בתוסף AI Wallet, במחשב שלכם.',
100
+ 'האתר מבקש תשובות מהארנק ואינו רואה את המפתחות שלכם או שיחות אחרות.',
101
+ 'אתם בוחרים חשבון לכל אתר, ומנתקים אתר מהארנק בכל רגע.',
102
+ ],
103
+ checking: 'מחפשים את AI Wallet',
104
+ connectTitle: 'השתמשו כאן בבינה המלאכותית שלכם',
105
+ connectText: 'AI Wallet עונה לאתר הזה עם המנוי שאתם כבר משלמים עליו.',
106
+ connectButton: 'חיבור AI Wallet',
107
+ waitingTitle: 'המשיכו ב AI Wallet',
108
+ waitingText: 'החלון שלו פתוח. הדף ימשיך מעצמו.',
109
+ installTitle: 'השתמשו כאן במנוי ChatGPT, Claude או Gemini שלכם',
110
+ installText: (browser) => `הוסיפו את AI Wallet לדפדפן ${browser ?? 'שלכם'} והאתר יענה עם מנוי הבינה המלאכותית `
111
+ + 'שאתם כבר משלמים עליו: ChatGPT, Claude, Gemini, Grok ועוד.',
112
+ addToBrowser: (browser) => `הוספה לדפדפן ${browser}`,
113
+ installButton: 'התקנת AI Wallet',
114
+ safariAlreadyAdded: 'כבר הוספתם? לחצו על AI Wallet בסרגל הכלים של Safari ובחרו „תמיד לאשר בכל האתרים”.',
115
+ refusals: {
116
+ declined: {
117
+ title: 'דחיתם את האתר הזה',
118
+ text: 'כדי להשתמש כאן בבינה המלאכותית שלכם, התחברו שוב ואשרו את האתר ב AI Wallet.',
119
+ action: 'התחברות מחדש',
120
+ },
121
+ closed: {
122
+ title: 'החלון של AI Wallet נסגר',
123
+ text: 'פתחו אותו שוב כדי לסיים לחבר את האתר.',
124
+ action: 'פתיחת AI Wallet',
125
+ },
126
+ interrupted: {
127
+ title: 'AI Wallet נעצר לפני הסוף',
128
+ text: 'פתחו אותו שוב כדי לסיים לחבר את האתר.',
129
+ action: 'פתיחת AI Wallet',
130
+ },
131
+ failed: { title: 'AI Wallet לא הצליח להתחבר', text: '', action: 'ניסיון נוסף' },
132
+ },
133
+ };
134
+ const ar = {
135
+ dir: 'rtl',
136
+ title: 'اربط الذكاء الاصطناعي الخاص بك',
137
+ close: 'إغلاق',
138
+ back: 'رجوع',
139
+ help: 'كيف يعمل',
140
+ aboutTitle: 'الذكاء الاصطناعي الخاص بك، على هذا الموقع',
141
+ aboutPoints: [
142
+ 'تبقى حسابات الذكاء الاصطناعي الخاصة بك في إضافة AI Wallet، على جهاز الكمبيوتر الخاص بك.',
143
+ 'يطلب هذا الموقع الإجابات من المحفظة ولا يرى مفاتيحك أو محادثاتك الأخرى.',
144
+ 'تختار الحساب لكل موقع، ويمكنك إيقاف الموقع من المحفظة في أي وقت.',
145
+ ],
146
+ checking: 'جارٍ البحث عن AI Wallet',
147
+ connectTitle: 'استخدم الذكاء الاصطناعي الخاص بك هنا',
148
+ connectText: 'يجيب AI Wallet على هذا الموقع باشتراك الذكاء الاصطناعي الذي تدفع ثمنه بالفعل.',
149
+ connectButton: 'ربط AI Wallet',
150
+ waitingTitle: 'تابع في AI Wallet',
151
+ waitingText: 'نافذته مفتوحة. ستتابع هذه الصفحة من تلقاء نفسها.',
152
+ installTitle: 'استخدم هنا اشتراكك في ChatGPT أو Claude أو Gemini',
153
+ installText: (browser) => `أضف AI Wallet إلى ${browser ?? 'متصفحك'} وسيجيب هذا الموقع باشتراك الذكاء الاصطناعي `
154
+ + 'الذي تدفع ثمنه بالفعل: ChatGPT وClaude وGemini وGrok وغيرها.',
155
+ addToBrowser: (browser) => `إضافة إلى ${browser}`,
156
+ installButton: 'تثبيت AI Wallet',
157
+ safariAlreadyAdded: 'هل أضفته من قبل؟ انقر على AI Wallet في شريط أدوات Safari واختر «السماح دائمًا على كل '
158
+ + 'مواقع الويب».',
159
+ refusals: {
160
+ declined: {
161
+ title: 'لقد رفضت هذا الموقع',
162
+ text: 'لاستخدام الذكاء الاصطناعي الخاص بك هنا، أعد الربط ووافق على الموقع في AI Wallet.',
163
+ action: 'إعادة الربط',
164
+ },
165
+ closed: {
166
+ title: 'أُغلقت نافذة AI Wallet',
167
+ text: 'افتحها مرة أخرى لإكمال ربط هذا الموقع.',
168
+ action: 'فتح AI Wallet',
169
+ },
170
+ interrupted: {
171
+ title: 'توقف AI Wallet قبل النهاية',
172
+ text: 'افتحه مرة أخرى لإكمال ربط هذا الموقع.',
173
+ action: 'فتح AI Wallet',
174
+ },
175
+ failed: { title: 'تعذّر على AI Wallet الاتصال', text: '', action: 'إعادة المحاولة' },
176
+ },
177
+ };
178
+ const zh = {
179
+ dir: 'ltr',
180
+ title: '连接你的 AI',
181
+ close: '关闭',
182
+ back: '返回',
183
+ help: '工作原理',
184
+ aboutTitle: '你的 AI,用在这个网站上',
185
+ aboutPoints: [
186
+ '你的 AI 账户保存在你电脑上的 AI Wallet 扩展中。',
187
+ '这个网站向钱包请求回答,看不到你的密钥和你的其他对话。',
188
+ '你为每个网站选择账户,并可随时在钱包中关闭某个网站。',
189
+ ],
190
+ checking: '正在查找 AI Wallet',
191
+ connectTitle: '在这里使用你自己的 AI',
192
+ connectText: 'AI Wallet 用你已经付费的 AI 订阅来回答这个网站。',
193
+ connectButton: '连接 AI Wallet',
194
+ waitingTitle: '在 AI Wallet 中继续',
195
+ waitingText: '它的窗口已打开。此页面会自动继续。',
196
+ installTitle: '在这里使用你的 ChatGPT、Claude 或 Gemini 订阅',
197
+ installText: (browser) => `把 AI Wallet 添加到${browser ? ` ${browser} ` : '你的浏览器'}后,`
198
+ + '这个网站就会用你已经付费的 AI 订阅来回答:ChatGPT、Claude、Gemini、Grok 等。',
199
+ addToBrowser: (browser) => `添加至 ${browser}`,
200
+ installButton: '安装 AI Wallet',
201
+ safariAlreadyAdded: '已经添加过?点按 Safari 工具栏中的 AI Wallet,然后选择“在所有网站上始终允许”。',
202
+ refusals: {
203
+ declined: {
204
+ title: '你拒绝了这个网站',
205
+ text: '要在这里使用你的 AI,请重新连接,并在 AI Wallet 中批准这个网站。',
206
+ action: '重新连接',
207
+ },
208
+ closed: {
209
+ title: 'AI Wallet 的窗口已关闭',
210
+ text: '再次打开它,完成连接这个网站。',
211
+ action: '打开 AI Wallet',
212
+ },
213
+ interrupted: {
214
+ title: 'AI Wallet 在完成前停止了',
215
+ text: '再次打开它,完成连接这个网站。',
216
+ action: '打开 AI Wallet',
217
+ },
218
+ failed: { title: 'AI Wallet 无法连接', text: '', action: '重试' },
219
+ },
220
+ };
221
+ export const builtInMessages = { en, fr, he, ar, zh };
222
+ //# sourceMappingURL=pickerMessages.js.map