@tensorpass/aiconnect 0.0.0-stage → 0.1.0

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 +56 -4
@@ -0,0 +1,84 @@
1
+ // Where a web account's credential lives: the site's own localStorage, for this origin only, under one
2
+ // key. Every script of the site's pages can read it, which the AI Wallet's accounts are kept from: the
3
+ // wallet holds those in the extension. Signing out removes it. A browser that refuses storage, such as a
4
+ // private window with storage blocked, keeps the credential for the page's life only.
5
+ export const WEB_ACCOUNT_KEY = 'aiconnect:web-account';
6
+ const isText = (value) => typeof value === 'string' && value.length > 0;
7
+ function credentialOf(value) {
8
+ const held = value;
9
+ if (held?.account === 'openrouter' && isText(held.key)) {
10
+ return { account: 'openrouter', key: held.key };
11
+ }
12
+ if (held?.account === 'tensorpass' && isText(held.accessToken) && isText(held.refreshToken)
13
+ && typeof held.expiresAt === 'number') {
14
+ return {
15
+ account: 'tensorpass', accessToken: held.accessToken, refreshToken: held.refreshToken, expiresAt: held.expiresAt,
16
+ };
17
+ }
18
+ return null;
19
+ }
20
+ function parsed(raw) {
21
+ try {
22
+ return credentialOf(JSON.parse(raw));
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ // Reading `localStorage` itself throws where the browser blocks storage. A server render has none.
29
+ function pageStorage() {
30
+ if (typeof window === 'undefined') {
31
+ return null;
32
+ }
33
+ try {
34
+ return window.localStorage ?? null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ export class WebAccountStore {
41
+ memory = null;
42
+ // Set once the browser refuses storage: the credential then lives in this page alone.
43
+ memoryOnly;
44
+ storage;
45
+ constructor(storage = pageStorage()) {
46
+ this.storage = storage;
47
+ this.memoryOnly = !storage;
48
+ }
49
+ read() {
50
+ if (this.memoryOnly || !this.storage) {
51
+ return this.memory;
52
+ }
53
+ try {
54
+ const raw = this.storage.getItem(WEB_ACCOUNT_KEY);
55
+ return raw ? parsed(raw) : null;
56
+ }
57
+ catch {
58
+ this.memoryOnly = true;
59
+ return this.memory;
60
+ }
61
+ }
62
+ save(credential) {
63
+ this.memory = credential;
64
+ if (this.memoryOnly || !this.storage) {
65
+ return;
66
+ }
67
+ try {
68
+ this.storage.setItem(WEB_ACCOUNT_KEY, JSON.stringify(credential));
69
+ }
70
+ catch {
71
+ this.memoryOnly = true;
72
+ }
73
+ }
74
+ forget() {
75
+ this.memory = null;
76
+ try {
77
+ this.storage?.removeItem(WEB_ACCOUNT_KEY);
78
+ }
79
+ catch {
80
+ // Nothing was stored.
81
+ }
82
+ }
83
+ }
84
+ //# sourceMappingURL=webAccountStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webAccountStore.js","sourceRoot":"","sources":["../../src/webAccounts/webAccountStore.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,uGAAuG;AACvG,yGAAyG;AACzG,sFAAsF;AA2BtF,MAAM,CAAC,MAAM,eAAe,GAAG,uBAAuB,CAAC;AAEvD,MAAM,MAAM,GAAG,CAAC,KAAc,EAAmB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAElG,SAAS,YAAY,CAAC,KAAc;IAClC,MAAM,IAAI,GAAG,KAAuC,CAAC;IACrD,IAAI,IAAI,EAAE,OAAO,KAAK,YAAY,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACvD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC;IAClD,CAAC;IACD,I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,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;YAClD,OAAO,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAClC,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;YACvB,OAAO,IAAI,CAAC,MAAM,CAAC;QACrB,CAAC;IACH,CAAC;IAED,IAAI,CAAC,UAAyB;QAC5B,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC;QACzB,IAAI,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YACrC,OAAO;QACT,CAAC;QACD,IAAI,CAAC;YACH,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC;QACpE,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACzB,CAAC;IACH,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC;YACH,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;QAC5C,CAAC;QAAC,MAAM,CAAC;YACP,sBAAsB;QACxB,CAAC;IACH,CAAC;CACF","sourcesContent":["// Where a web account's credential lives: the site's own localStorage, for this origin only, under one\n// key. Every script of the site's pages can read it, which the AI Wallet's accounts are kept from: the\n// wallet holds those in the extension. Signing out removes it. A browser that refuses storage, such as a\n// private window with storage blocked, keeps the credential for the page's life only.\n\nexport type WebAccountId = 'tensorpass' | 'openrouter';\n\n// An OpenRouter key bound to the visitor's own credits.\nexport interface OpenRouterCredential {\n account: 'openrouter';\n key: string;\n}\n\n// A TensorPass plan token of a few minutes, its refresh token, and when the access token ends, in epoch\n// milliseconds.\nexport interface TensorPassCredential {\n account: 'tensorpass';\n accessToken: string;\n refreshToken: string;\n expiresAt: number;\n}\n\nexport type WebCredential = OpenRouterCredential | TensorPassCredential;\n\nexport interface KeyValueStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport const WEB_ACCOUNT_KEY = 'aiconnect:web-account';\n\nconst isText = (value: unknown): value is string => typeof value === 'string' && value.length > 0;\n\nfunction credentialOf(value: unknown): WebCredential | null {\n const held = value as Record<string, unknown> | null;\n if (held?.account === 'openrouter' && isText(held.key)) {\n return { account: 'openrouter', key: held.key };\n }\n if (held?.account === 'tensorpass' && isText(held.accessToken) && isText(held.refreshToken)\n && typeof held.expiresAt === 'number') {\n return {\n account: 'tensorpass', accessToken: held.accessToken, refreshToken: held.refreshToken, expiresAt: held.expiresAt,\n };\n }\n return null;\n}\n\nfunction parsed(raw: string): WebCredential | null {\n try {\n return credentialOf(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\n// Reading `localStorage` itself throws where the browser blocks storage. A server render has none.\nfunction pageStorage(): KeyValueStorage | null {\n if (typeof window === 'undefined') {\n return null;\n }\n try {\n return window.localStorage ?? null;\n } catch {\n return null;\n }\n}\n\nexport class WebAccountStore {\n private memory: WebCredential | null = null;\n // Set once the browser refuses storage: the credential then lives in this page alone.\n private memoryOnly: boolean;\n private readonly storage: KeyValueStorage | null;\n\n constructor(storage: KeyValueStorage | null = pageStorage()) {\n this.storage = storage;\n this.memoryOnly = !storage;\n }\n\n read(): WebCredential | null {\n if (this.memoryOnly || !this.storage) {\n return this.memory;\n }\n try {\n const raw = this.storage.getItem(WEB_ACCOUNT_KEY);\n return raw ? parsed(raw) : null;\n } catch {\n this.memoryOnly = true;\n return this.memory;\n }\n }\n\n save(credential: WebCredential): void {\n this.memory = credential;\n if (this.memoryOnly || !this.storage) {\n return;\n }\n try {\n this.storage.setItem(WEB_ACCOUNT_KEY, JSON.stringify(credential));\n } catch {\n this.memoryOnly = true;\n }\n }\n\n forget(): void {\n this.memory = null;\n try {\n this.storage?.removeItem(WEB_ACCOUNT_KEY);\n } catch {\n // Nothing was stored.\n }\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import type { WireProtocol } from './wireProtocol.ts';
2
+ export declare const anthropicMessages: WireProtocol;
@@ -0,0 +1,181 @@
1
+ // The Anthropic Messages protocol, as the Anthropic SDK, the Vercel AI SDK's `anthropic()` models
2
+ // and LangChain's ChatAnthropic speak it. Streamed answers go as named events: `message_start`, a
3
+ // content block per text and per tool call, then `message_delta` with the stop reason and the
4
+ // usage. `message_start` names the model of the account that answers, which the wallet tells
5
+ // before the first text, and counts nothing yet, since the wallet reports usage once the answer ends.
6
+ import { dataUrl, textOf } from "../chatContent.js";
7
+ import { EMPTY_PARAMETERS, errorType, toolNameOf, unsupported, userContent } from "./wireProtocol.js";
8
+ const STOP_REASONS = {
9
+ stop: 'end_turn',
10
+ length: 'max_tokens',
11
+ toolCalls: 'tool_use',
12
+ contentFilter: 'refusal',
13
+ };
14
+ // Thinking blocks hold the provider's own reasoning, which another account cannot read.
15
+ const SKIPPED_BLOCKS = new Set(['thinking', 'redacted_thinking']);
16
+ const TOOL_CHOICES = { auto: 'auto', any: 'required', none: 'none' };
17
+ // What `message_start` counts: nothing yet, the final counts come with `message_delta`.
18
+ const NOTHING_COUNTED = { input_tokens: 0, output_tokens: 0 };
19
+ function blocksOf(content) {
20
+ if (typeof content === 'string') {
21
+ return content ? [{ type: 'text', text: content }] : [];
22
+ }
23
+ return (content ?? []).filter((block) => !SKIPPED_BLOCKS.has(block.type));
24
+ }
25
+ function imageUrl(source) {
26
+ if (source.type === 'base64' && source.media_type && source.data) {
27
+ return dataUrl({ mediaType: source.media_type, data: source.data });
28
+ }
29
+ if (source.type === 'url' && source.url) {
30
+ return source.url;
31
+ }
32
+ throw unsupported(`${source.type} image sources`);
33
+ }
34
+ function partOf(block) {
35
+ if (block.type === 'text') {
36
+ return { type: 'text', text: block.text ?? '' };
37
+ }
38
+ if (block.type === 'image' && block.source) {
39
+ return { type: 'image', url: imageUrl(block.source) };
40
+ }
41
+ throw unsupported(`${block.type} content`);
42
+ }
43
+ // A tool result's content is text; images inside a result have no place in the shared format.
44
+ function resultText(block) {
45
+ const parts = blocksOf(block.content).map(partOf);
46
+ if (parts.some((part) => part.type !== 'text')) {
47
+ throw unsupported('images inside tool results');
48
+ }
49
+ return textOf(parts);
50
+ }
51
+ // A user turn carries the results of the previous tool calls first, then what the user wrote.
52
+ function readUser(blocks, names) {
53
+ const results = blocks.filter((block) => block.type === 'tool_result').map((block) => {
54
+ const toolCallId = block.tool_use_id ?? '';
55
+ return { role: 'tool', toolCallId, name: toolNameOf(names, toolCallId), content: resultText(block) };
56
+ });
57
+ const parts = blocks.filter((block) => block.type !== 'tool_result').map(partOf);
58
+ return parts.length ? [...results, { role: 'user', content: userContent(parts) }] : results;
59
+ }
60
+ function readAssistant(blocks, names) {
61
+ const toolCalls = blocks.filter((block) => block.type === 'tool_use').map((block) => ({
62
+ id: block.id ?? '', name: block.name ?? '', arguments: block.input ?? {},
63
+ }));
64
+ toolCalls.forEach((call) => names.set(call.id, call.name));
65
+ const content = textOf(blocks.filter((block) => block.type !== 'tool_use').map(partOf));
66
+ return { role: 'assistant', content, ...(toolCalls.length ? { toolCalls } : {}) };
67
+ }
68
+ function readMessages(body) {
69
+ const names = new Map();
70
+ const system = textOf(blocksOf(body.system).map(partOf));
71
+ const conversation = (body.messages ?? []).flatMap((message) => (message.role === 'assistant'
72
+ ? [readAssistant(blocksOf(message.content), names)]
73
+ : readUser(blocksOf(message.content), names)));
74
+ return system ? [{ role: 'system', content: system }, ...conversation] : conversation;
75
+ }
76
+ function readTools(tools) {
77
+ return tools?.map((tool) => {
78
+ if (tool.type && tool.type !== 'custom') {
79
+ throw unsupported(`the ${tool.type} tool`);
80
+ }
81
+ return { name: tool.name, description: tool.description ?? '', inputSchema: tool.input_schema ?? EMPTY_PARAMETERS };
82
+ });
83
+ }
84
+ function readToolChoice(choice) {
85
+ if (!choice) {
86
+ return undefined;
87
+ }
88
+ return choice.type === 'tool' && choice.name ? { name: choice.name } : TOOL_CHOICES[choice.type];
89
+ }
90
+ function read(raw) {
91
+ const body = raw;
92
+ const format = body.output_config?.format ?? body.output_format;
93
+ return {
94
+ request: {
95
+ messages: readMessages(body),
96
+ tools: readTools(body.tools),
97
+ options: {
98
+ maxTokens: body.max_tokens,
99
+ temperature: body.temperature,
100
+ topP: body.top_p,
101
+ stop: body.stop_sequences,
102
+ toolChoice: readToolChoice(body.tool_choice),
103
+ responseFormat: format ? { type: 'json', schema: format.schema } : undefined,
104
+ },
105
+ },
106
+ stream: body.stream === true,
107
+ };
108
+ }
109
+ // The protocol counts cached input apart from the rest.
110
+ function wireUsage(usage) {
111
+ if (!usage) {
112
+ return undefined;
113
+ }
114
+ return {
115
+ input_tokens: usage.inputTokens - usage.cachedInputTokens,
116
+ output_tokens: usage.outputTokens,
117
+ cache_read_input_tokens: usage.cachedInputTokens,
118
+ };
119
+ }
120
+ function contentBlocks({ message }) {
121
+ const text = message.content ? [{ type: 'text', text: message.content }] : [];
122
+ const uses = (message.toolCalls ?? []).map((call) => ({
123
+ type: 'tool_use', id: call.id, name: call.name, input: call.arguments,
124
+ }));
125
+ return [...text, ...uses];
126
+ }
127
+ function messageObject(context, model, content, response) {
128
+ return {
129
+ id: `msg_${context.id}`,
130
+ type: 'message',
131
+ role: 'assistant',
132
+ model,
133
+ content,
134
+ stop_reason: response ? STOP_REASONS[response.finishReason] : null,
135
+ stop_sequence: null,
136
+ usage: response ? wireUsage(response.usage) : NOTHING_COUNTED,
137
+ };
138
+ }
139
+ function writeToolUse(write, call, index) {
140
+ const contentBlock = { type: 'tool_use', id: call.id, name: call.name, input: {} };
141
+ const delta = { type: 'input_json_delta', partial_json: JSON.stringify(call.arguments) };
142
+ write.send({ type: 'content_block_start', index, content_block: contentBlock }, 'content_block_start');
143
+ write.send({ type: 'content_block_delta', index, delta }, 'content_block_delta');
144
+ write.send({ type: 'content_block_stop', index }, 'content_block_stop');
145
+ }
146
+ async function stream(answer, write, context) {
147
+ const { model } = await answer.started;
148
+ write.send({ type: 'message_start', message: messageObject(context, model, []) }, 'message_start');
149
+ let streamed = false;
150
+ for await (const text of answer.texts()) {
151
+ if (!streamed) {
152
+ const contentBlock = { type: 'text', text: '' };
153
+ write.send({ type: 'content_block_start', index: 0, content_block: contentBlock }, 'content_block_start');
154
+ streamed = true;
155
+ }
156
+ write.send({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } }, 'content_block_delta');
157
+ }
158
+ const response = await answer.result;
159
+ if (streamed) {
160
+ write.send({ type: 'content_block_stop', index: 0 }, 'content_block_stop');
161
+ }
162
+ const offset = streamed ? 1 : 0;
163
+ (response.message.toolCalls ?? []).forEach((call, index) => writeToolUse(write, call, index + offset));
164
+ const delta = { stop_reason: STOP_REASONS[response.finishReason], stop_sequence: null };
165
+ write.send({ type: 'message_delta', delta, usage: wireUsage(response.usage) }, 'message_delta');
166
+ write.send({ type: 'message_stop' }, 'message_stop');
167
+ }
168
+ function body(response, context) {
169
+ return messageObject(context, response.model, contentBlocks(response), response);
170
+ }
171
+ function errorBody(error) {
172
+ return { type: 'error', error: { type: errorType(error.status), message: error.message } };
173
+ }
174
+ export const anthropicMessages = {
175
+ read,
176
+ stream,
177
+ body,
178
+ error: errorBody,
179
+ streamError: (error) => ({ data: errorBody(error), event: 'error' }),
180
+ };
181
+ //# sourceMappingURL=anthropicMessages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropicMessages.js","sourceRoot":"","sources":["../../src/wireProtocols/anthropicMessages.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,kGAAkG;AAClG,8FAA8F;AAC9F,6FAA6F;AAC7F,sGAAsG;AAEtG,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAOpD,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAwCtG,MAAM,YAAY,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C;AACnF,CAAC;AAED,SAAS,SAAS,CAAC,KAAyB;IAC1C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;AAC7F,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAiB;IAC7C,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,KAAK,EAAE,SAAS;IAChB,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;CACrE,CAAC","sourcesContent":["// The Anthropic Messages protocol, as the Anthropic SDK, the Vercel AI SDK's `anthropic()` models\n// and LangChain's ChatAnthropic speak it. Streamed answers go as named events: `message_start`, a\n// content block per text and per tool call, then `message_delta` with the stop reason and the\n// usage. `message_start` names the model of the account that answers, which the wallet tells\n// before the first text, and counts nothing yet, since the wallet reports usage once the answer ends.\n\nimport { dataUrl, textOf } from '../chatContent.ts';\nimport type {\n ChatMessage, ChatResponse, ContentPart, FinishReason, JsonSchema, ToolCall, ToolChoice, ToolDefinition, Usage,\n} from '../types.ts';\nimport type { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport { EMPTY_PARAMETERS, errorType, toolNameOf, unsupported, userContent } from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface WireBlock {\n type: string;\n text?: string;\n source?: { type: string; media_type?: string; data?: string; url?: string };\n id?: string;\n name?: string;\n input?: Record<string, unknown>;\n tool_use_id?: string;\n content?: string | WireBlock[];\n}\n\ninterface WireMessage {\n role: 'user' | 'assistant';\n content: string | WireBlock[];\n}\n\ninterface WireTool {\n type?: string;\n name: string;\n description?: string;\n input_schema?: JsonSchema;\n}\n\ninterface MessagesBody {\n system?: string | WireBlock[];\n messages?: WireMessage[];\n tools?: WireTool[];\n tool_choice?: { type: string; name?: string };\n output_config?: { format?: { type: string; schema?: JsonSchema } };\n output_format?: { type: string; schema?: JsonSchema };\n max_tokens?: number;\n temperature?: number;\n top_p?: number;\n stop_sequences?: string[];\n stream?: boolean;\n}\n\nconst STOP_REASONS: Record<FinishReason, string> = {\n stop: 'end_turn',\n length: 'max_tokens',\n toolCalls: 'tool_use',\n contentFilter: 'refusal',\n};\n\n// Thinking blocks hold the provider's own reasoning, which another account cannot read.\nconst SKIPPED_BLOCKS = new Set(['thinking', 'redacted_thinking']);\n\nconst TOOL_CHOICES: Record<string, ToolChoice> = { auto: 'auto', any: 'required', none: 'none' };\n\n// What `message_start` counts: nothing yet, the final counts come with `message_delta`.\nconst NOTHING_COUNTED = { input_tokens: 0, output_tokens: 0 };\n\nfunction blocksOf(content: string | WireBlock[] | undefined): WireBlock[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', text: content }] : [];\n }\n return (content ?? []).filter((block) => !SKIPPED_BLOCKS.has(block.type));\n}\n\nfunction imageUrl(source: NonNullable<WireBlock['source']>): string {\n if (source.type === 'base64' && source.media_type && source.data) {\n return dataUrl({ mediaType: source.media_type, data: source.data });\n }\n if (source.type === 'url' && source.url) {\n return source.url;\n }\n throw unsupported(`${source.type} image sources`);\n}\n\nfunction partOf(block: WireBlock): ContentPart {\n if (block.type === 'text') {\n return { type: 'text', text: block.text ?? '' };\n }\n if (block.type === 'image' && block.source) {\n return { type: 'image', url: imageUrl(block.source) };\n }\n throw unsupported(`${block.type} content`);\n}\n\n// A tool result's content is text; images inside a result have no place in the shared format.\nfunction resultText(block: WireBlock): string {\n const parts = blocksOf(block.content).map(partOf);\n if (parts.some((part) => part.type !== 'text')) {\n throw unsupported('images inside tool results');\n }\n return textOf(parts);\n}\n\n// A user turn carries the results of the previous tool calls first, then what the user wrote.\nfunction readUser(blocks: WireBlock[], names: Map<string, string>): ChatMessage[] {\n const results = blocks.filter((block) => block.type === 'tool_result').map((block): ChatMessage => {\n const toolCallId = block.tool_use_id ?? '';\n return { role: 'tool', toolCallId, name: toolNameOf(names, toolCallId), content: resultText(block) };\n });\n const parts = blocks.filter((block) => block.type !== 'tool_result').map(partOf);\n return parts.length ? [...results, { role: 'user', content: userContent(parts) }] : results;\n}\n\nfunction readAssistant(blocks: WireBlock[], names: Map<string, string>): ChatMessage {\n const toolCalls: ToolCall[] = blocks.filter((block) => block.type === 'tool_use').map((block) => ({\n id: block.id ?? '', name: block.name ?? '', arguments: block.input ?? {},\n }));\n toolCalls.forEach((call) => names.set(call.id, call.name));\n const content = textOf(blocks.filter((block) => block.type !== 'tool_use').map(partOf));\n return { role: 'assistant', content, ...(toolCalls.length ? { toolCalls } : {}) };\n}\n\nfunction readMessages(body: MessagesBody): ChatMessage[] {\n const names = new Map<string, string>();\n const system = textOf(blocksOf(body.system).map(partOf));\n const conversation = (body.messages ?? []).flatMap((message) => (message.role === 'assistant'\n ? [readAssistant(blocksOf(message.content), names)]\n : readUser(blocksOf(message.content), names)));\n return system ? [{ role: 'system', content: system }, ...conversation] : conversation;\n}\n\nfunction readTools(tools?: WireTool[]): ToolDefinition[] | undefined {\n return tools?.map((tool) => {\n if (tool.type && tool.type !== 'custom') {\n throw unsupported(`the ${tool.type} tool`);\n }\n return { name: tool.name, description: tool.description ?? '', inputSchema: tool.input_schema ?? EMPTY_PARAMETERS };\n });\n}\n\nfunction readToolChoice(choice: MessagesBody['tool_choice']): ToolChoice | undefined {\n if (!choice) {\n return undefined;\n }\n return choice.type === 'tool' && choice.name ? { name: choice.name } : TOOL_CHOICES[choice.type];\n}\n\nfunction read(raw: Record<string, unknown>): WireRequest {\n const body = raw as MessagesBody;\n const format = body.output_config?.format ?? body.output_format;\n return {\n request: {\n messages: readMessages(body),\n tools: readTools(body.tools),\n options: {\n maxTokens: body.max_tokens,\n temperature: body.temperature,\n topP: body.top_p,\n stop: body.stop_sequences,\n toolChoice: readToolChoice(body.tool_choice),\n responseFormat: format ? { type: 'json', schema: format.schema } : undefined,\n },\n },\n stream: body.stream === true,\n };\n}\n\n// The protocol counts cached input apart from the rest.\nfunction wireUsage(usage: Usage | undefined) {\n if (!usage) {\n return undefined;\n }\n return {\n input_tokens: usage.inputTokens - usage.cachedInputTokens,\n output_tokens: usage.outputTokens,\n cache_read_input_tokens: usage.cachedInputTokens,\n };\n}\n\nfunction contentBlocks({ message }: ChatResponse) {\n const text = message.content ? [{ type: 'text', text: message.content }] : [];\n const uses = (message.toolCalls ?? []).map((call) => ({\n type: 'tool_use', id: call.id, name: call.name, input: call.arguments,\n }));\n return [...text, ...uses];\n}\n\nfunction messageObject(context: AnswerContext, model: string, content: unknown[], response?: ChatResponse) {\n return {\n id: `msg_${context.id}`,\n type: 'message',\n role: 'assistant',\n model,\n content,\n stop_reason: response ? STOP_REASONS[response.finishReason] : null,\n stop_sequence: null,\n usage: response ? wireUsage(response.usage) : NOTHING_COUNTED,\n };\n}\n\nfunction writeToolUse(write: EventWriter, call: ToolCall, index: number): void {\n const contentBlock = { type: 'tool_use', id: call.id, name: call.name, input: {} };\n const delta = { type: 'input_json_delta', partial_json: JSON.stringify(call.arguments) };\n write.send({ type: 'content_block_start', index, content_block: contentBlock }, 'content_block_start');\n write.send({ type: 'content_block_delta', index, delta }, 'content_block_delta');\n write.send({ type: 'content_block_stop', index }, 'content_block_stop');\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const { model } = await answer.started;\n write.send({ type: 'message_start', message: messageObject(context, model, []) }, 'message_start');\n let streamed = false;\n for await (const text of answer.texts()) {\n if (!streamed) {\n const contentBlock = { type: 'text', text: '' };\n write.send({ type: 'content_block_start', index: 0, content_block: contentBlock }, 'content_block_start');\n streamed = true;\n }\n write.send({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } }, 'content_block_delta');\n }\n const response = await answer.result;\n if (streamed) {\n write.send({ type: 'content_block_stop', index: 0 }, 'content_block_stop');\n }\n const offset = streamed ? 1 : 0;\n (response.message.toolCalls ?? []).forEach((call, index) => writeToolUse(write, call, index + offset));\n const delta = { stop_reason: STOP_REASONS[response.finishReason], stop_sequence: null };\n write.send({ type: 'message_delta', delta, usage: wireUsage(response.usage) }, 'message_delta');\n write.send({ type: 'message_stop' }, 'message_stop');\n}\n\nfunction body(response: ChatResponse, context: AnswerContext) {\n return messageObject(context, response.model, contentBlocks(response), response);\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { type: 'error', error: { type: errorType(error.status), message: error.message } };\n}\n\nexport const anthropicMessages: WireProtocol = {\n read,\n stream,\n body,\n error: errorBody,\n streamError: (error) => ({ data: errorBody(error), event: 'error' }),\n};\n"]}
@@ -0,0 +1,4 @@
1
+ export interface EventWriter {
2
+ send(data: unknown, event?: string): void;
3
+ }
4
+ export declare function eventStream(run: (writer: EventWriter) => Promise<void>, onCancel: () => void): ReadableStream<Uint8Array>;
@@ -0,0 +1,32 @@
1
+ // Server sent events written to a byte stream as the wallet answers. A reader that cancels the
2
+ // stream stops the answer; writes after that are dropped.
3
+ export function eventStream(run, onCancel) {
4
+ const encoder = new TextEncoder();
5
+ let open = true;
6
+ return new ReadableStream({
7
+ start(controller) {
8
+ const writer = {
9
+ send(data, event) {
10
+ if (!open) {
11
+ return;
12
+ }
13
+ const name = event ? `event: ${event}\n` : '';
14
+ const payload = typeof data === 'string' ? data : JSON.stringify(data);
15
+ controller.enqueue(encoder.encode(`${name}data: ${payload}\n\n`));
16
+ },
17
+ };
18
+ const finish = (end) => {
19
+ if (open) {
20
+ open = false;
21
+ end();
22
+ }
23
+ };
24
+ run(writer).then(() => finish(() => controller.close()), (error) => finish(() => controller.error(error)));
25
+ },
26
+ cancel() {
27
+ open = false;
28
+ onCancel();
29
+ },
30
+ });
31
+ }
32
+ //# sourceMappingURL=eventStream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventStream.js","sourceRoot":"","sources":["../../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;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Server sent events written to a byte stream as the wallet answers. A reader that cancels the\n// stream stops the answer; writes after that are dropped.\n\nexport interface EventWriter {\n // Writes one event; a string goes as is, anything else as JSON.\n send(data: unknown, event?: string): void;\n}\n\nexport function eventStream(\n run: (writer: EventWriter) => Promise<void>, onCancel: () => void,\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n let open = true;\n return new ReadableStream({\n start(controller) {\n const writer: EventWriter = {\n send(data, event) {\n if (!open) {\n return;\n }\n const name = event ? `event: ${event}\\n` : '';\n const payload = typeof data === 'string' ? data : JSON.stringify(data);\n controller.enqueue(encoder.encode(`${name}data: ${payload}\\n\\n`));\n },\n };\n const finish = (end: () => void) => {\n if (open) {\n open = false;\n end();\n }\n };\n run(writer).then(\n () => finish(() => controller.close()),\n (error: unknown) => finish(() => controller.error(error)),\n );\n },\n cancel() {\n open = false;\n onCancel();\n },\n });\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import type { WireProtocol } from './wireProtocol.ts';
2
+ export declare const geminiContents: WireProtocol;
@@ -0,0 +1,201 @@
1
+ // The Gemini `generateContent` protocol, as Google's Gen AI SDK and the Vercel AI SDK's `google()`
2
+ // models speak it. The path says whether to stream (`:streamGenerateContent`). Streamed answers go
3
+ // as plain data events of the same response shape; the last one carries the tool calls, the
4
+ // finish reason and the token counts. Gemini may leave tool call ids out: calls then get one in
5
+ // order, and each result answers the first open call of its name.
6
+ import { textOf } from "../chatContent.js";
7
+ import { WalletRequestError } from "../walletProvider.js";
8
+ import { EMPTY_PARAMETERS, unsupported, userContent } from "./wireProtocol.js";
9
+ const FINISH_REASONS = {
10
+ stop: 'STOP',
11
+ toolCalls: 'STOP',
12
+ length: 'MAX_TOKENS',
13
+ contentFilter: 'SAFETY',
14
+ };
15
+ const TOOL_MODES = { AUTO: 'auto', NONE: 'none', ANY: 'required', VALIDATED: 'auto' };
16
+ const GOOGLE_STATUSES = {
17
+ 400: 'INVALID_ARGUMENT',
18
+ 401: 'UNAUTHENTICATED',
19
+ 403: 'PERMISSION_DENIED',
20
+ 404: 'NOT_FOUND',
21
+ 429: 'RESOURCE_EXHAUSTED',
22
+ 503: 'UNAVAILABLE',
23
+ };
24
+ // Gemini's OpenAPI style schema as JSON Schema: lower case types, `nullable` as a null type, and
25
+ // no `propertyOrdering`, which other providers refuse.
26
+ function jsonSchemaOf(schema) {
27
+ const converted = { ...schema };
28
+ delete converted.propertyOrdering;
29
+ delete converted.nullable;
30
+ if (typeof schema.type === 'string') {
31
+ const type = schema.type.toLowerCase();
32
+ converted.type = schema.nullable ? [type, 'null'] : type;
33
+ }
34
+ if (schema.properties) {
35
+ const properties = Object.entries(schema.properties);
36
+ converted.properties = Object.fromEntries(properties.map(([name, value]) => [name, jsonSchemaOf(value)]));
37
+ }
38
+ if (schema.items) {
39
+ converted.items = jsonSchemaOf(schema.items);
40
+ }
41
+ if (Array.isArray(schema.anyOf)) {
42
+ converted.anyOf = schema.anyOf.map(jsonSchemaOf);
43
+ }
44
+ return converted;
45
+ }
46
+ function mediaPart(mimeType, url) {
47
+ if (!mimeType?.startsWith('image/')) {
48
+ throw unsupported(`${mimeType ?? 'untyped'} files`);
49
+ }
50
+ return { type: 'image', url };
51
+ }
52
+ function partOf(part) {
53
+ if (typeof part.text === 'string') {
54
+ return { type: 'text', text: part.text };
55
+ }
56
+ if (part.inlineData) {
57
+ const { mimeType, data } = part.inlineData;
58
+ return mediaPart(mimeType, `data:${mimeType};base64,${data}`);
59
+ }
60
+ if (part.fileData) {
61
+ return mediaPart(part.fileData.mimeType, part.fileData.fileUri);
62
+ }
63
+ throw unsupported(`the ${Object.keys(part).join(', ')} part`);
64
+ }
65
+ function readModel(reading, parts) {
66
+ const toolCalls = parts.filter((part) => part.functionCall).map((part) => {
67
+ const { id, name, args } = part.functionCall;
68
+ reading.calls += 1;
69
+ return { id: id ?? `call_${reading.calls}`, name, arguments: args ?? {} };
70
+ });
71
+ reading.open.push(...toolCalls);
72
+ const content = textOf(parts.filter((part) => !part.functionCall).map(partOf));
73
+ reading.messages.push({ role: 'assistant', content, ...(toolCalls.length ? { toolCalls } : {}) });
74
+ }
75
+ function answeredCall(reading, response) {
76
+ const index = reading.open.findIndex((call) => (response.id ? call.id === response.id : call.name === response.name));
77
+ if (index < 0) {
78
+ throw new WalletRequestError(`A function response answers ${response.name}, which no open call made`, 400);
79
+ }
80
+ return reading.open.splice(index, 1)[0];
81
+ }
82
+ function readUser(reading, parts) {
83
+ for (const part of parts.filter((candidate) => candidate.functionResponse)) {
84
+ const call = answeredCall(reading, part.functionResponse);
85
+ const content = JSON.stringify(part.functionResponse.response ?? {});
86
+ reading.messages.push({ role: 'tool', toolCallId: call.id, name: call.name, content });
87
+ }
88
+ const rest = parts.filter((part) => !part.functionResponse).map(partOf);
89
+ if (rest.length) {
90
+ reading.messages.push({ role: 'user', content: userContent(rest) });
91
+ }
92
+ }
93
+ // Thought parts hold the provider's own reasoning, which another account cannot read.
94
+ function readMessages(body) {
95
+ const reading = { messages: [], open: [], calls: 0 };
96
+ const system = typeof body.systemInstruction === 'string'
97
+ ? body.systemInstruction
98
+ : textOf((body.systemInstruction?.parts ?? []).map(partOf));
99
+ if (system) {
100
+ reading.messages.push({ role: 'system', content: system });
101
+ }
102
+ for (const content of body.contents ?? []) {
103
+ const parts = (content.parts ?? []).filter((part) => !part.thought);
104
+ if (content.role === 'model') {
105
+ readModel(reading, parts);
106
+ }
107
+ else {
108
+ readUser(reading, parts);
109
+ }
110
+ }
111
+ return reading.messages;
112
+ }
113
+ function readTools(tools) {
114
+ if (!tools) {
115
+ return undefined;
116
+ }
117
+ return [tools].flat().flatMap((tool) => {
118
+ if (!tool.functionDeclarations) {
119
+ throw unsupported(`the ${Object.keys(tool).join(', ')} tool`);
120
+ }
121
+ return tool.functionDeclarations.map(({ name, description = '', parameters, parametersJsonSchema }) => ({
122
+ name,
123
+ description,
124
+ inputSchema: parametersJsonSchema ?? (parameters ? jsonSchemaOf(parameters) : EMPTY_PARAMETERS),
125
+ }));
126
+ });
127
+ }
128
+ function readToolChoice(config) {
129
+ const calling = config?.functionCallingConfig;
130
+ const names = calling?.allowedFunctionNames ?? [];
131
+ if (calling?.mode === 'ANY' && names.length === 1) {
132
+ return { name: names[0] };
133
+ }
134
+ return calling?.mode ? TOOL_MODES[calling.mode] : undefined;
135
+ }
136
+ function read(raw, url) {
137
+ const body = raw;
138
+ const generation = body.generationConfig ?? {};
139
+ if ((generation.candidateCount ?? 1) > 1) {
140
+ throw unsupported('several candidates per request');
141
+ }
142
+ const { responseJsonSchema, responseSchema } = generation;
143
+ const schema = responseJsonSchema ?? (responseSchema ? jsonSchemaOf(responseSchema) : undefined);
144
+ const json = generation.responseMimeType === 'application/json';
145
+ return {
146
+ request: {
147
+ messages: readMessages(body),
148
+ tools: readTools(body.tools),
149
+ options: {
150
+ maxTokens: generation.maxOutputTokens,
151
+ temperature: generation.temperature,
152
+ topP: generation.topP,
153
+ stop: generation.stopSequences,
154
+ toolChoice: readToolChoice(body.toolConfig),
155
+ responseFormat: json ? { type: 'json', schema } : undefined,
156
+ },
157
+ },
158
+ stream: /:streamGenerateContent$/i.test(url.pathname),
159
+ };
160
+ }
161
+ function usageMetadata(usage) {
162
+ if (!usage) {
163
+ return undefined;
164
+ }
165
+ return {
166
+ promptTokenCount: usage.inputTokens,
167
+ candidatesTokenCount: usage.outputTokens,
168
+ totalTokenCount: usage.inputTokens + usage.outputTokens,
169
+ cachedContentTokenCount: usage.cachedInputTokens,
170
+ };
171
+ }
172
+ function callParts(calls = []) {
173
+ return calls.map((call) => ({ functionCall: { id: call.id, name: call.name, args: call.arguments } }));
174
+ }
175
+ function chunk(context, model, parts, response) {
176
+ const finish = response ? { finishReason: FINISH_REASONS[response.finishReason] } : {};
177
+ return {
178
+ candidates: [{ content: { role: 'model', parts }, index: 0, ...finish }],
179
+ usageMetadata: usageMetadata(response?.usage),
180
+ modelVersion: model,
181
+ responseId: context.id,
182
+ };
183
+ }
184
+ async function stream(answer, write, context) {
185
+ const { model } = await answer.started;
186
+ for await (const text of answer.texts()) {
187
+ write.send(chunk(context, model, [{ text }]));
188
+ }
189
+ const response = await answer.result;
190
+ write.send(chunk(context, response.model, callParts(response.message.toolCalls), response));
191
+ }
192
+ function body(response, context) {
193
+ const { content, toolCalls } = response.message;
194
+ const parts = [...(content ? [{ text: content }] : []), ...callParts(toolCalls)];
195
+ return chunk(context, response.model, parts, response);
196
+ }
197
+ function errorBody(error) {
198
+ return { error: { code: error.status, message: error.message, status: GOOGLE_STATUSES[error.status] ?? 'INTERNAL' } };
199
+ }
200
+ export const geminiContents = { read, stream, body, error: errorBody };
201
+ //# sourceMappingURL=geminiContents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geminiContents.js","sourceRoot":"","sources":["../../src/wireProtocols/geminiContents.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,mGAAmG;AACnG,4FAA4F;AAC5F,gGAAgG;AAChG,kEAAkE;AAElE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAI3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAoD/E,MAAM,cAAc,GAAiC;IACnD,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,MAAM;IACjB,MAAM,EAAE,YAAY;IACpB,aAAa,EAAE,QAAQ;CACxB,CAAC;AAEF,MAAM,UAAU,GAA+B,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC;AAElH,MAAM,eAAe,GAA2B;IAC9C,GAAG,EAAE,kBAAkB;IACvB,GAAG,EAAE,iBAAiB;IACtB,GAAG,EAAE,mBAAmB;IACxB,GAAG,EAAE,WAAW;IAChB,GAAG,EAAE,oBAAoB;IACzB,GAAG,EAAE,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C,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,UAAU,EAAE,EAAE,CAAC;AACxH,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC","sourcesContent":["// The Gemini `generateContent` protocol, as Google's Gen AI SDK and the Vercel AI SDK's `google()`\n// models speak it. The path says whether to stream (`:streamGenerateContent`). Streamed answers go\n// as plain data events of the same response shape; the last one carries the tool calls, the\n// finish reason and the token counts. Gemini may leave tool call ids out: calls then get one in\n// order, and each result answers the first open call of its name.\n\nimport { textOf } from '../chatContent.ts';\nimport type {\n ChatMessage, ChatResponse, ContentPart, FinishReason, JsonSchema, ToolCall, ToolChoice, ToolDefinition, Usage,\n} from '../types.ts';\nimport { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport { EMPTY_PARAMETERS, unsupported, userContent } from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface WirePart {\n text?: string;\n thought?: boolean;\n inlineData?: { mimeType: string; data: string };\n fileData?: { mimeType?: string; fileUri: string };\n functionCall?: { id?: string; name: string; args?: Record<string, unknown> };\n functionResponse?: { id?: string; name: string; response?: unknown };\n}\n\ninterface WireContent {\n role?: string;\n parts?: WirePart[];\n}\n\ninterface FunctionDeclaration {\n name: string;\n description?: string;\n parameters?: JsonSchema;\n parametersJsonSchema?: JsonSchema;\n}\n\ninterface WireTool {\n functionDeclarations?: FunctionDeclaration[];\n}\n\ninterface GenerateBody {\n contents?: WireContent[];\n systemInstruction?: string | WireContent;\n tools?: WireTool | WireTool[];\n toolConfig?: { functionCallingConfig?: { mode?: string; allowedFunctionNames?: string[] } };\n generationConfig?: {\n maxOutputTokens?: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n candidateCount?: number;\n responseMimeType?: string;\n responseSchema?: JsonSchema;\n responseJsonSchema?: JsonSchema;\n };\n}\n\n// The conversation being read, with the tool calls still waiting for their result.\ninterface Reading {\n messages: ChatMessage[];\n open: ToolCall[];\n calls: number;\n}\n\nconst FINISH_REASONS: Record<FinishReason, string> = {\n stop: 'STOP',\n toolCalls: 'STOP',\n length: 'MAX_TOKENS',\n contentFilter: 'SAFETY',\n};\n\nconst TOOL_MODES: Record<string, ToolChoice> = { AUTO: 'auto', NONE: 'none', ANY: 'required', VALIDATED: 'auto' };\n\nconst GOOGLE_STATUSES: Record<number, string> = {\n 400: 'INVALID_ARGUMENT',\n 401: 'UNAUTHENTICATED',\n 403: 'PERMISSION_DENIED',\n 404: 'NOT_FOUND',\n 429: 'RESOURCE_EXHAUSTED',\n 503: 'UNAVAILABLE',\n};\n\n// Gemini's OpenAPI style schema as JSON Schema: lower case types, `nullable` as a null type, and\n// no `propertyOrdering`, which other providers refuse.\nfunction jsonSchemaOf(schema: JsonSchema): JsonSchema {\n const converted: JsonSchema = { ...schema };\n delete converted.propertyOrdering;\n delete converted.nullable;\n if (typeof schema.type === 'string') {\n const type = schema.type.toLowerCase();\n converted.type = schema.nullable ? [type, 'null'] : type;\n }\n if (schema.properties) {\n const properties = Object.entries(schema.properties as Record<string, JsonSchema>);\n converted.properties = Object.fromEntries(properties.map(([name, value]) => [name, jsonSchemaOf(value)]));\n }\n if (schema.items) {\n converted.items = jsonSchemaOf(schema.items as JsonSchema);\n }\n if (Array.isArray(schema.anyOf)) {\n converted.anyOf = (schema.anyOf as JsonSchema[]).map(jsonSchemaOf);\n }\n return converted;\n}\n\nfunction mediaPart(mimeType: string | undefined, url: string): ContentPart {\n if (!mimeType?.startsWith('image/')) {\n throw unsupported(`${mimeType ?? 'untyped'} files`);\n }\n return { type: 'image', url };\n}\n\nfunction partOf(part: WirePart): ContentPart {\n if (typeof part.text === 'string') {\n return { type: 'text', text: part.text };\n }\n if (part.inlineData) {\n const { mimeType, data } = part.inlineData;\n return mediaPart(mimeType, `data:${mimeType};base64,${data}`);\n }\n if (part.fileData) {\n return mediaPart(part.fileData.mimeType, part.fileData.fileUri);\n }\n throw unsupported(`the ${Object.keys(part).join(', ')} part`);\n}\n\nfunction readModel(reading: Reading, parts: WirePart[]): void {\n const toolCalls: ToolCall[] = parts.filter((part) => part.functionCall).map((part) => {\n const { id, name, args } = part.functionCall!;\n reading.calls += 1;\n return { id: id ?? `call_${reading.calls}`, name, arguments: args ?? {} };\n });\n reading.open.push(...toolCalls);\n const content = textOf(parts.filter((part) => !part.functionCall).map(partOf));\n reading.messages.push({ role: 'assistant', content, ...(toolCalls.length ? { toolCalls } : {}) });\n}\n\nfunction answeredCall(reading: Reading, response: NonNullable<WirePart['functionResponse']>): ToolCall {\n const index = reading.open.findIndex((call) => (response.id ? call.id === response.id : call.name === response.name));\n if (index < 0) {\n throw new WalletRequestError(`A function response answers ${response.name}, which no open call made`, 400);\n }\n return reading.open.splice(index, 1)[0];\n}\n\nfunction readUser(reading: Reading, parts: WirePart[]): void {\n for (const part of parts.filter((candidate) => candidate.functionResponse)) {\n const call = answeredCall(reading, part.functionResponse!);\n const content = JSON.stringify(part.functionResponse!.response ?? {});\n reading.messages.push({ role: 'tool', toolCallId: call.id, name: call.name, content });\n }\n const rest = parts.filter((part) => !part.functionResponse).map(partOf);\n if (rest.length) {\n reading.messages.push({ role: 'user', content: userContent(rest) });\n }\n}\n\n// Thought parts hold the provider's own reasoning, which another account cannot read.\nfunction readMessages(body: GenerateBody): ChatMessage[] {\n const reading: Reading = { messages: [], open: [], calls: 0 };\n const system = typeof body.systemInstruction === 'string'\n ? body.systemInstruction\n : textOf((body.systemInstruction?.parts ?? []).map(partOf));\n if (system) {\n reading.messages.push({ role: 'system', content: system });\n }\n for (const content of body.contents ?? []) {\n const parts = (content.parts ?? []).filter((part) => !part.thought);\n if (content.role === 'model') {\n readModel(reading, parts);\n } else {\n readUser(reading, parts);\n }\n }\n return reading.messages;\n}\n\nfunction readTools(tools: GenerateBody['tools']): ToolDefinition[] | undefined {\n if (!tools) {\n return undefined;\n }\n return [tools].flat().flatMap((tool) => {\n if (!tool.functionDeclarations) {\n throw unsupported(`the ${Object.keys(tool).join(', ')} tool`);\n }\n return tool.functionDeclarations.map(({ name, description = '', parameters, parametersJsonSchema }) => ({\n name,\n description,\n inputSchema: parametersJsonSchema ?? (parameters ? jsonSchemaOf(parameters) : EMPTY_PARAMETERS),\n }));\n });\n}\n\nfunction readToolChoice(config: GenerateBody['toolConfig']): ToolChoice | undefined {\n const calling = config?.functionCallingConfig;\n const names = calling?.allowedFunctionNames ?? [];\n if (calling?.mode === 'ANY' && names.length === 1) {\n return { name: names[0] };\n }\n return calling?.mode ? TOOL_MODES[calling.mode] : undefined;\n}\n\nfunction read(raw: Record<string, unknown>, url: URL): WireRequest {\n const body = raw as GenerateBody;\n const generation = body.generationConfig ?? {};\n if ((generation.candidateCount ?? 1) > 1) {\n throw unsupported('several candidates per request');\n }\n const { responseJsonSchema, responseSchema } = generation;\n const schema = responseJsonSchema ?? (responseSchema ? jsonSchemaOf(responseSchema) : undefined);\n const json = generation.responseMimeType === 'application/json';\n return {\n request: {\n messages: readMessages(body),\n tools: readTools(body.tools),\n options: {\n maxTokens: generation.maxOutputTokens,\n temperature: generation.temperature,\n topP: generation.topP,\n stop: generation.stopSequences,\n toolChoice: readToolChoice(body.toolConfig),\n responseFormat: json ? { type: 'json', schema } : undefined,\n },\n },\n stream: /:streamGenerateContent$/i.test(url.pathname),\n };\n}\n\nfunction usageMetadata(usage: Usage | undefined) {\n if (!usage) {\n return undefined;\n }\n return {\n promptTokenCount: usage.inputTokens,\n candidatesTokenCount: usage.outputTokens,\n totalTokenCount: usage.inputTokens + usage.outputTokens,\n cachedContentTokenCount: usage.cachedInputTokens,\n };\n}\n\nfunction callParts(calls: ToolCall[] = []): WirePart[] {\n return calls.map((call) => ({ functionCall: { id: call.id, name: call.name, args: call.arguments } }));\n}\n\nfunction chunk(context: AnswerContext, model: string, parts: WirePart[], response?: ChatResponse) {\n const finish = response ? { finishReason: FINISH_REASONS[response.finishReason] } : {};\n return {\n candidates: [{ content: { role: 'model', parts }, index: 0, ...finish }],\n usageMetadata: usageMetadata(response?.usage),\n modelVersion: model,\n responseId: context.id,\n };\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const { model } = await answer.started;\n for await (const text of answer.texts()) {\n write.send(chunk(context, model, [{ text }]));\n }\n const response = await answer.result;\n write.send(chunk(context, response.model, callParts(response.message.toolCalls), response));\n}\n\nfunction body(response: ChatResponse, context: AnswerContext) {\n const { content, toolCalls } = response.message;\n const parts = [...(content ? [{ text: content }] : []), ...callParts(toolCalls)];\n return chunk(context, response.model, parts, response);\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { error: { code: error.status, message: error.message, status: GOOGLE_STATUSES[error.status] ?? 'INTERNAL' } };\n}\n\nexport const geminiContents: WireProtocol = { read, stream, body, error: errorBody };\n"]}
@@ -0,0 +1,2 @@
1
+ import type { WireProtocol } from './wireProtocol.ts';
2
+ export declare const openAiChat: WireProtocol;