@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,133 @@
1
+ // The OpenAI chat completions protocol as a web account speaks it: the chat format written as a request
2
+ // body, and the streamed chunks gathered back into one answer, its tool calls rebuilt from their deltas.
3
+ // OpenRouter and TensorPass's plan gateway both answer in it.
4
+ // The name OpenAI requires on a JSON schema, for a site that gave its schema none.
5
+ const SCHEMA_NAME = 'answer';
6
+ const FINISH_REASONS = {
7
+ stop: 'stop',
8
+ length: 'length',
9
+ tool_calls: 'toolCalls',
10
+ function_call: 'toolCalls',
11
+ content_filter: 'contentFilter',
12
+ };
13
+ function wireContent(content) {
14
+ if (typeof content === 'string') {
15
+ return content;
16
+ }
17
+ return content.map((part) => (part.type === 'text'
18
+ ? { type: 'text', text: part.text }
19
+ : { type: 'image_url', image_url: { url: part.url } }));
20
+ }
21
+ function wireMessage(message) {
22
+ if (message.role === 'tool') {
23
+ return { role: 'tool', tool_call_id: message.toolCallId, content: message.content };
24
+ }
25
+ if (message.role === 'assistant' && message.toolCalls?.length) {
26
+ return {
27
+ role: 'assistant',
28
+ content: message.content || null,
29
+ tool_calls: message.toolCalls.map((call) => ({
30
+ id: call.id,
31
+ type: 'function',
32
+ function: { name: call.name, arguments: JSON.stringify(call.arguments) },
33
+ })),
34
+ };
35
+ }
36
+ return { role: message.role, content: wireContent(message.content) };
37
+ }
38
+ function wireTool(tool) {
39
+ const { name, description, inputSchema } = tool;
40
+ return { type: 'function', function: { name, description, parameters: inputSchema } };
41
+ }
42
+ function wireToolChoice(choice) {
43
+ return typeof choice === 'object' ? { type: 'function', function: { name: choice.name } } : choice;
44
+ }
45
+ function wireResponseFormat(format) {
46
+ if (!format) {
47
+ return undefined;
48
+ }
49
+ if (!format.schema) {
50
+ return { type: 'json_object' };
51
+ }
52
+ const { name = SCHEMA_NAME, schema, strict } = format;
53
+ return { type: 'json_schema', json_schema: { name, schema, strict } };
54
+ }
55
+ // Fields left undefined are dropped by the JSON encoding.
56
+ export function requestBody(model, request) {
57
+ const options = request.options ?? {};
58
+ return {
59
+ model,
60
+ stream: true,
61
+ stream_options: { include_usage: true },
62
+ messages: request.messages.map(wireMessage),
63
+ tools: request.tools?.length ? request.tools.map(wireTool) : undefined,
64
+ tool_choice: wireToolChoice(options.toolChoice),
65
+ response_format: wireResponseFormat(options.responseFormat),
66
+ max_tokens: options.maxTokens,
67
+ temperature: options.temperature,
68
+ top_p: options.topP,
69
+ stop: options.stop?.length ? options.stop : undefined,
70
+ };
71
+ }
72
+ function parseArguments(raw) {
73
+ if (!raw.trim()) {
74
+ return {};
75
+ }
76
+ try {
77
+ return JSON.parse(raw);
78
+ }
79
+ catch {
80
+ return {};
81
+ }
82
+ }
83
+ // The answer as its chunks arrive: the text, the tool calls, the finish reason, the model and the usage
84
+ // the provider reports on its last chunk.
85
+ export class AnswerAssembly {
86
+ content = '';
87
+ model;
88
+ reason;
89
+ usage;
90
+ partials = [];
91
+ constructor(model) {
92
+ this.model = model;
93
+ }
94
+ // Takes one chunk and returns the text it adds.
95
+ add(chunk) {
96
+ this.model = chunk.model || this.model;
97
+ this.usage = chunk.usage ?? this.usage;
98
+ const choice = chunk.choices?.[0];
99
+ this.reason = choice?.finish_reason || this.reason;
100
+ for (const delta of choice?.delta?.tool_calls ?? []) {
101
+ const partial = (this.partials[delta.index] ??= { id: '', name: '', arguments: '' });
102
+ partial.id ||= delta.id ?? '';
103
+ partial.name += delta.function?.name ?? '';
104
+ partial.arguments += delta.function?.arguments ?? '';
105
+ }
106
+ const text = choice?.delta?.content ?? '';
107
+ this.content += text;
108
+ return text;
109
+ }
110
+ response() {
111
+ const toolCalls = this.partials.filter(Boolean).map((partial, index) => ({
112
+ id: partial.id || `call_${index}`, name: partial.name, arguments: parseArguments(partial.arguments),
113
+ }));
114
+ const finishReason = toolCalls.length ? 'toolCalls' : FINISH_REASONS[this.reason ?? ''] ?? 'stop';
115
+ return {
116
+ message: { role: 'assistant', content: this.content, ...(toolCalls.length ? { toolCalls } : {}) },
117
+ finishReason,
118
+ model: this.model,
119
+ usage: usageOf(this.usage),
120
+ };
121
+ }
122
+ }
123
+ function usageOf(usage) {
124
+ if (!usage) {
125
+ return undefined;
126
+ }
127
+ return {
128
+ inputTokens: usage.prompt_tokens ?? 0,
129
+ outputTokens: usage.completion_tokens ?? 0,
130
+ cachedInputTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,
131
+ };
132
+ }
133
+ //# sourceMappingURL=openAiWire.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openAiWire.js","sourceRoot":"","sources":["../../src/webAccounts/openAiWire.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,yGAAyG;AACzG,8DAA8D;AAO9D,mFAAmF;AACnF,MAAM,WAAW,GAAG,QAAQ,CAAC;AAE7B,MAAM,cAAc,GAAiC;IACnD,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;IAChB,UAAU,EAAE,WAAW;IACvB,aAAa,EAAE,WAAW;IAC1B,cAAc,EAAE,eAAe;CAChC,CAAC;AAoBF,SAAS,WAAW,CAAC,OAA+B;IAClD,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM;QAChD,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,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KAAK,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF;AAED,SAAS,OAAO,CAAC,KAA4B;IAC3C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,aAAa,IAAI,CAAC;QACrC,YAAY,EAAE,KAAK,CAAC,iBAAiB,IAAI,CAAC;QAC1C,iBAAiB,EAAE,KAAK,CAAC,qBAAqB,EAAE,aAAa,IAAI,CAAC;KACnE,CAAC;AACJ,CAAC","sourcesContent":["// The OpenAI chat completions protocol as a web account speaks it: the chat format written as a request\n// body, and the streamed chunks gathered back into one answer, its tool calls rebuilt from their deltas.\n// OpenRouter and TensorPass's plan gateway both answer in it.\n\nimport type {\n ChatMessage, ChatRequest, ChatResponse, ContentPart, FinishReason, ResponseFormat, ToolCall, ToolChoice,\n ToolDefinition, Usage,\n} from '../types.ts';\n\n// The name OpenAI requires on a JSON schema, for a site that gave its schema none.\nconst SCHEMA_NAME = 'answer';\n\nconst FINISH_REASONS: Record<string, FinishReason> = {\n stop: 'stop',\n length: 'length',\n tool_calls: 'toolCalls',\n function_call: 'toolCalls',\n content_filter: 'contentFilter',\n};\n\ninterface ToolCallDelta {\n index: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n}\n\ninterface WireUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n prompt_tokens_details?: { cached_tokens?: number };\n}\n\nexport interface Chunk {\n model?: string;\n usage?: WireUsage;\n choices?: { delta?: { content?: string | null; tool_calls?: ToolCallDelta[] }; finish_reason?: string | null }[];\n}\n\nfunction wireContent(content: string | ContentPart[]) {\n if (typeof content === 'string') {\n return content;\n }\n return content.map((part) => (part.type === 'text'\n ? { type: 'text', text: part.text }\n : { type: 'image_url', image_url: { url: part.url } }));\n}\n\nfunction wireMessage(message: ChatMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content };\n }\n if (message.role === 'assistant' && message.toolCalls?.length) {\n return {\n role: 'assistant',\n content: message.content || null,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: JSON.stringify(call.arguments) },\n })),\n };\n }\n return { role: message.role, content: wireContent(message.content) };\n}\n\nfunction wireTool(tool: ToolDefinition): Record<string, unknown> {\n const { name, description, inputSchema } = tool;\n return { type: 'function', function: { name, description, parameters: inputSchema } };\n}\n\nfunction wireToolChoice(choice?: ToolChoice) {\n return typeof choice === 'object' ? { type: 'function', function: { name: choice.name } } : choice;\n}\n\nfunction wireResponseFormat(format?: ResponseFormat) {\n if (!format) {\n return undefined;\n }\n if (!format.schema) {\n return { type: 'json_object' };\n }\n const { name = SCHEMA_NAME, schema, strict } = format;\n return { type: 'json_schema', json_schema: { name, schema, strict } };\n}\n\n// Fields left undefined are dropped by the JSON encoding.\nexport function requestBody(model: string, request: ChatRequest): Record<string, unknown> {\n const options = request.options ?? {};\n return {\n model,\n stream: true,\n stream_options: { include_usage: true },\n messages: request.messages.map(wireMessage),\n tools: request.tools?.length ? request.tools.map(wireTool) : undefined,\n tool_choice: wireToolChoice(options.toolChoice),\n response_format: wireResponseFormat(options.responseFormat),\n max_tokens: options.maxTokens,\n temperature: options.temperature,\n top_p: options.topP,\n stop: options.stop?.length ? options.stop : undefined,\n };\n}\n\nfunction parseArguments(raw: string): Record<string, unknown> {\n if (!raw.trim()) {\n return {};\n }\n try {\n return JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return {};\n }\n}\n\n// The answer as its chunks arrive: the text, the tool calls, the finish reason, the model and the usage\n// the provider reports on its last chunk.\nexport class AnswerAssembly {\n content = '';\n model: string;\n private reason: string | undefined;\n private usage: WireUsage | undefined;\n private readonly partials: { id: string; name: string; arguments: string }[] = [];\n\n constructor(model: string) {\n this.model = model;\n }\n\n // Takes one chunk and returns the text it adds.\n add(chunk: Chunk): string {\n this.model = chunk.model || this.model;\n this.usage = chunk.usage ?? this.usage;\n const choice = chunk.choices?.[0];\n this.reason = choice?.finish_reason || this.reason;\n for (const delta of choice?.delta?.tool_calls ?? []) {\n const partial = (this.partials[delta.index] ??= { id: '', name: '', arguments: '' });\n partial.id ||= delta.id ?? '';\n partial.name += delta.function?.name ?? '';\n partial.arguments += delta.function?.arguments ?? '';\n }\n const text = choice?.delta?.content ?? '';\n this.content += text;\n return text;\n }\n\n response(): ChatResponse {\n const toolCalls: ToolCall[] = this.partials.filter(Boolean).map((partial, index) => ({\n id: partial.id || `call_${index}`, name: partial.name, arguments: parseArguments(partial.arguments),\n }));\n const finishReason = toolCalls.length ? 'toolCalls' : FINISH_REASONS[this.reason ?? ''] ?? 'stop';\n return {\n message: { role: 'assistant', content: this.content, ...(toolCalls.length ? { toolCalls } : {}) },\n finishReason,\n model: this.model,\n usage: usageOf(this.usage),\n };\n }\n}\n\nfunction usageOf(usage: WireUsage | undefined): Usage | undefined {\n if (!usage) {\n return undefined;\n }\n return {\n inputTokens: usage.prompt_tokens ?? 0,\n outputTokens: usage.completion_tokens ?? 0,\n cachedInputTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import type { WebAccount, WebAccountContext } from './webAccount.ts';
2
+ export declare const OPENROUTER_DEFAULT_MODEL = "openrouter/auto";
3
+ export declare function openRouterAccount(model: string, context?: WebAccountContext): WebAccount;
@@ -0,0 +1,64 @@
1
+ // OpenRouter for a visitor without the wallet: the site sends the visitor to OpenRouter's sign in with a
2
+ // PKCE challenge, OpenRouter sends them back with a code, and the page trades it for a key bound to the
3
+ // visitor's own credits. Every answer is billed to them. OpenRouter returns the sign in's state with the
4
+ // code, and leaves it out of a refusal.
5
+ // https://openrouter.ai/docs/use-cases/oauth-pkce
6
+ import { jsonOf, replyMessage, WEB_ACCOUNT_NAMES } from "./webAccount.js";
7
+ import { webSession } from "./openAiCompatibleSession.js";
8
+ const AUTHORIZE_URL = 'https://openrouter.ai/auth';
9
+ const KEY_EXCHANGE_URL = 'https://openrouter.ai/api/v1/auth/keys';
10
+ const CHAT_URL = 'https://openrouter.ai/api/v1/chat/completions';
11
+ // OpenRouter's Auto Router, which picks the model for each prompt.
12
+ export const OPENROUTER_DEFAULT_MODEL = 'openrouter/auto';
13
+ const NAME = WEB_ACCOUNT_NAMES.openrouter;
14
+ // OpenRouter credits the site that sent the call by these two headers.
15
+ function siteHeaders() {
16
+ const origin = globalThis.location?.origin;
17
+ return origin ? { 'HTTP-Referer': origin, 'X-Title': globalThis.location.host } : {};
18
+ }
19
+ export function openRouterAccount(model, context = {}) {
20
+ const send = context.fetch ?? fetch;
21
+ return {
22
+ id: 'openrouter',
23
+ name: NAME,
24
+ model,
25
+ authorizeUrl({ redirectUri, state, challenge }) {
26
+ const url = new URL(AUTHORIZE_URL);
27
+ url.search = new URLSearchParams({
28
+ callback_url: redirectUri, code_challenge: challenge, code_challenge_method: 'S256', state,
29
+ }).toString();
30
+ return url.toString();
31
+ },
32
+ async exchange({ code, verifier }) {
33
+ const response = await send(KEY_EXCHANGE_URL, {
34
+ method: 'POST',
35
+ headers: { 'Content-Type': 'application/json' },
36
+ body: JSON.stringify({ code, code_verifier: verifier, code_challenge_method: 'S256' }),
37
+ });
38
+ const body = await jsonOf(response);
39
+ if (!response.ok || typeof body.key !== 'string') {
40
+ throw new Error(replyMessage(body, `${NAME} answered ${response.status}`));
41
+ }
42
+ return { account: 'openrouter', key: body.key };
43
+ },
44
+ session(store, onSignedOut) {
45
+ return webSession({
46
+ providerId: 'openrouter',
47
+ providerName: NAME,
48
+ model,
49
+ endpoint: CHAT_URL,
50
+ headers: siteHeaders(),
51
+ fetch: context.fetch,
52
+ credential: async () => {
53
+ const held = store.read();
54
+ return held?.account === 'openrouter' ? { Authorization: `Bearer ${held.key}` } : {};
55
+ },
56
+ renew: async () => null,
57
+ onRefused: onSignedOut,
58
+ });
59
+ },
60
+ // The key stays listed on the visitor's OpenRouter keys page, where they delete it.
61
+ revoke: async () => undefined,
62
+ };
63
+ }
64
+ //# sourceMappingURL=openRouterAccount.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openRouterAccount.js","sourceRoot":"","sources":["../../src/webAccounts/openRouterAccount.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,wGAAwG;AACxG,yGAAyG;AACzG,wCAAwC;AACxC,kDAAkD;AAGlD,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,MAAM,aAAa,GAAG,4BAA4B,CAAC;AACnD,MAAM,gBAAgB,GAAG,wCAAwC,CAAC;AAClE,MAAM,QAAQ,GAAG,+CAA+C,CAAC;AACjE,mEAAmE;AACnE,MAAM,CAAC,MAAM,wBAAwB,GAAG,iBAAiB,CAAC;AAC1D,MAAM,IAAI,GAAG,iBAAiB,CAAC,UAAU,CAAC;AAE1C,uEAAuE;AACvE,SAAS,WAAW;IAClB,MAAM,MAAM,GAAG,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC3C,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,MAAM,EAAE,SAAS,EAAE,UAAU,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACvF,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,KAAa,EAAE,UAA6B,EAAE;IAC9E,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;IACpC,OAAO;QACL,EAAE,EAAE,YAAY;QAChB,IAAI,EAAE,IAAI;QACV,KAAK;QACL,YAAY,CAAC,EAAE,WAAW,EAAE,KAAK,EAAE,SAAS,EAAE;YAC5C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,aAAa,CAAC,CAAC;YACnC,GAAG,CAAC,MAAM,GAAG,IAAI,eAAe,CAAC;gBAC/B,YAAY,EAAE,WAAW,EAAE,cAAc,EAA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,aAAa,EAAE,UAAU,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACvF,CAAC;gBACD,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;gBACvB,SAAS,EAAE,WAAW;aACvB,CAAC,CAAC;QACL,CAAC;QACD,oFAAoF;QACpF,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,SAAS;KAC9B,CAAC;AACJ,CAAC","sourcesContent":["// OpenRouter for a visitor without the wallet: the site sends the visitor to OpenRouter's sign in with a\n// PKCE challenge, OpenRouter sends them back with a code, and the page trades it for a key bound to the\n// visitor's own credits. Every answer is billed to them. OpenRouter returns the sign in's state with the\n// code, and leaves it out of a refusal.\n// https://openrouter.ai/docs/use-cases/oauth-pkce\n\nimport type { WebAccount, WebAccountContext } from './webAccount.ts';\nimport { jsonOf, replyMessage, WEB_ACCOUNT_NAMES } from './webAccount.ts';\nimport { webSession } from './openAiCompatibleSession.ts';\n\nconst AUTHORIZE_URL = 'https://openrouter.ai/auth';\nconst KEY_EXCHANGE_URL = 'https://openrouter.ai/api/v1/auth/keys';\nconst CHAT_URL = 'https://openrouter.ai/api/v1/chat/completions';\n// OpenRouter's Auto Router, which picks the model for each prompt.\nexport const OPENROUTER_DEFAULT_MODEL = 'openrouter/auto';\nconst NAME = WEB_ACCOUNT_NAMES.openrouter;\n\n// OpenRouter credits the site that sent the call by these two headers.\nfunction siteHeaders(): Record<string, string> {\n const origin = globalThis.location?.origin;\n return origin ? { 'HTTP-Referer': origin, 'X-Title': globalThis.location.host } : {};\n}\n\nexport function openRouterAccount(model: string, context: WebAccountContext = {}): WebAccount {\n const send = context.fetch ?? fetch;\n return {\n id: 'openrouter',\n name: NAME,\n model,\n authorizeUrl({ redirectUri, state, challenge }) {\n const url = new URL(AUTHORIZE_URL);\n url.search = new URLSearchParams({\n callback_url: redirectUri, code_challenge: challenge, code_challenge_method: 'S256', state,\n }).toString();\n return url.toString();\n },\n async exchange({ code, verifier }) {\n const response = await send(KEY_EXCHANGE_URL, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code, code_verifier: verifier, code_challenge_method: 'S256' }),\n });\n const body = await jsonOf(response);\n if (!response.ok || typeof body.key !== 'string') {\n throw new Error(replyMessage(body, `${NAME} answered ${response.status}`));\n }\n return { account: 'openrouter', key: body.key };\n },\n session(store, onSignedOut) {\n return webSession({\n providerId: 'openrouter',\n providerName: NAME,\n model,\n endpoint: CHAT_URL,\n headers: siteHeaders(),\n fetch: context.fetch,\n credential: async (): Promise<Record<string, string>> => {\n const held = store.read();\n return held?.account === 'openrouter' ? { Authorization: `Bearer ${held.key}` } : {};\n },\n renew: async () => null,\n onRefused: onSignedOut,\n });\n },\n // The key stays listed on the visitor's OpenRouter keys page, where they delete it.\n revoke: async () => undefined,\n };\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function randomToken(byteLength?: number): string;
2
+ export declare function challengeFor(verifier: string): Promise<string>;
@@ -0,0 +1,17 @@
1
+ // PKCE (RFC 7636) with the S256 method, on the Web Crypto API that browsers and Node share. The state of a
2
+ // sign in is a random token too.
3
+ function base64Url(bytes) {
4
+ let binary = '';
5
+ for (const byte of bytes) {
6
+ binary += String.fromCharCode(byte);
7
+ }
8
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
9
+ }
10
+ export function randomToken(byteLength = 32) {
11
+ return base64Url(crypto.getRandomValues(new Uint8Array(byteLength)));
12
+ }
13
+ export async function challengeFor(verifier) {
14
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
15
+ return base64Url(new Uint8Array(digest));
16
+ }
17
+ //# sourceMappingURL=pkce.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pkce.js","sourceRoot":"","sources":["../../src/webAccounts/pkce.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,iCAAiC;AAEjC,SAAS,SAAS,CAAC,KAAiB;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACjF,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,UAAU,GAAG,EAAE;IACzC,OAAO,SAAS,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACvE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,QAAgB;IACjD,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;IACzF,OAAO,SAAS,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["// PKCE (RFC 7636) with the S256 method, on the Web Crypto API that browsers and Node share. The state of a\n// sign in is a random token too.\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nexport function randomToken(byteLength = 32): string {\n return base64Url(crypto.getRandomValues(new Uint8Array(byteLength)));\n}\n\nexport async function challengeFor(verifier: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));\n return base64Url(new Uint8Array(digest));\n}\n"]}
@@ -0,0 +1 @@
1
+ export declare function serverSentEvents(response: Response): AsyncGenerator<Record<string, unknown>>;
@@ -0,0 +1,62 @@
1
+ // A streamed HTTP answer read as server sent events, each event's data parsed as JSON, until the OpenAI
2
+ // style `[DONE]`. A line and a whole stream each have a longest length, and the provider's stream is
3
+ // stopped as soon as the reading ends, whether it finished, failed or was left by its reader.
4
+ // The longest line, in characters. An event of a chat is a few kilobytes at most.
5
+ const MAX_LINE_LENGTH = 1_048_576;
6
+ // The most a whole stream carries, in characters.
7
+ const MAX_STREAM_LENGTH = 67_108_864;
8
+ function* eventsOf(lines) {
9
+ for (const line of lines) {
10
+ if (!line.startsWith('data:')) {
11
+ continue;
12
+ }
13
+ const data = line.slice('data:'.length).trim();
14
+ if (data === '[DONE]') {
15
+ yield 'done';
16
+ return;
17
+ }
18
+ if (data) {
19
+ yield JSON.parse(data);
20
+ }
21
+ }
22
+ }
23
+ // The finished lines of what was read, and the line still being written.
24
+ function linesOf(text) {
25
+ const lines = text.split('\n');
26
+ if (lines.some((line) => line.length > MAX_LINE_LENGTH)) {
27
+ throw new Error('The provider sent a line longer than a stream may carry');
28
+ }
29
+ return { lines, rest: lines.pop() ?? '' };
30
+ }
31
+ export async function* serverSentEvents(response) {
32
+ if (!response.body) {
33
+ return;
34
+ }
35
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
36
+ let buffer = '';
37
+ let read = 0;
38
+ try {
39
+ for (;;) {
40
+ const { value, done } = await reader.read();
41
+ if (done) {
42
+ return;
43
+ }
44
+ read += value.length;
45
+ if (read > MAX_STREAM_LENGTH) {
46
+ throw new Error('The provider sent more than a stream may carry');
47
+ }
48
+ const { lines, rest } = linesOf(buffer + value);
49
+ buffer = rest;
50
+ for (const event of eventsOf(lines)) {
51
+ if (event === 'done') {
52
+ return;
53
+ }
54
+ yield event;
55
+ }
56
+ }
57
+ }
58
+ finally {
59
+ await reader.cancel().catch(() => undefined);
60
+ }
61
+ }
62
+ //# sourceMappingURL=serverSentEvents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverSentEvents.js","sourceRoot":"","sources":["../../src/webAccounts/serverSentEvents.ts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AC,IAAI,iBAAiB,EAAE,CAAC,CAAC,SAAS,EAAE,CAAC;IAC9E,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,CAAC;QACH,SAAS,CAAC;YACR,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,IAAI,EAAE,CAAC;gBACT,OAAO;YACT,CAAC;YACD,IAAI,IAAI,KAAK,CAAC,MAAM,CAAC;YACrB,IAAI,IAAI,GAAG,iBAAiB,EAAE,CAAC;gBAC7B,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;YACpE,CAAC;YACD,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC;YAChD,MAAM,GAAG,IAAI,CAAC;YACd,KAAK,MAAM,KAAK,IAAI,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;gBACpC,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;oBACrB,OAAO;gBACT,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC/C,CAAC;AACH,CAAC","sourcesContent":["// A streamed HTTP answer read as server sent events, each event's data parsed as JSON, until the OpenAI\n// style `[DONE]`. A line and a whole stream each have a longest length, and the provider's stream is\n// stopped as soon as the reading ends, whether it finished, failed or was left by its reader.\n\n// The longest line, in characters. An event of a chat is a few kilobytes at most.\nconst MAX_LINE_LENGTH = 1_048_576;\n// The most a whole stream carries, in characters.\nconst MAX_STREAM_LENGTH = 67_108_864;\n\nfunction* eventsOf(lines: string[]): Generator<Record<string, unknown> | 'done'> {\n for (const line of lines) {\n if (!line.startsWith('data:')) {\n continue;\n }\n const data = line.slice('data:'.length).trim();\n if (data === '[DONE]') {\n yield 'done';\n return;\n }\n if (data) {\n yield JSON.parse(data) as Record<string, unknown>;\n }\n }\n}\n\n// The finished lines of what was read, and the line still being written.\nfunction linesOf(text: string): { lines: string[]; rest: string } {\n const lines = text.split('\\n');\n if (lines.some((line) => line.length > MAX_LINE_LENGTH)) {\n throw new Error('The provider sent a line longer than a stream may carry');\n }\n return { lines, rest: lines.pop() ?? '' };\n}\n\nexport async function* serverSentEvents(response: Response): AsyncGenerator<Record<string, unknown>> {\n if (!response.body) {\n return;\n }\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n let buffer = '';\n let read = 0;\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) {\n return;\n }\n read += value.length;\n if (read > MAX_STREAM_LENGTH) {\n throw new Error('The provider sent more than a stream may carry');\n }\n const { lines, rest } = linesOf(buffer + value);\n buffer = rest;\n for (const event of eventsOf(lines)) {\n if (event === 'done') {\n return;\n }\n yield event;\n }\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import type { WebAccountId } from './webAccountStore.ts';
2
+ export interface SignInResult {
3
+ state: string;
4
+ code?: string;
5
+ error?: string;
6
+ }
7
+ export interface PendingSignIn {
8
+ account: WebAccountId;
9
+ state: string;
10
+ verifier: string;
11
+ redirectUri: string;
12
+ returnTo: string;
13
+ }
14
+ export declare function pageAddress(): string;
15
+ export declare function callbackAddress(signInCallback?: string): string;
16
+ export declare function withAnswer(address: string, answer: SignInResult): string;
17
+ export declare function openSignInWindow(): Window | null;
18
+ export declare function answerIn(address: string, state: string): SignInResult | null;
19
+ export declare function markWindow(state: string | null): void;
20
+ export declare function windowMark(): string | null;
21
+ export declare function returnToOpener(result: SignInResult): void;
22
+ export declare function listenForResult(state: string, onResult: (result: SignInResult) => void): () => void;
23
+ export declare function keepForRedirect(pending: PendingSignIn): void;
24
+ export declare function redirectedSignIn(): PendingSignIn | null;
25
+ export declare function forgetRedirected(): void;
26
+ export declare function isSignInReturn(address: string): boolean;
27
+ export declare function cleanAddress(): void;
@@ -0,0 +1,164 @@
1
+ // The window a web sign in runs in, and the way its answer comes back to the page that opened it.
2
+ //
3
+ // The page opens a popup from the visitor's click, and the provider's sign in sends it back to the site's
4
+ // return address (the `signInCallback` page, or else the page itself) with the code (or OAuth's error) and
5
+ // the sign in's state. The page there finds the state the opener marked in the origin's storage, hands the
6
+ // answer to the opener and closes. A
7
+ // sign in page that isolates itself from its opener with a Cross-Origin-Opener-Policy, as Google's and
8
+ // some providers' pages do, leaves the popup without `window.opener` once it comes back, so the answer
9
+ // also goes by a BroadcastChannel named after the state and by a storage event, which reach every page of
10
+ // the same origin and no other. Where the browser blocks the popup, the page itself goes to the sign in
11
+ // and comes back to finish it, its pending sign in kept in the tab's sessionStorage.
12
+ const WINDOW_NAME = 'aiconnect-sign-in';
13
+ const WINDOW_FEATURES = 'popup,width=520,height=720';
14
+ const CHANNEL_PREFIX = 'aiconnect:sign-in:';
15
+ // The answer written for the storage event, removed at once.
16
+ const RESULT_KEY = 'aiconnect:sign-in-result';
17
+ const MESSAGE_TYPE = 'aiconnect:sign-in';
18
+ // The state of the sign in whose popup is open, in localStorage, which the popup shares with its opener.
19
+ const WINDOW_MARK = 'aiconnect:sign-in-window';
20
+ // The sign in a page left for the provider's page in place of a popup, in sessionStorage.
21
+ const REDIRECT_KEY = 'aiconnect:sign-in';
22
+ // The parameters a callback adds to the page's address, removed once the sign in is read. `aiconnect_state`
23
+ // is the state an earlier release carried in the address.
24
+ const CALLBACK_PARAMS = ['aiconnect_state', 'code', 'state', 'error', 'error_description', 'error_uri', 'iss'];
25
+ // Storage access throws where the browser blocks it; the sign in then runs without the mark.
26
+ function attempt(work) {
27
+ try {
28
+ return work();
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
34
+ function withoutCallback(address) {
35
+ const url = new URL(address);
36
+ for (const name of CALLBACK_PARAMS) {
37
+ url.searchParams.delete(name);
38
+ }
39
+ return url;
40
+ }
41
+ // The page's own address, without the parameters of a sign in's answer.
42
+ export function pageAddress() {
43
+ const url = withoutCallback(location.href);
44
+ url.hash = '';
45
+ return url.toString();
46
+ }
47
+ // Where the provider sends the sign in back to: the site's return page, a path or an address on the page's
48
+ // own origin, or else the page itself.
49
+ export function callbackAddress(signInCallback) {
50
+ if (!signInCallback) {
51
+ return pageAddress();
52
+ }
53
+ const url = new URL(signInCallback, location.href);
54
+ if (url.origin !== location.origin) {
55
+ throw new Error(`signInCallback must be on this page's origin, ${location.origin}`);
56
+ }
57
+ return url.toString();
58
+ }
59
+ // The page a sign in started from, with the answer for its client to finish.
60
+ export function withAnswer(address, answer) {
61
+ const url = new URL(address);
62
+ url.searchParams.set('state', answer.state);
63
+ url.searchParams.set(answer.code ? 'code' : 'error', answer.code ?? answer.error ?? 'server_error');
64
+ return url.toString();
65
+ }
66
+ // Opened empty during the click, so the browser lets it open; null where the browser blocks it.
67
+ export function openSignInWindow() {
68
+ return window.open('', WINDOW_NAME, WINDOW_FEATURES);
69
+ }
70
+ // The answer of the sign in that expects `state`, when the page's address carries it. TensorPass returns
71
+ // the state with the code or the error. OpenRouter may come back with its code or its error alone, as it
72
+ // did on 16 November 2026; such an answer is taken while this origin waits for a sign in, since only the
73
+ // verifier the page holds trades a code.
74
+ export function answerIn(address, state) {
75
+ const params = new URL(address).searchParams;
76
+ const code = params.get('code');
77
+ const error = params.get('error');
78
+ const returned = params.get('state');
79
+ if ((returned === state || !returned) && (code || error)) {
80
+ return { state, ...(code ? { code } : {}), ...(error ? { error } : {}) };
81
+ }
82
+ return null;
83
+ }
84
+ function isResult(data) {
85
+ const message = data;
86
+ return message?.type === MESSAGE_TYPE && typeof message.state === 'string';
87
+ }
88
+ export function markWindow(state) {
89
+ attempt(() => (state ? localStorage.setItem(WINDOW_MARK, state) : localStorage.removeItem(WINDOW_MARK)));
90
+ }
91
+ // The state of the sign in whose popup is open, as its opener marked it.
92
+ export function windowMark() {
93
+ return attempt(() => localStorage.getItem(WINDOW_MARK)) ?? null;
94
+ }
95
+ // In the popup: hands the answer to the page that opened it, by each way, then closes.
96
+ export function returnToOpener(result) {
97
+ const message = { type: MESSAGE_TYPE, ...result };
98
+ attempt(() => window.opener?.postMessage(message, location.origin));
99
+ if (typeof BroadcastChannel === 'function') {
100
+ const channel = new BroadcastChannel(CHANNEL_PREFIX + result.state);
101
+ channel.postMessage(message);
102
+ channel.close();
103
+ }
104
+ attempt(() => {
105
+ localStorage.setItem(RESULT_KEY, JSON.stringify(message));
106
+ localStorage.removeItem(RESULT_KEY);
107
+ });
108
+ window.close();
109
+ }
110
+ // In the opener: hears the answer of the sign in that expects `state`, from its own origin, by any of the
111
+ // three ways, until the returned function stops it.
112
+ export function listenForResult(state, onResult) {
113
+ const take = (data) => {
114
+ if (isResult(data) && data.state === state) {
115
+ onResult({ state: data.state, code: data.code, error: data.error });
116
+ }
117
+ };
118
+ const onMessage = (event) => {
119
+ if (event.origin === location.origin) {
120
+ take(event.data);
121
+ }
122
+ };
123
+ const onStorage = (event) => {
124
+ if (event.key === RESULT_KEY && event.newValue) {
125
+ take(attempt(() => JSON.parse(event.newValue)));
126
+ }
127
+ };
128
+ window.addEventListener('message', onMessage);
129
+ window.addEventListener('storage', onStorage);
130
+ const channel = typeof BroadcastChannel === 'function' ? new BroadcastChannel(CHANNEL_PREFIX + state) : null;
131
+ channel?.addEventListener('message', (event) => take(event.data));
132
+ return () => {
133
+ window.removeEventListener('message', onMessage);
134
+ window.removeEventListener('storage', onStorage);
135
+ channel?.close();
136
+ };
137
+ }
138
+ export function keepForRedirect(pending) {
139
+ attempt(() => sessionStorage.setItem(REDIRECT_KEY, JSON.stringify(pending)));
140
+ }
141
+ // The sign in this tab left for the provider's page, if any.
142
+ export function redirectedSignIn() {
143
+ const raw = attempt(() => sessionStorage.getItem(REDIRECT_KEY));
144
+ if (!raw) {
145
+ return null;
146
+ }
147
+ const pending = attempt(() => JSON.parse(raw));
148
+ const complete = pending && typeof pending.state === 'string' && typeof pending.verifier === 'string';
149
+ return complete ? { ...pending, returnTo: pending.returnTo ?? pending.redirectUri } : null;
150
+ }
151
+ export function forgetRedirected() {
152
+ attempt(() => sessionStorage.removeItem(REDIRECT_KEY));
153
+ }
154
+ // Whether the page is the return of a sign in this origin started, in a popup or in the tab: the loader
155
+ // then loads the client at once, since the sign in waits for it.
156
+ export function isSignInReturn(address) {
157
+ const state = windowMark() ?? redirectedSignIn()?.state;
158
+ return Boolean(state && answerIn(address, state));
159
+ }
160
+ // Takes the callback's parameters out of the address bar, leaving the page where it was.
161
+ export function cleanAddress() {
162
+ history.replaceState(history.state, '', withoutCallback(location.href).toString());
163
+ }
164
+ //# sourceMappingURL=signInWindow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signInWindow.js","sourceRoot":"","sources":["../../src/webAccounts/signInWindow.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,EAAE;AACF,0GAA0G;AAC1G,2GAA2G;AAC3G,2GAA2G;AAC3G,qCAAqC;AACrC,uGAAuG;AACvG,uGAAuG;AACvG,0GAA0G;AAC1G,wGAAwG;AACxG,qFAAqF;AAIrF,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,eAAe,GAAG,4BAA4B,CAAC;AACrD,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAC5C,6DAA6D;AAC7D,MAAM,UAAU,GAAG,0BAA0B,CAAC;AAC9C,MAAM,YAAY,GAAG,mBAAmB,CAAC;AACzC,yGAAyG;AACzG,MAAM,WAAW,GAAG,0BAA0B,CAAC;AAC/C,0FAA0F;AAC1F,MAAM,YAAY,GAAG,mBAAmB,CAAC;AACzC,4GAA4G;AAC5G,0DAA0D;AAC1D,MAAM,eAAe,GAAG,CAAC,iBAAiB,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC;AAiB/G,6FAA6F;AAC7F,SAAS,OAAO,CA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O,CAAC,KAAK,IAAI,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AACpD,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,YAAY;IAC1B,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE,eAAe,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;AACrF,CAAC","sourcesContent":["// The window a web sign in runs in, and the way its answer comes back to the page that opened it.\n//\n// The page opens a popup from the visitor's click, and the provider's sign in sends it back to the site's\n// return address (the `signInCallback` page, or else the page itself) with the code (or OAuth's error) and\n// the sign in's state. The page there finds the state the opener marked in the origin's storage, hands the\n// answer to the opener and closes. A\n// sign in page that isolates itself from its opener with a Cross-Origin-Opener-Policy, as Google's and\n// some providers' pages do, leaves the popup without `window.opener` once it comes back, so the answer\n// also goes by a BroadcastChannel named after the state and by a storage event, which reach every page of\n// the same origin and no other. Where the browser blocks the popup, the page itself goes to the sign in\n// and comes back to finish it, its pending sign in kept in the tab's sessionStorage.\n\nimport type { WebAccountId } from './webAccountStore.ts';\n\nconst WINDOW_NAME = 'aiconnect-sign-in';\nconst WINDOW_FEATURES = 'popup,width=520,height=720';\nconst CHANNEL_PREFIX = 'aiconnect:sign-in:';\n// The answer written for the storage event, removed at once.\nconst RESULT_KEY = 'aiconnect:sign-in-result';\nconst MESSAGE_TYPE = 'aiconnect:sign-in';\n// The state of the sign in whose popup is open, in localStorage, which the popup shares with its opener.\nconst WINDOW_MARK = 'aiconnect:sign-in-window';\n// The sign in a page left for the provider's page in place of a popup, in sessionStorage.\nconst REDIRECT_KEY = 'aiconnect:sign-in';\n// The parameters a callback adds to the page's address, removed once the sign in is read. `aiconnect_state`\n// is the state an earlier release carried in the address.\nconst CALLBACK_PARAMS = ['aiconnect_state', 'code', 'state', 'error', 'error_description', 'error_uri', 'iss'];\n\nexport interface SignInResult {\n state: string;\n code?: string;\n error?: string;\n}\n\nexport interface PendingSignIn {\n account: WebAccountId;\n state: string;\n verifier: string;\n redirectUri: string;\n // The page the sign in started from, which a dedicated return page sends the tab back to.\n returnTo: string;\n}\n\n// Storage access throws where the browser blocks it; the sign in then runs without the mark.\nfunction attempt<T>(work: () => T): T | undefined {\n try {\n return work();\n } catch {\n return undefined;\n }\n}\n\nfunction withoutCallback(address: string): URL {\n const url = new URL(address);\n for (const name of CALLBACK_PARAMS) {\n url.searchParams.delete(name);\n }\n return url;\n}\n\n// The page's own address, without the parameters of a sign in's answer.\nexport function pageAddress(): string {\n const url = withoutCallback(location.href);\n url.hash = '';\n return url.toString();\n}\n\n// Where the provider sends the sign in back to: the site's return page, a path or an address on the page's\n// own origin, or else the page itself.\nexport function callbackAddress(signInCallback?: string): string {\n if (!signInCallback) {\n return pageAddress();\n }\n const url = new URL(signInCallback, location.href);\n if (url.origin !== location.origin) {\n throw new Error(`signInCallback must be on this page's origin, ${location.origin}`);\n }\n return url.toString();\n}\n\n// The page a sign in started from, with the answer for its client to finish.\nexport function withAnswer(address: string, answer: SignInResult): string {\n const url = new URL(address);\n url.searchParams.set('state', answer.state);\n url.searchParams.set(answer.code ? 'code' : 'error', answer.code ?? answer.error ?? 'server_error');\n return url.toString();\n}\n\n// Opened empty during the click, so the browser lets it open; null where the browser blocks it.\nexport function openSignInWindow(): Window | null {\n return window.open('', WINDOW_NAME, WINDOW_FEATURES);\n}\n\n// The answer of the sign in that expects `state`, when the page's address carries it. TensorPass returns\n// the state with the code or the error. OpenRouter may come back with its code or its error alone, as it\n// did on 16 November 2026; such an answer is taken while this origin waits for a sign in, since only the\n// verifier the page holds trades a code.\nexport function answerIn(address: string, state: string): SignInResult | null {\n const params = new URL(address).searchParams;\n const code = params.get('code');\n const error = params.get('error');\n const returned = params.get('state');\n if ((returned === state || !returned) && (code || error)) {\n return { state, ...(code ? { code } : {}), ...(error ? { error } : {}) };\n }\n return null;\n}\n\nfunction isResult(data: unknown): data is SignInResult & { type: string } {\n const message = data as Record<string, unknown> | null;\n return message?.type === MESSAGE_TYPE && typeof message.state === 'string';\n}\n\nexport function markWindow(state: string | null): void {\n attempt(() => (state ? localStorage.setItem(WINDOW_MARK, state) : localStorage.removeItem(WINDOW_MARK)));\n}\n\n// The state of the sign in whose popup is open, as its opener marked it.\nexport function windowMark(): string | null {\n return attempt(() => localStorage.getItem(WINDOW_MARK)) ?? null;\n}\n\n// In the popup: hands the answer to the page that opened it, by each way, then closes.\nexport function returnToOpener(result: SignInResult): void {\n const message = { type: MESSAGE_TYPE, ...result };\n attempt(() => window.opener?.postMessage(message, location.origin));\n if (typeof BroadcastChannel === 'function') {\n const channel = new BroadcastChannel(CHANNEL_PREFIX + result.state);\n channel.postMessage(message);\n channel.close();\n }\n attempt(() => {\n localStorage.setItem(RESULT_KEY, JSON.stringify(message));\n localStorage.removeItem(RESULT_KEY);\n });\n window.close();\n}\n\n// In the opener: hears the answer of the sign in that expects `state`, from its own origin, by any of the\n// three ways, until the returned function stops it.\nexport function listenForResult(state: string, onResult: (result: SignInResult) => void): () => void {\n const take = (data: unknown) => {\n if (isResult(data) && data.state === state) {\n onResult({ state: data.state, code: data.code, error: data.error });\n }\n };\n const onMessage = (event: MessageEvent) => {\n if (event.origin === location.origin) {\n take(event.data);\n }\n };\n const onStorage = (event: StorageEvent) => {\n if (event.key === RESULT_KEY && event.newValue) {\n take(attempt(() => JSON.parse(event.newValue!) as unknown));\n }\n };\n window.addEventListener('message', onMessage);\n window.addEventListener('storage', onStorage);\n const channel = typeof BroadcastChannel === 'function' ? new BroadcastChannel(CHANNEL_PREFIX + state) : null;\n channel?.addEventListener('message', (event) => take(event.data));\n return () => {\n window.removeEventListener('message', onMessage);\n window.removeEventListener('storage', onStorage);\n channel?.close();\n };\n}\n\nexport function keepForRedirect(pending: PendingSignIn): void {\n attempt(() => sessionStorage.setItem(REDIRECT_KEY, JSON.stringify(pending)));\n}\n\n// The sign in this tab left for the provider's page, if any.\nexport function redirectedSignIn(): PendingSignIn | null {\n const raw = attempt(() => sessionStorage.getItem(REDIRECT_KEY));\n if (!raw) {\n return null;\n }\n const pending = attempt(() => JSON.parse(raw) as PendingSignIn);\n const complete = pending && typeof pending.state === 'string' && typeof pending.verifier === 'string';\n return complete ? { ...pending, returnTo: pending.returnTo ?? pending.redirectUri } : null;\n}\n\nexport function forgetRedirected(): void {\n attempt(() => sessionStorage.removeItem(REDIRECT_KEY));\n}\n\n// Whether the page is the return of a sign in this origin started, in a popup or in the tab: the loader\n// then loads the client at once, since the sign in waits for it.\nexport function isSignInReturn(address: string): boolean {\n const state = windowMark() ?? redirectedSignIn()?.state;\n return Boolean(state && answerIn(address, state));\n}\n\n// Takes the callback's parameters out of the address bar, leaving the page where it was.\nexport function cleanAddress(): void {\n history.replaceState(history.state, '', withoutCallback(location.href).toString());\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import type { WebAccount, WebAccountContext } from './webAccount.ts';
2
+ export declare const PLAN_GATEWAY = "https://plan.tensorpass.app";
3
+ export type PlanLevel = 'quick' | 'smart' | 'expert';
4
+ export interface TensorPassOptions extends WebAccountContext {
5
+ gateway: string;
6
+ siteKey: string;
7
+ level: PlanLevel;
8
+ }
9
+ export declare function tensorPassAccount(options: TensorPassOptions): WebAccount;