@tensorpass/aiconnect 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 (124) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +18 -2
  4. package/dist/callback.d.ts +2 -0
  5. package/dist/callback.js +4 -0
  6. package/dist/callback.js.map +1 -0
  7. package/dist/chatContent.d.ts +9 -0
  8. package/dist/chatContent.js +23 -0
  9. package/dist/chatContent.js.map +1 -0
  10. package/dist/cli/loopbackSignIn.d.ts +11 -0
  11. package/dist/cli/loopbackSignIn.js +94 -0
  12. package/dist/cli/loopbackSignIn.js.map +1 -0
  13. package/dist/cli/main.d.ts +2 -0
  14. package/dist/cli/main.js +41 -0
  15. package/dist/cli/main.js.map +1 -0
  16. package/dist/cli/siteKeyCommand.d.ts +11 -0
  17. package/dist/cli/siteKeyCommand.js +31 -0
  18. package/dist/cli/siteKeyCommand.js.map +1 -0
  19. package/dist/cli/siteKeyPlacement.d.ts +3 -0
  20. package/dist/cli/siteKeyPlacement.js +56 -0
  21. package/dist/cli/siteKeyPlacement.js.map +1 -0
  22. package/dist/client.d.ts +43 -0
  23. package/dist/client.js +211 -0
  24. package/dist/client.js.map +1 -0
  25. package/dist/connectionState.d.ts +31 -0
  26. package/dist/connectionState.js +4 -0
  27. package/dist/connectionState.js.map +1 -0
  28. package/dist/guards/answerGuard.d.ts +14 -0
  29. package/dist/guards/answerGuard.js +189 -0
  30. package/dist/guards/answerGuard.js.map +1 -0
  31. package/dist/guards/chatGuard.d.ts +18 -0
  32. package/dist/guards/chatGuard.js +62 -0
  33. package/dist/guards/chatGuard.js.map +1 -0
  34. package/dist/guards/envelopes.d.ts +8 -0
  35. package/dist/guards/envelopes.js +49 -0
  36. package/dist/guards/envelopes.js.map +1 -0
  37. package/dist/guards/index.d.ts +8 -0
  38. package/dist/guards/index.js +8 -0
  39. package/dist/guards/index.js.map +1 -0
  40. package/dist/guards/policy.d.ts +28 -0
  41. package/dist/guards/policy.js +20 -0
  42. package/dist/guards/policy.js.map +1 -0
  43. package/dist/guards/questionGuard.d.ts +8 -0
  44. package/dist/guards/questionGuard.js +53 -0
  45. package/dist/guards/questionGuard.js.map +1 -0
  46. package/dist/index.d.ts +22 -0
  47. package/dist/index.js +16 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/mcpToolSource.d.ts +13 -0
  50. package/dist/mcpToolSource.js +54 -0
  51. package/dist/mcpToolSource.js.map +1 -0
  52. package/dist/toolLoop.d.ts +18 -0
  53. package/dist/toolLoop.js +153 -0
  54. package/dist/toolLoop.js.map +1 -0
  55. package/dist/types.d.ts +98 -0
  56. package/dist/types.js +6 -0
  57. package/dist/types.js.map +1 -0
  58. package/dist/visitorBrowser.d.ts +17 -0
  59. package/dist/visitorBrowser.js +72 -0
  60. package/dist/visitorBrowser.js.map +1 -0
  61. package/dist/walletProvider.d.ts +25 -0
  62. package/dist/walletProvider.js +42 -0
  63. package/dist/walletProvider.js.map +1 -0
  64. package/dist/webAccounts/finishSignIn.d.ts +2 -0
  65. package/dist/webAccounts/finishSignIn.js +46 -0
  66. package/dist/webAccounts/finishSignIn.js.map +1 -0
  67. package/dist/webAccounts/openAiCompatibleSession.d.ts +15 -0
  68. package/dist/webAccounts/openAiCompatibleSession.js +84 -0
  69. package/dist/webAccounts/openAiCompatibleSession.js.map +1 -0
  70. package/dist/webAccounts/openAiWire.d.ts +39 -0
  71. package/dist/webAccounts/openAiWire.js +133 -0
  72. package/dist/webAccounts/openAiWire.js.map +1 -0
  73. package/dist/webAccounts/openRouterAccount.d.ts +3 -0
  74. package/dist/webAccounts/openRouterAccount.js +64 -0
  75. package/dist/webAccounts/openRouterAccount.js.map +1 -0
  76. package/dist/webAccounts/pkce.d.ts +2 -0
  77. package/dist/webAccounts/pkce.js +17 -0
  78. package/dist/webAccounts/pkce.js.map +1 -0
  79. package/dist/webAccounts/serverSentEvents.d.ts +1 -0
  80. package/dist/webAccounts/serverSentEvents.js +62 -0
  81. package/dist/webAccounts/serverSentEvents.js.map +1 -0
  82. package/dist/webAccounts/signInWindow.d.ts +27 -0
  83. package/dist/webAccounts/signInWindow.js +164 -0
  84. package/dist/webAccounts/signInWindow.js.map +1 -0
  85. package/dist/webAccounts/tensorPassAccount.d.ts +9 -0
  86. package/dist/webAccounts/tensorPassAccount.js +128 -0
  87. package/dist/webAccounts/tensorPassAccount.js.map +1 -0
  88. package/dist/webAccounts/tensorPassPlan.d.ts +27 -0
  89. package/dist/webAccounts/tensorPassPlan.js +36 -0
  90. package/dist/webAccounts/tensorPassPlan.js.map +1 -0
  91. package/dist/webAccounts/webAccount.d.ts +30 -0
  92. package/dist/webAccounts/webAccount.js +19 -0
  93. package/dist/webAccounts/webAccount.js.map +1 -0
  94. package/dist/webAccounts/webAccountSource.d.ts +43 -0
  95. package/dist/webAccounts/webAccountSource.js +216 -0
  96. package/dist/webAccounts/webAccountSource.js.map +1 -0
  97. package/dist/webAccounts/webAccountStore.d.ts +27 -0
  98. package/dist/webAccounts/webAccountStore.js +84 -0
  99. package/dist/webAccounts/webAccountStore.js.map +1 -0
  100. package/dist/wireProtocols/anthropicMessages.d.ts +2 -0
  101. package/dist/wireProtocols/anthropicMessages.js +181 -0
  102. package/dist/wireProtocols/anthropicMessages.js.map +1 -0
  103. package/dist/wireProtocols/eventStream.d.ts +4 -0
  104. package/dist/wireProtocols/eventStream.js +32 -0
  105. package/dist/wireProtocols/eventStream.js.map +1 -0
  106. package/dist/wireProtocols/geminiContents.d.ts +2 -0
  107. package/dist/wireProtocols/geminiContents.js +201 -0
  108. package/dist/wireProtocols/geminiContents.js.map +1 -0
  109. package/dist/wireProtocols/openAiChat.d.ts +2 -0
  110. package/dist/wireProtocols/openAiChat.js +161 -0
  111. package/dist/wireProtocols/openAiChat.js.map +1 -0
  112. package/dist/wireProtocols/openAiResponses.d.ts +2 -0
  113. package/dist/wireProtocols/openAiResponses.js +226 -0
  114. package/dist/wireProtocols/openAiResponses.js.map +1 -0
  115. package/dist/wireProtocols/walletAnswer.d.ts +7 -0
  116. package/dist/wireProtocols/walletAnswer.js +50 -0
  117. package/dist/wireProtocols/walletAnswer.js.map +1 -0
  118. package/dist/wireProtocols/walletFetch.d.ts +3 -0
  119. package/dist/wireProtocols/walletFetch.js +101 -0
  120. package/dist/wireProtocols/walletFetch.js.map +1 -0
  121. package/dist/wireProtocols/wireProtocol.d.ts +31 -0
  122. package/dist/wireProtocols/wireProtocol.js +44 -0
  123. package/dist/wireProtocols/wireProtocol.js.map +1 -0
  124. package/package.json +61 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolLoop.js","sourceRoot":"","sources":["../src/toolLoop.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,qGAAqG;AACrG,yGAAyG;AACzG,sGAAsG;AACtG,mGAAmG;AACnG,sGAAsG;AACtG,sGAAsG;AACtG,qGAAqG;AACrG,qGAAqG;AAErG,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAKlD,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,sFAAsF;AACtF,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,WAAW,GAAG,wCAAwC,CAAC;AAC7D,MAAM,cAAc,GAAG,+CAA+C,CAAC;AAiCvE,SAAS,WAAW,CAAC,KAAgB,EAAE,MAAmC,EAAE,GAAe;IACzF,IAAI,QAAQ,GAAG,EAAE,CAAC;IAClB,IAAI,IAAI,GAAsB,IAAI,CAAC;IACnC,OAAO;QACL,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YAChB,IAAI,IAAI,EAAE,CAAC;gBACT,OAAO;YACT,CAAC;YACD,QAAQ,IAAI,KAAK,CAAC;YAClB,MAAM,OAAO,GAAG,KAAK,CAAC,WAAW,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;YAClD,IAAI,CAAC,OAAO,CA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AAO,GAAG,CAAC,KAAK,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,QAAuB;IACjD,MAAM,IAAI,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7B,OAAO,IAAI,EAAE,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AAClD,CAAC","sourcesContent":["// The agent loop run in the browser: the user's model answers or asks for tools, the site's tools\n// run, their results go back to the model, until it answers in plain text. A tool runs only when the\n// loop offered it to the model at that step: a call to any other name gets a tool error and stays out of\n// the site's tools. With the conversation's guards, the loop stops a question that tries to take over\n// the model before it leaves the page, sends the instructions and the tool results in their salted\n// envelopes, and checks the answer at each piece it streams: from the first piece that trips a guard,\n// the text stops reaching the page, the model's answer is cut, and the loop throws a `GuardStop`. The\n// pieces before that one already reached the page, and the visitor's browser holds the whole answer:\n// what must stay out of a visitor's reach is held back on the site's server (see `checkToolResult`).\n\nimport { textOf } from './chatContent.ts';\nimport { GuardStop } from './guards/chatGuard.ts';\nimport type { ChatGuard } from './guards/chatGuard.ts';\nimport type { AnswerStop } from './guards/policy.ts';\nimport type { AssistantMessage, ChatMessage, ProviderSession, ToolCall, ToolDefinition, ToolSource } from './types.ts';\n\nconst DEFAULT_MAX_STEPS = 6;\n// The tool calls run for one answer of the model. The calls past it get a tool error.\nconst DEFAULT_MAX_TOOL_CALLS = 8;\nconst NOT_OFFERED = 'Tool error: this tool is not available';\nconst TOO_MANY_CALLS = 'Tool error: too many tool calls in one answer';\n\nexport interface ConversationHooks {\n onText?: (delta: string) => void;\n onToolCall?: (call: ToolCall) => void;\n // The tool's own result, as the site's tool returned it, outside the envelope the model reads.\n onToolResult?: (call: ToolCall, result: string) => void;\n}\n\nexport interface ConversationOptions extends ConversationHooks {\n session: ProviderSession;\n messages: ChatMessage[];\n tools?: ToolSource;\n maxSteps?: number;\n maxToolCalls?: number;\n signal?: AbortSignal;\n // The guards of the conversation, from `createChatGuard`, kept for all its questions.\n guard?: ChatGuard;\n}\n\n// The answer's text as it streams, checked with everything streamed before it in the question.\ninterface StreamWatch {\n onText: (delta: string) => void;\n stopped: () => AnswerStop | null;\n}\n\ninterface ConversationRun {\n options: ConversationOptions;\n added: ChatMessage[];\n signal?: AbortSignal;\n watch?: StreamWatch;\n}\n\nfunction watchStream(guard: ChatGuard, onText: ConversationHooks['onText'], cut: () => void): StreamWatch {\n let streamed = '';\n let stop: AnswerStop | null = null;\n return {\n onText: (delta) => {\n if (stop) {\n return;\n }\n streamed += delta;\n const verdict = guard.checkAnswer(streamed, true);\n if (!verdict.ok) {\n stop = verdict.reason;\n cut();\n return;\n }\n onText?.(delta);\n },\n stopped: () => stop,\n };\n}\n\n// The guarded run of a question: its question checked, and a signal that also cuts the model's answer\n// when the stream trips a guard.\nfunction startRun(options: ConversationOptions): ConversationRun {\n const { guard } = options;\n if (!guard) {\n return { options, added: [], signal: options.signal };\n }\n guard.remember(options.messages);\n const question = options.messages.findLast((message) => message.role === 'user');\n const verdict = question ? guard.checkQuestion(textOf(question.content)) : { ok: true as const };\n if (!verdict.ok) {\n throw new GuardStop('question', verdict.reason);\n }\n const cut = new AbortController();\n const signal = options.signal ? AbortSignal.any([options.signal, cut.signal]) : cut.signal;\n return { options, added: [], signal, watch: watchStream(guard, options.onText, () => cut.abort()) };\n}\n\nasync function askModel(run: ConversationRun, tools?: ToolDefinition[]): Promise<AssistantMessage> {\n const { options, signal, watch } = run;\n const messages = [...options.messages, ...run.added];\n let message: AssistantMessage;\n try {\n ({ message } = await options.session.chat({\n messages: options.guard ? options.guard.forModel(messages) : messages,\n tools,\n signal,\n onText: watch ? watch.onText : options.onText,\n }));\n } catch (error) {\n const stop = watch?.stopped();\n throw stop ? new GuardStop('answer', stop) : error;\n }\n const stop = watch?.stopped();\n if (stop) {\n throw new GuardStop('answer', stop);\n }\n // A provider that answers in one piece streams nothing, so the whole answer is checked as well.\n const verdict = options.guard?.checkAnswer(message.content);\n if (verdict && !verdict.ok) {\n throw new GuardStop('answer', verdict.reason);\n }\n return message;\n}\n\nasync function runToolCall(tools: ToolSource, call: ToolCall, hooks: ConversationHooks): Promise<ChatMessage> {\n hooks.onToolCall?.(call);\n let content: string;\n try {\n content = await tools.callTool(call.name, call.arguments);\n } catch (error) {\n content = `Tool error: ${error instanceof Error ? error.message : String(error)}`;\n }\n hooks.onToolResult?.(call, content);\n return { role: 'tool', toolCallId: call.id, name: call.name, content };\n}\n\n// The tools of one step: the site's source and the definitions the model was offered at that step.\ninterface OfferedTools {\n source: ToolSource;\n definitions: ToolDefinition[];\n}\n\n// The tool error a call gets in place of its run: its tool was not offered, or the answer already ran\n// its share of tools. The words are fixed, since a name the model wrote is no tool result for an answer\n// to repeat.\nfunction refusalOf(call: ToolCall, offered: ToolDefinition[], hasRoom: boolean): ChatMessage | null {\n const refuse = (content: string): ChatMessage => ({ role: 'tool', toolCallId: call.id, name: call.name, content });\n if (!offered.some((definition) => definition.name === call.name)) {\n return refuse(NOT_OFFERED);\n }\n return hasRoom ? null : refuse(TOO_MANY_CALLS);\n}\n\n// Answers every call of one model answer, so each call keeps its result in the conversation. A stopped\n// conversation runs no further tool.\nasync function answerToolCalls(run: ConversationRun, calls: ToolCall[], tools: OfferedTools): Promise<ChatMessage[]> {\n const { options } = run;\n const limit = options.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS;\n const results: ChatMessage[] = [];\n let ran = 0;\n for (const call of calls) {\n run.signal?.throwIfAborted();\n const refusal = refusalOf(call, tools.definitions, ran < limit);\n if (refusal) {\n results.push(refusal);\n continue;\n }\n ran += 1;\n const result = await runToolCall(tools.source, call, options);\n options.guard?.remember([result]);\n results.push(result);\n }\n return results;\n}\n\n// The answer that ends the conversation. Tool calls made when no tool was offered are left out, so the\n// conversation ends on the model's text and a provider accepts it as it is.\nfunction concluding(message: AssistantMessage): AssistantMessage {\n return message.toolCalls?.length ? { role: 'assistant', content: message.content } : message;\n}\n\n// Returns the messages the conversation gained: assistant turns and tool results, ending with\n// the final assistant answer.\nexport async function runConversation(options: ConversationOptions): Promise<ChatMessage[]> {\n const run = startRun(options);\n const { tools } = options;\n const definitions = tools ? await tools.listTools() : undefined;\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n\n for (let step = 0; step < maxSteps; step += 1) {\n // The last step offers no tools, so the model has to conclude.\n const offered = step < maxSteps - 1 ? definitions : undefined;\n const message = await askModel(run, offered);\n if (!tools || !offered || !message.toolCalls?.length) {\n run.added.push(concluding(message));\n return run.added;\n }\n run.added.push(message);\n run.added.push(...await answerToolCalls(run, message.toolCalls, { source: tools, definitions: offered }));\n }\n return run.added;\n}\n\nexport function finalAnswer(messages: ChatMessage[]): AssistantMessage | null {\n const last = messages.at(-1);\n return last?.role === 'assistant' ? last : null;\n}\n"]}
@@ -0,0 +1,98 @@
1
+ export type JsonSchema = Record<string, unknown>;
2
+ export interface ToolCall {
3
+ id: string;
4
+ name: string;
5
+ arguments: Record<string, unknown>;
6
+ }
7
+ export interface TextPart {
8
+ type: 'text';
9
+ text: string;
10
+ }
11
+ export interface ImagePart {
12
+ type: 'image';
13
+ url: string;
14
+ }
15
+ export type ContentPart = TextPart | ImagePart;
16
+ export interface SystemMessage {
17
+ role: 'system';
18
+ content: string;
19
+ }
20
+ export interface UserMessage {
21
+ role: 'user';
22
+ content: string | ContentPart[];
23
+ }
24
+ export interface AssistantMessage {
25
+ role: 'assistant';
26
+ content: string;
27
+ toolCalls?: ToolCall[];
28
+ }
29
+ export interface ToolMessage {
30
+ role: 'tool';
31
+ toolCallId: string;
32
+ name: string;
33
+ content: string;
34
+ }
35
+ export type ChatMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;
36
+ export interface ToolDefinition {
37
+ name: string;
38
+ description: string;
39
+ inputSchema: JsonSchema;
40
+ }
41
+ export type ToolChoice = 'auto' | 'none' | 'required' | {
42
+ name: string;
43
+ };
44
+ export interface ResponseFormat {
45
+ type: 'json';
46
+ schema?: JsonSchema;
47
+ name?: string;
48
+ strict?: boolean;
49
+ }
50
+ export type GenerationHint = 'maxTokens' | 'temperature' | 'topP' | 'stop';
51
+ export interface GenerationOptions {
52
+ maxTokens?: number;
53
+ temperature?: number;
54
+ topP?: number;
55
+ stop?: string[];
56
+ toolChoice?: ToolChoice;
57
+ responseFormat?: ResponseFormat;
58
+ }
59
+ export interface ChatStart {
60
+ providerName: string;
61
+ model: string;
62
+ }
63
+ export interface ChatRequest {
64
+ messages: ChatMessage[];
65
+ tools?: ToolDefinition[];
66
+ options?: GenerationOptions;
67
+ signal?: AbortSignal;
68
+ onStart?: (start: ChatStart) => void;
69
+ onText?: (delta: string) => void;
70
+ }
71
+ export type FinishReason = 'stop' | 'length' | 'toolCalls' | 'contentFilter';
72
+ export interface Usage {
73
+ inputTokens: number;
74
+ outputTokens: number;
75
+ cachedInputTokens: number;
76
+ }
77
+ export interface ChatResponse {
78
+ message: AssistantMessage;
79
+ finishReason: FinishReason;
80
+ model: string;
81
+ usage?: Usage;
82
+ }
83
+ export interface ProviderSession {
84
+ providerId: string;
85
+ model: string;
86
+ chat(request: ChatRequest): Promise<ChatResponse>;
87
+ }
88
+ export type WalletLink = {
89
+ connected: false;
90
+ } | {
91
+ connected: true;
92
+ providerName: string;
93
+ model?: string;
94
+ };
95
+ export interface ToolSource {
96
+ listTools(): Promise<ToolDefinition[]>;
97
+ callTool(name: string, args: Record<string, unknown>): Promise<string>;
98
+ }
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ // The vocabulary a site and the AI Wallet share: one chat format for every provider, the tools a
2
+ // site offers, and what a site sees of the wallet. The wallet's connectors translate the chat
3
+ // format to each provider's wire protocol and back; `AiConnect.fetch` translates the protocols the
4
+ // AI SDKs speak into it.
5
+ export {};
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,8FAA8F;AAC9F,mGAAmG;AACnG,yBAAyB","sourcesContent":["// The vocabulary a site and the AI Wallet share: one chat format for every provider, the tools a\n// site offers, and what a site sees of the wallet. The wallet's connectors translate the chat\n// format to each provider's wire protocol and back; `AiConnect.fetch` translates the protocols the\n// AI SDKs speak into it.\n\nexport type JsonSchema = Record<string, unknown>;\n\nexport interface ToolCall {\n id: string;\n name: string;\n arguments: Record<string, unknown>;\n}\n\nexport interface TextPart {\n type: 'text';\n text: string;\n}\n\n// An image as a `data:` URL, or an https URL for the providers that fetch images themselves.\nexport interface ImagePart {\n type: 'image';\n url: string;\n}\n\nexport type ContentPart = TextPart | ImagePart;\n\nexport interface SystemMessage {\n role: 'system';\n content: string;\n}\n\nexport interface UserMessage {\n role: 'user';\n content: string | ContentPart[];\n}\n\nexport interface AssistantMessage {\n role: 'assistant';\n content: string;\n toolCalls?: ToolCall[];\n}\n\nexport interface ToolMessage {\n role: 'tool';\n toolCallId: string;\n name: string;\n content: string;\n}\n\nexport type ChatMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: JsonSchema;\n}\n\n// Whether the model may answer in text, must call a tool, or must call the named one.\nexport type ToolChoice = 'auto' | 'none' | 'required' | { name: string };\n\n// An answer in JSON, held to the schema when one is given. `strict` asks the providers that offer\n// it to refuse any schema they cannot enforce exactly.\nexport interface ResponseFormat {\n type: 'json';\n schema?: JsonSchema;\n name?: string;\n strict?: boolean;\n}\n\n// The settings an account may refuse: its connector leaves them out of the call.\nexport type GenerationHint = 'maxTokens' | 'temperature' | 'topP' | 'stop';\n\n// What the site asks of the answer. The hints above are left out where the account refuses them;\n// a tool choice and a response format always reach the provider.\nexport interface GenerationOptions {\n maxTokens?: number;\n temperature?: number;\n topP?: number;\n stop?: string[];\n toolChoice?: ToolChoice;\n responseFormat?: ResponseFormat;\n}\n\n// Who answers a chat: the display name of the account, such as `Claude`, and the model the wallet\n// asks it for. A site on Auto learns it here, since the wallet picks the account for each answer.\nexport interface ChatStart {\n providerName: string;\n model: string;\n}\n\nexport interface ChatRequest {\n messages: ChatMessage[];\n tools?: ToolDefinition[];\n options?: GenerationOptions;\n signal?: AbortSignal;\n // On a site, the wallet's session calls it once, before the first text or the result.\n onStart?: (start: ChatStart) => void;\n onText?: (delta: string) => void;\n}\n\n// Why the answer ended: it was complete, it reached the token limit, it calls tools, or the\n// provider's filter stopped it.\nexport type FinishReason = 'stop' | 'length' | 'toolCalls' | 'contentFilter';\n\n// The tokens the provider counted for the call. `inputTokens` includes `cachedInputTokens`.\nexport interface Usage {\n inputTokens: number;\n outputTokens: number;\n cachedInputTokens: number;\n}\n\nexport interface ChatResponse {\n message: AssistantMessage;\n finishReason: FinishReason;\n // The model that answered, as the provider named it.\n model: string;\n // Absent when the provider reports no token counts.\n usage?: Usage;\n}\n\n// A chat session, ready to answer: on a site, the wallet answering with the user's account; in the\n// wallet, a connector calling the provider with the account's credential.\nexport interface ProviderSession {\n providerId: string;\n model: string;\n chat(request: ChatRequest): Promise<ChatResponse>;\n}\n\n// What a site sees of the wallet: whether it may use the visitor's AI, and then which account\n// answers it and on which model.\nexport type WalletLink =\n | { connected: false }\n | { connected: true; providerName: string; model?: string };\n\nexport interface ToolSource {\n listTools(): Promise<ToolDefinition[]>;\n callTool(name: string, args: Record<string, unknown>): Promise<string>;\n}\n"]}
@@ -0,0 +1,17 @@
1
+ export type VisitorBrowser = 'chrome' | 'edge' | 'brave' | 'opera' | 'firefox' | 'safari' | 'other';
2
+ export declare const BROWSER_NAMES: Record<Exclude<VisitorBrowser, 'other'>, string>;
3
+ export interface BrowserSignals {
4
+ userAgent: string;
5
+ brands: string[];
6
+ brave: boolean;
7
+ mobile: boolean;
8
+ }
9
+ /**
10
+ * The browser the signals describe. Safari is named on a Mac, an iPhone and an iPad, where the wallet runs
11
+ * in it; any other browser of a phone or a tablet, or a browser the wallet does not name, is `other`.
12
+ */
13
+ export declare function browserOf({ userAgent, brands, brave, mobile }: BrowserSignals): VisitorBrowser;
14
+ /** The browser this page runs in, or `other` where there is no browser, as on a server. */
15
+ export declare function visitorBrowser(): VisitorBrowser;
16
+ /** Where a visitor on this browser adds AI Wallet. */
17
+ export declare function walletInstallUrl(browser: VisitorBrowser): string;
@@ -0,0 +1,72 @@
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: today every browser goes to the
3
+ // wallet's page, which names the browser in its query; a browser's store listing replaces its address
4
+ // here once the listing is public.
5
+ // The browsers' own names, in Latin script in every language.
6
+ export const BROWSER_NAMES = {
7
+ chrome: 'Chrome',
8
+ edge: 'Edge',
9
+ brave: 'Brave',
10
+ opera: 'Opera',
11
+ firefox: 'Firefox',
12
+ safari: 'Safari',
13
+ };
14
+ const WALLET_PAGE = 'https://tensorpass.app/wallet';
15
+ const MOBILE = /Mobi|Android|iPhone|iPad|iPod/;
16
+ // Safari's user agent, on a Mac as on an iPhone or an iPad, and the other browsers that carry Safari's
17
+ // tokens: Chromium's, Android's own, and the other browsers of iOS, which run on Safari's engine and take
18
+ // no extension.
19
+ const SAFARI = /\bVersion\/[\d.]+.*\bSafari\//;
20
+ const NOT_SAFARI = /\b(Chrome|Chromium|CriOS|FxiOS|EdgiOS|OPiOS)\/|\bAndroid\b/;
21
+ // The brand that names each Chromium browser in `userAgentData`, then the token of its user agent.
22
+ const CHROMIUM = [
23
+ { browser: 'edge', brand: 'Microsoft Edge', token: /\bEdg\// },
24
+ { browser: 'opera', brand: 'Opera', token: /\bOPR\// },
25
+ { browser: 'brave', brand: 'Brave', token: /\bBrave\// },
26
+ ];
27
+ /**
28
+ * The browser the signals describe. Safari is named on a Mac, an iPhone and an iPad, where the wallet runs
29
+ * in it; any other browser of a phone or a tablet, or a browser the wallet does not name, is `other`.
30
+ */
31
+ export function browserOf({ userAgent, brands, brave, mobile }) {
32
+ if (!brave && SAFARI.test(userAgent) && !NOT_SAFARI.test(userAgent)) {
33
+ return 'safari';
34
+ }
35
+ if (mobile || MOBILE.test(userAgent)) {
36
+ return 'other';
37
+ }
38
+ if (brave) {
39
+ return 'brave';
40
+ }
41
+ const chromium = CHROMIUM.find(({ brand, token }) => brands.includes(brand) || token.test(userAgent));
42
+ if (chromium) {
43
+ return chromium.browser;
44
+ }
45
+ // Chromium itself, and the browsers built on it that name no brand of their own, install from the
46
+ // Chrome Web Store as Chrome does.
47
+ if (brands.includes('Google Chrome') || brands.includes('Chromium') || /\bChrome\//.test(userAgent)) {
48
+ return /\b(Vivaldi|YaBrowser|SamsungBrowser)\//.test(userAgent) ? 'other' : 'chrome';
49
+ }
50
+ if (/\bFirefox\//.test(userAgent)) {
51
+ return 'firefox';
52
+ }
53
+ return 'other';
54
+ }
55
+ /** The browser this page runs in, or `other` where there is no browser, as on a server. */
56
+ export function visitorBrowser() {
57
+ const nav = globalThis.navigator;
58
+ if (!nav?.userAgent) {
59
+ return 'other';
60
+ }
61
+ return browserOf({
62
+ userAgent: nav.userAgent,
63
+ brands: nav.userAgentData?.brands?.map((entry) => entry.brand) ?? [],
64
+ brave: nav.brave !== undefined,
65
+ mobile: nav.userAgentData?.mobile === true,
66
+ });
67
+ }
68
+ /** Where a visitor on this browser adds AI Wallet. */
69
+ export function walletInstallUrl(browser) {
70
+ return browser === 'other' ? WALLET_PAGE : `${WALLET_PAGE}?browser=${browser}`;
71
+ }
72
+ //# sourceMappingURL=visitorBrowser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visitorBrowser.js","sourceRoot":"","sources":["../src/visitorBrowser.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,uGAAuG;AACvG,sGAAsG;AACtG,mCAAmC;AAInC,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;AAW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IAClG,mCAAmC;IACnC,IAAI,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;QACpG,OAAO,wCAAwC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC;IACvF,CAAC;IACD,IAAI,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;QAClC,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAQD,2FAA2F;AAC3F,MAAM,UAAU,cAAc;IAC5B,MAAM,GAAG,GAAI,UAA+C,CAAC,SAAS,CAAC;IACvE,IAAI,CAAC,GAAG,EAAE,SAAS,EAAE,CAAC;QACpB,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,SAAS,CAAC;QACf,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,MAAM,EAAE,GAAG,CAAC,aAAa,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE;QACpE,KAAK,EAAE,GAAG,CAAC,KAAK,KAAK,SAAS;QAC9B,MAAM,EAAE,GAAG,CAAC,aAAa,EAAE,MAAM,KAAK,IAAI;KAC3C,CAAC,CAAC;AACL,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,gBAAgB,CAAC,OAAuB;IACtD,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,GAAG,WAAW,YAAY,OAAO,EAAE,CAAC;AACjF,CAAC","sourcesContent":["// The visitor's browser, which names the button that adds AI Wallet and picks where it installs from.\n// This is the one place that knows where each browser gets the wallet: today every browser goes to the\n// wallet's page, which names the browser in its query; a browser's store listing replaces its address\n// here once the listing is public.\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';\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/** Where a visitor on this browser adds AI Wallet. */\nexport function walletInstallUrl(browser: VisitorBrowser): string {\n return browser === 'other' ? WALLET_PAGE : `${WALLET_PAGE}?browser=${browser}`;\n}\n"]}
@@ -0,0 +1,25 @@
1
+ import type { ChatMessage, ChatStart, GenerationOptions, ToolDefinition, WalletLink } from './types.ts';
2
+ export interface WalletChatParams {
3
+ messages: ChatMessage[];
4
+ tools?: ToolDefinition[];
5
+ options?: GenerationOptions;
6
+ }
7
+ export type ChatEvent = ({
8
+ kind: 'start';
9
+ } & ChatStart) | {
10
+ kind: 'text';
11
+ delta: string;
12
+ };
13
+ export type WalletRefusal = 'declined' | 'closed' | 'interrupted';
14
+ export declare class WalletRequestError extends Error {
15
+ readonly status: number;
16
+ readonly reason?: WalletRefusal;
17
+ readonly code?: string;
18
+ constructor(message: string, status: number, reason?: WalletRefusal, code?: string);
19
+ }
20
+ export interface WalletProvider {
21
+ isAIWallet: true;
22
+ request(method: string, params?: unknown, onEvent?: (event: ChatEvent) => void, signal?: AbortSignal): Promise<unknown>;
23
+ onLink(listener: (link: WalletLink) => void): () => void;
24
+ }
25
+ export declare function findWallet(): Promise<WalletProvider | null>;
@@ -0,0 +1,42 @@
1
+ // The AI Wallet as a page sees it: `window.aiwallet`, which the extension announces to every page.
2
+ // The extension's page script runs before the site's code, so the wallet is there on load; the
3
+ // announce event covers a script that runs later.
4
+ // A request the wallet refused or could not answer. `status` follows HTTP and is set where the
5
+ // failure happens: the provider's own status for a provider error, 401 for a site the visitor has
6
+ // not connected, 403 for a declined connection, a locked wallet or a wallet without an account,
7
+ // 499 for an answer the visitor stopped in the wallet. `reason` says why a connection did not go
8
+ // through, when the visitor's step in the wallet says why.
9
+ export class WalletRequestError extends Error {
10
+ status;
11
+ reason;
12
+ // The code a web account's provider gave its refusal, such as the plan gateway's `plan_inactive`.
13
+ code;
14
+ constructor(message, status, reason, code) {
15
+ super(message);
16
+ this.name = 'WalletRequestError';
17
+ this.status = status;
18
+ this.reason = reason;
19
+ this.code = code;
20
+ }
21
+ }
22
+ // How long a page waits for the wallet to announce itself before concluding it is not installed.
23
+ const ANNOUNCE_WAIT_MS = 300;
24
+ export function findWallet() {
25
+ const present = globalThis.aiwallet;
26
+ if (present?.isAIWallet) {
27
+ return Promise.resolve(present);
28
+ }
29
+ return new Promise((resolve) => {
30
+ const onAnnounce = (event) => {
31
+ window.removeEventListener('aiwallet:announce', onAnnounce);
32
+ resolve(event.detail);
33
+ };
34
+ window.addEventListener('aiwallet:announce', onAnnounce);
35
+ window.dispatchEvent(new Event('aiwallet:request'));
36
+ setTimeout(() => {
37
+ window.removeEventListener('aiwallet:announce', onAnnounce);
38
+ resolve(null);
39
+ }, ANNOUNCE_WAIT_MS);
40
+ });
41
+ }
42
+ //# sourceMappingURL=walletProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walletProvider.js","sourceRoot":"","sources":["../src/walletProvider.ts"],"names":[],"mappings":"AAAA,mGAAmG;A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AC;QAChB,CAAC,EAAE,gBAAgB,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// The AI Wallet as a page sees it: `window.aiwallet`, which the extension announces to every page.\n// The extension's page script runs before the site's code, so the wallet is there on load; the\n// announce event covers a script that runs later.\n\nimport type { ChatMessage, ChatStart, GenerationOptions, ToolDefinition, WalletLink } from './types.ts';\n\n// What a site sends with a `chat` request.\nexport interface WalletChatParams {\n messages: ChatMessage[];\n tools?: ToolDefinition[];\n options?: GenerationOptions;\n}\n\n// What a chat streams to the page before its result: one `start` naming who answers, sent before\n// the first text or, when the answer has no text, before the result; then each piece of text.\nexport type ChatEvent = ({ kind: 'start' } & ChatStart) | { kind: 'text'; delta: string };\n\n// Why a connection did not go through when the visitor's own step in the wallet says why: they\n// declined the site, closed the wallet's window before finishing, or the wallet stopped before it\n// answered. The site words each one in the page's language, with the next step.\nexport type WalletRefusal = 'declined' | 'closed' | 'interrupted';\n\n// A request the wallet refused or could not answer. `status` follows HTTP and is set where the\n// failure happens: the provider's own status for a provider error, 401 for a site the visitor has\n// not connected, 403 for a declined connection, a locked wallet or a wallet without an account,\n// 499 for an answer the visitor stopped in the wallet. `reason` says why a connection did not go\n// through, when the visitor's step in the wallet says why.\nexport class WalletRequestError extends Error {\n readonly status: number;\n readonly reason?: WalletRefusal;\n // The code a web account's provider gave its refusal, such as the plan gateway's `plan_inactive`.\n readonly code?: string;\n\n constructor(message: string, status: number, reason?: WalletRefusal, code?: string) {\n super(message);\n this.name = 'WalletRequestError';\n this.status = status;\n this.reason = reason;\n this.code = code;\n }\n}\n\nexport interface WalletProvider {\n isAIWallet: true;\n // A chat streams its events to `onEvent`. Aborting `signal` rejects the request with the signal's\n // reason, and the wallet stops the chat it runs for it.\n request(\n method: string, params?: unknown, onEvent?: (event: ChatEvent) => void, signal?: AbortSignal,\n ): Promise<unknown>;\n // Called when the visitor changes, in the wallet, the account or model this site answers with.\n onLink(listener: (link: WalletLink) => void): () => void;\n}\n\n// How long a page waits for the wallet to announce itself before concluding it is not installed.\nconst ANNOUNCE_WAIT_MS = 300;\n\nexport function findWallet(): Promise<WalletProvider | null> {\n const present = (globalThis as { aiwallet?: WalletProvider }).aiwallet;\n if (present?.isAIWallet) {\n return Promise.resolve(present);\n }\n return new Promise((resolve) => {\n const onAnnounce = (event: Event) => {\n window.removeEventListener('aiwallet:announce', onAnnounce);\n resolve((event as CustomEvent<WalletProvider>).detail);\n };\n window.addEventListener('aiwallet:announce', onAnnounce);\n window.dispatchEvent(new Event('aiwallet:request'));\n setTimeout(() => {\n window.removeEventListener('aiwallet:announce', onAnnounce);\n resolve(null);\n }, ANNOUNCE_WAIT_MS);\n });\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export type SignInReturn = 'window' | 'redirect' | 'none';
2
+ export declare function finishSignIn(): SignInReturn;
@@ -0,0 +1,46 @@
1
+ // The site's return page of a web sign in, the address a site passes as `signInCallback`. It does one
2
+ // thing on load: in the popup, it hands the provider's answer to the page that opened it and closes; in the
3
+ // tab of a sign in the browser kept out of a popup, it sends the tab back to the page the sign in started
4
+ // from, whose client finishes it. A popup the browser does not let close shows one line saying so. It
5
+ // imports nothing else of the SDK, so the page stays small.
6
+ import { answerIn, redirectedSignIn, returnToOpener, windowMark, withAnswer } from "./signInWindow.js";
7
+ // The line a popup shows when the browser keeps it open, in the languages of the connect window.
8
+ const CLOSE_LINES = {
9
+ en: 'You are signed in. You can close this window.',
10
+ fr: 'Vous êtes connecté. Vous pouvez fermer cette fenêtre.',
11
+ he: 'התחברתם. אפשר לסגור את החלון הזה.',
12
+ ar: 'تم تسجيل دخولك. يمكنك إغلاق هذه النافذة.',
13
+ zh: '你已登录。可以关闭此窗口。',
14
+ };
15
+ function closeLine() {
16
+ const language = (globalThis.navigator?.language ?? 'en').slice(0, 2);
17
+ return CLOSE_LINES[language] ?? CLOSE_LINES.en;
18
+ }
19
+ function showCloseLine() {
20
+ const line = document.createElement('p');
21
+ line.textContent = closeLine();
22
+ line.style.cssText = 'margin:40px auto;max-width:28em;padding:0 16px;font:16px/1.5 system-ui,sans-serif;'
23
+ + 'text-align:center';
24
+ document.body.replaceChildren(line);
25
+ }
26
+ // Runs on the return page's load and answers what the page was: a popup's return, a tab's return, or a
27
+ // visit with no sign in waiting, which leaves the page as it is.
28
+ export function finishSignIn() {
29
+ const mark = windowMark();
30
+ const answer = mark ? answerIn(location.href, mark) : null;
31
+ if (answer) {
32
+ returnToOpener(answer);
33
+ if (!window.closed) {
34
+ showCloseLine();
35
+ }
36
+ return 'window';
37
+ }
38
+ const pending = redirectedSignIn();
39
+ const returned = pending ? answerIn(location.href, pending.state) : null;
40
+ if (!pending || !returned) {
41
+ return 'none';
42
+ }
43
+ location.replace(withAnswer(pending.returnTo, returned));
44
+ return 'redirect';
45
+ }
46
+ //# sourceMappingURL=finishSignIn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"finishSignIn.js","sourceRoot":"","sources":["../../src/webAccounts/finishSignIn.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,4GAA4G;AAC5G,0GAA0G;AAC1G,sGAAsG;AACtG,4DAA4D;AAE5D,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEvG,iGAAiG;AACjG,MAAM,WAAW,GAA2B;IAC1C,EAAE,EAAE,+CAA+C;IACnD,EAAE,EAAE,uDAAuD;IAC3D,EAAE,EAAE,mCAAmC;IACvC,EAAE,EAAE,0CAA0C;IAC9C,EAAE,EAAE,eAAe;CACpB,CAAC;AAIF,SAAS,SAAS;IAChB,MAAM,QAAQ,GAAG,CAAC,UAAU,CAAC,SAAS,EAAE,QAAQ,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACtE,OAAO,WAAW,CAAC,QAAQ,CAAC,IAAI,WAAW,CAAC,EAAE,CAAC;AACjD,CAAC;AAED,SAAS,aAAa;IACpB,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;IACzC,IAAI,CAAC,WAAW,GAAG,SAAS,EAAE,CAAC;IAC/B,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,oFAAoF;UACrG,mBAAmB,CAAC;IACxB,QAAQ,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;AACtC,CAAC;AAED,uGAAuG;AACvG,iEAAiE;AACjE,MAAM,UAAU,YAAY;IAC1B,MAAM,IAAI,GAAG,UAAU,EAAE,CAAC;IAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3D,IAAI,MAAM,EAAE,CAAC;QACX,cAAc,CAAC,MAAM,CAAC,CAAC;QACvB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;YACnB,aAAa,EAAE,CAAC;QAClB,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,MAAM,OAAO,GAAG,gBAAgB,EAAE,CAAC;IACnC,MAAM,QAAQ,GAAG,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzE,IAAI,CAAC,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC1B,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;IACzD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["// The site's return page of a web sign in, the address a site passes as `signInCallback`. It does one\n// thing on load: in the popup, it hands the provider's answer to the page that opened it and closes; in the\n// tab of a sign in the browser kept out of a popup, it sends the tab back to the page the sign in started\n// from, whose client finishes it. A popup the browser does not let close shows one line saying so. It\n// imports nothing else of the SDK, so the page stays small.\n\nimport { answerIn, redirectedSignIn, returnToOpener, windowMark, withAnswer } from './signInWindow.ts';\n\n// The line a popup shows when the browser keeps it open, in the languages of the connect window.\nconst CLOSE_LINES: Record<string, string> = {\n en: 'You are signed in. You can close this window.',\n fr: 'Vous êtes connecté. Vous pouvez fermer cette fenêtre.',\n he: 'התחברתם. אפשר לסגור את החלון הזה.',\n ar: 'تم تسجيل دخولك. يمكنك إغلاق هذه النافذة.',\n zh: '你已登录。可以关闭此窗口。',\n};\n\nexport type SignInReturn = 'window' | 'redirect' | 'none';\n\nfunction closeLine(): string {\n const language = (globalThis.navigator?.language ?? 'en').slice(0, 2);\n return CLOSE_LINES[language] ?? CLOSE_LINES.en;\n}\n\nfunction showCloseLine(): void {\n const line = document.createElement('p');\n line.textContent = closeLine();\n line.style.cssText = 'margin:40px auto;max-width:28em;padding:0 16px;font:16px/1.5 system-ui,sans-serif;'\n + 'text-align:center';\n document.body.replaceChildren(line);\n}\n\n// Runs on the return page's load and answers what the page was: a popup's return, a tab's return, or a\n// visit with no sign in waiting, which leaves the page as it is.\nexport function finishSignIn(): SignInReturn {\n const mark = windowMark();\n const answer = mark ? answerIn(location.href, mark) : null;\n if (answer) {\n returnToOpener(answer);\n if (!window.closed) {\n showCloseLine();\n }\n return 'window';\n }\n const pending = redirectedSignIn();\n const returned = pending ? answerIn(location.href, pending.state) : null;\n if (!pending || !returned) {\n return 'none';\n }\n location.replace(withAnswer(pending.returnTo, returned));\n return 'redirect';\n}\n"]}
@@ -0,0 +1,15 @@
1
+ import type { ProviderSession } from '../types.ts';
2
+ import type { WebAccountId } from './webAccountStore.ts';
3
+ export type HttpFetch = (input: string, init: RequestInit) => Promise<Response>;
4
+ export interface WebSessionConfig {
5
+ providerId: WebAccountId;
6
+ providerName: string;
7
+ model: string;
8
+ endpoint: string;
9
+ credential: () => Promise<Record<string, string>>;
10
+ renew: () => Promise<Record<string, string> | null>;
11
+ onRefused: () => void;
12
+ headers?: Record<string, string>;
13
+ fetch?: HttpFetch;
14
+ }
15
+ export declare function webSession(config: WebSessionConfig): ProviderSession;
@@ -0,0 +1,84 @@
1
+ // The chat session of a web account: the site's page calls the account's chat completions endpoint
2
+ // itself, with the visitor's credential, and streams the answer to the conversation loop in the same
3
+ // events the wallet sends. The account names who answers before the first text or the result, a refused
4
+ // call becomes a `WalletRequestError` with the provider's status and its own message, and a call refused
5
+ // with 401 renews the credential once where the account can, then signs the visitor out.
6
+ import { WalletRequestError } from "../walletProvider.js";
7
+ import { AnswerAssembly, requestBody } from "./openAiWire.js";
8
+ import { serverSentEvents } from "./serverSentEvents.js";
9
+ // The characters of a refusal's body read for its message.
10
+ const ERROR_DETAIL_LENGTH = 300;
11
+ // The message OpenRouter and the plan gateway both put in `error.message`, or the start of the body, and
12
+ // the gateway's `error.code`, by which the chat tells a plan without a subscription from other refusals.
13
+ async function refusalOf(config, response) {
14
+ const text = (await response.text().catch(() => '')).slice(0, 4096);
15
+ let message = text.slice(0, ERROR_DETAIL_LENGTH);
16
+ let code;
17
+ try {
18
+ const detail = JSON.parse(text).error;
19
+ message = typeof detail?.message === 'string' ? detail.message : message;
20
+ code = typeof detail?.code === 'string' ? detail.code : undefined;
21
+ }
22
+ catch {
23
+ // The body is not JSON; its start stands as the message.
24
+ }
25
+ const status = response.status;
26
+ return new WalletRequestError(`${config.providerName}: ${message || `HTTP ${status}`}`, status, undefined, code);
27
+ }
28
+ function send(config, headers, request) {
29
+ return (config.fetch ?? fetch)(config.endpoint, {
30
+ method: 'POST',
31
+ signal: request.signal,
32
+ headers: { 'Content-Type': 'application/json', ...config.headers, ...headers },
33
+ body: JSON.stringify(requestBody(config.model, request)),
34
+ });
35
+ }
36
+ async function answered(config, request) {
37
+ let response = await send(config, await config.credential(), request);
38
+ if (response.status === 401) {
39
+ await response.body?.cancel().catch(() => undefined);
40
+ const renewed = await config.renew();
41
+ response = renewed ? await send(config, renewed, request) : response;
42
+ }
43
+ if (response.status === 401) {
44
+ config.onRefused();
45
+ }
46
+ if (!response.ok) {
47
+ throw await refusalOf(config, response);
48
+ }
49
+ return response;
50
+ }
51
+ // A provider that fails after the stream opened sends an event with `error` in place of a chunk.
52
+ function throwStreamError(config, event) {
53
+ const failure = event.error;
54
+ if (failure) {
55
+ const message = typeof failure.message === 'string' ? failure.message : 'the answer stopped';
56
+ const status = typeof failure.code === 'number' ? failure.code : 502;
57
+ throw new WalletRequestError(`${config.providerName}: ${message}`, status);
58
+ }
59
+ }
60
+ async function chat(config, request) {
61
+ const response = await answered(config, request);
62
+ const answer = new AnswerAssembly(config.model);
63
+ let started = false;
64
+ const start = () => {
65
+ if (!started) {
66
+ started = true;
67
+ request.onStart?.({ providerName: config.providerName, model: answer.model });
68
+ }
69
+ };
70
+ for await (const event of serverSentEvents(response)) {
71
+ throwStreamError(config, event);
72
+ const text = answer.add(event);
73
+ if (text) {
74
+ start();
75
+ request.onText?.(text);
76
+ }
77
+ }
78
+ start();
79
+ return answer.response();
80
+ }
81
+ export function webSession(config) {
82
+ return { providerId: config.providerId, model: config.model, chat: (request) => chat(config, request) };
83
+ }
84
+ //# sourceMappingURL=openAiCompatibleSession.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openAiCompatibleSession.js","sourceRoot":"","sources":["../../src/webAccounts/openAiCompatibleSession.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,qGAAqG;AACrG,wGAAwG;AACxG,yGAAyG;AACzG,yFAAyF;AAGzF,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAoBzD,2DAA2D;AAC3D,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,yGAAyG;AACzG,yGAAyG;AACzG,KAAK,UAAU,SAAS,CAAC,MAAwB,EAAE,QAAkB;I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O,CAAC,EAAE,CAAC;AAC1G,CAAC","sourcesContent":["// The chat session of a web account: the site's page calls the account's chat completions endpoint\n// itself, with the visitor's credential, and streams the answer to the conversation loop in the same\n// events the wallet sends. The account names who answers before the first text or the result, a refused\n// call becomes a `WalletRequestError` with the provider's status and its own message, and a call refused\n// with 401 renews the credential once where the account can, then signs the visitor out.\n\nimport type { ChatRequest, ChatResponse, ProviderSession } from '../types.ts';\nimport { WalletRequestError } from '../walletProvider.ts';\nimport { AnswerAssembly, requestBody } from './openAiWire.ts';\nimport type { Chunk } from './openAiWire.ts';\nimport { serverSentEvents } from './serverSentEvents.ts';\nimport type { WebAccountId } from './webAccountStore.ts';\n\nexport type HttpFetch = (input: string, init: RequestInit) => Promise<Response>;\n\nexport interface WebSessionConfig {\n providerId: WebAccountId;\n providerName: string;\n model: string;\n endpoint: string;\n // The headers that carry the credential, read for each call.\n credential: () => Promise<Record<string, string>>;\n // A new credential after a 401, or null where the account has none to renew.\n renew: () => Promise<Record<string, string> | null>;\n // The credential no longer opens the account: the visitor is signed out.\n onRefused: () => void;\n headers?: Record<string, string>;\n fetch?: HttpFetch;\n}\n\n// The characters of a refusal's body read for its message.\nconst ERROR_DETAIL_LENGTH = 300;\n\n// The message OpenRouter and the plan gateway both put in `error.message`, or the start of the body, and\n// the gateway's `error.code`, by which the chat tells a plan without a subscription from other refusals.\nasync function refusalOf(config: WebSessionConfig, response: Response): Promise<WalletRequestError> {\n const text = (await response.text().catch(() => '')).slice(0, 4096);\n let message = text.slice(0, ERROR_DETAIL_LENGTH);\n let code: string | undefined;\n try {\n const detail = (JSON.parse(text) as { error?: { message?: unknown; code?: unknown } }).error;\n message = typeof detail?.message === 'string' ? detail.message : message;\n code = typeof detail?.code === 'string' ? detail.code : undefined;\n } catch {\n // The body is not JSON; its start stands as the message.\n }\n const status = response.status;\n return new WalletRequestError(`${config.providerName}: ${message || `HTTP ${status}`}`, status, undefined, code);\n}\n\nfunction send(config: WebSessionConfig, headers: Record<string, string>, request: ChatRequest): Promise<Response> {\n return (config.fetch ?? fetch)(config.endpoint, {\n method: 'POST',\n signal: request.signal,\n headers: { 'Content-Type': 'application/json', ...config.headers, ...headers },\n body: JSON.stringify(requestBody(config.model, request)),\n });\n}\n\nasync function answered(config: WebSessionConfig, request: ChatRequest): Promise<Response> {\n let response = await send(config, await config.credential(), request);\n if (response.status === 401) {\n await response.body?.cancel().catch(() => undefined);\n const renewed = await config.renew();\n response = renewed ? await send(config, renewed, request) : response;\n }\n if (response.status === 401) {\n config.onRefused();\n }\n if (!response.ok) {\n throw await refusalOf(config, response);\n }\n return response;\n}\n\n// A provider that fails after the stream opened sends an event with `error` in place of a chunk.\nfunction throwStreamError(config: WebSessionConfig, event: Record<string, unknown>): void {\n const failure = event.error as { message?: unknown; code?: unknown } | undefined;\n if (failure) {\n const message = typeof failure.message === 'string' ? failure.message : 'the answer stopped';\n const status = typeof failure.code === 'number' ? failure.code : 502;\n throw new WalletRequestError(`${config.providerName}: ${message}`, status);\n }\n}\n\nasync function chat(config: WebSessionConfig, request: ChatRequest): Promise<ChatResponse> {\n const response = await answered(config, request);\n const answer = new AnswerAssembly(config.model);\n let started = false;\n const start = () => {\n if (!started) {\n started = true;\n request.onStart?.({ providerName: config.providerName, model: answer.model });\n }\n };\n for await (const event of serverSentEvents(response)) {\n throwStreamError(config, event);\n const text = answer.add(event as Chunk);\n if (text) {\n start();\n request.onText?.(text);\n }\n }\n start();\n return answer.response();\n}\n\nexport function webSession(config: WebSessionConfig): ProviderSession {\n return { providerId: config.providerId, model: config.model, chat: (request) => chat(config, request) };\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import type { ChatRequest, ChatResponse } from '../types.ts';
2
+ interface ToolCallDelta {
3
+ index: number;
4
+ id?: string;
5
+ function?: {
6
+ name?: string;
7
+ arguments?: string;
8
+ };
9
+ }
10
+ interface WireUsage {
11
+ prompt_tokens?: number;
12
+ completion_tokens?: number;
13
+ prompt_tokens_details?: {
14
+ cached_tokens?: number;
15
+ };
16
+ }
17
+ export interface Chunk {
18
+ model?: string;
19
+ usage?: WireUsage;
20
+ choices?: {
21
+ delta?: {
22
+ content?: string | null;
23
+ tool_calls?: ToolCallDelta[];
24
+ };
25
+ finish_reason?: string | null;
26
+ }[];
27
+ }
28
+ export declare function requestBody(model: string, request: ChatRequest): Record<string, unknown>;
29
+ export declare class AnswerAssembly {
30
+ content: string;
31
+ model: string;
32
+ private reason;
33
+ private usage;
34
+ private readonly partials;
35
+ constructor(model: string);
36
+ add(chunk: Chunk): string;
37
+ response(): ChatResponse;
38
+ }
39
+ export {};