@blackbox_ai/blackbox-cli-core 0.0.9 → 0.8.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.
- package/README.md +11 -183
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/src/blackbox/blackboxOAuth2.js +17 -1
- package/dist/src/blackbox/blackboxOAuth2.js.map +1 -1
- package/dist/src/code_assist/oauth2.js +15 -3
- package/dist/src/code_assist/oauth2.js.map +1 -1
- package/dist/src/config/blackboxModels.d.ts +3 -2
- package/dist/src/config/blackboxModels.js +262 -33
- package/dist/src/config/blackboxModels.js.map +1 -1
- package/dist/src/config/config.d.ts +65 -0
- package/dist/src/config/config.js +282 -17
- package/dist/src/config/config.js.map +1 -1
- package/dist/src/config/models.d.ts +1 -1
- package/dist/src/config/models.js +1 -1
- package/dist/src/config/models.js.map +1 -1
- package/dist/src/config/multiAgentModels.d.ts +63 -0
- package/dist/src/config/multiAgentModels.js +194 -0
- package/dist/src/config/multiAgentModels.js.map +1 -0
- package/dist/src/core/client.js +8 -2
- package/dist/src/core/client.js.map +1 -1
- package/dist/src/core/contentGenerator.d.ts +1 -0
- package/dist/src/core/contentGenerator.js +57 -7
- package/dist/src/core/contentGenerator.js.map +1 -1
- package/dist/src/core/encryptedClientFactory.d.ts +17 -0
- package/dist/src/core/encryptedClientFactory.js +92 -0
- package/dist/src/core/encryptedClientFactory.js.map +1 -0
- package/dist/src/core/encryptedContentGenerator.d.ts +47 -0
- package/dist/src/core/encryptedContentGenerator.js +445 -0
- package/dist/src/core/encryptedContentGenerator.js.map +1 -0
- package/dist/src/core/encryptedGeminiClient.d.ts +59 -0
- package/dist/src/core/encryptedGeminiClient.js +177 -0
- package/dist/src/core/encryptedGeminiClient.js.map +1 -0
- package/dist/src/core/encryptedGeminiClientBridge.d.ts +107 -0
- package/dist/src/core/encryptedGeminiClientBridge.js +808 -0
- package/dist/src/core/encryptedGeminiClientBridge.js.map +1 -0
- package/dist/src/core/encryptedGeminiClientWrapper.d.ts +129 -0
- package/dist/src/core/encryptedGeminiClientWrapper.js +305 -0
- package/dist/src/core/encryptedGeminiClientWrapper.js.map +1 -0
- package/dist/src/core/encryptedTurn.d.ts +40 -0
- package/dist/src/core/encryptedTurn.js +114 -0
- package/dist/src/core/encryptedTurn.js.map +1 -0
- package/dist/src/core/logger.d.ts +21 -0
- package/dist/src/core/logger.js +110 -0
- package/dist/src/core/logger.js.map +1 -1
- package/dist/src/core/openaiContentGenerator/constants.d.ts +2 -0
- package/dist/src/core/openaiContentGenerator/constants.js +2 -0
- package/dist/src/core/openaiContentGenerator/constants.js.map +1 -1
- package/dist/src/core/openaiContentGenerator/converter.d.ts +16 -1
- package/dist/src/core/openaiContentGenerator/converter.js +135 -4
- package/dist/src/core/openaiContentGenerator/converter.js.map +1 -1
- package/dist/src/core/openaiContentGenerator/pipeline.js +6 -2
- package/dist/src/core/openaiContentGenerator/pipeline.js.map +1 -1
- package/dist/src/core/openaiContentGenerator/provider/default.js +10 -1
- package/dist/src/core/openaiContentGenerator/provider/default.js.map +1 -1
- package/dist/src/core/prompts.d.ts +17 -0
- package/dist/src/core/prompts.js +347 -19
- package/dist/src/core/prompts.js.map +1 -1
- package/dist/src/core/tokenLimits.d.ts +1 -0
- package/dist/src/core/tokenLimits.js +37 -2
- package/dist/src/core/tokenLimits.js.map +1 -1
- package/dist/src/core/tokenLimits.test.js +36 -1
- package/dist/src/core/tokenLimits.test.js.map +1 -1
- package/dist/src/encrypt/attestation.d.ts +5 -0
- package/dist/src/encrypt/attestation.js +100 -0
- package/dist/src/encrypt/attestation.js.map +1 -0
- package/dist/src/encrypt/client.d.ts +14 -0
- package/dist/src/encrypt/client.js +132 -0
- package/dist/src/encrypt/client.js.map +1 -0
- package/dist/src/encrypt/config.d.ts +22 -0
- package/dist/src/encrypt/config.js +43 -0
- package/dist/src/encrypt/config.js.map +1 -0
- package/dist/src/encrypt/crypto-utils.d.ts +57 -0
- package/dist/src/encrypt/crypto-utils.js +257 -0
- package/dist/src/encrypt/crypto-utils.js.map +1 -0
- package/dist/src/encrypt/history-manager.d.ts +43 -0
- package/dist/src/encrypt/history-manager.js +164 -0
- package/dist/src/encrypt/history-manager.js.map +1 -0
- package/dist/src/encrypt/minimax-template.d.ts +73 -0
- package/dist/src/encrypt/minimax-template.js +276 -0
- package/dist/src/encrypt/minimax-template.js.map +1 -0
- package/dist/src/encrypt/sessions.d.ts +17 -0
- package/dist/src/encrypt/sessions.js +221 -0
- package/dist/src/encrypt/sessions.js.map +1 -0
- package/dist/src/encrypt/streaming-client.d.ts +29 -0
- package/dist/src/encrypt/streaming-client.js +232 -0
- package/dist/src/encrypt/streaming-client.js.map +1 -0
- package/dist/src/encrypt/tool-formatter.d.ts +36 -0
- package/dist/src/encrypt/tool-formatter.js +353 -0
- package/dist/src/encrypt/tool-formatter.js.map +1 -0
- package/dist/src/encrypt/tool-parser.d.ts +93 -0
- package/dist/src/encrypt/tool-parser.js +567 -0
- package/dist/src/encrypt/tool-parser.js.map +1 -0
- package/dist/src/encrypt/types.d.ts +81 -0
- package/dist/src/encrypt/types.js +2 -0
- package/dist/src/encrypt/types.js.map +1 -0
- package/dist/src/generated/git-commit.d.ts +3 -3
- package/dist/src/generated/git-commit.js +3 -3
- package/dist/src/ide/ide-client.js +9 -19
- package/dist/src/ide/ide-client.js.map +1 -1
- package/dist/src/index.d.ts +15 -0
- package/dist/src/index.js +15 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/mcp/oauth-provider.js +2 -6
- package/dist/src/mcp/oauth-provider.js.map +1 -1
- package/dist/src/mcp/oauth-token-storage.d.ts +7 -0
- package/dist/src/mcp/oauth-token-storage.js +24 -0
- package/dist/src/mcp/oauth-token-storage.js.map +1 -1
- package/dist/src/services/EncryptedChatService.d.ts +80 -0
- package/dist/src/services/EncryptedChatService.js +202 -0
- package/dist/src/services/EncryptedChatService.js.map +1 -0
- package/dist/src/services/StatsHistoryService.d.ts +131 -0
- package/dist/src/services/StatsHistoryService.js +427 -0
- package/dist/src/services/StatsHistoryService.js.map +1 -0
- package/dist/src/services/checkpointApiService.d.ts +101 -0
- package/dist/src/services/checkpointApiService.js +215 -0
- package/dist/src/services/checkpointApiService.js.map +1 -0
- package/dist/src/services/environmentSanitization.d.ts +24 -0
- package/dist/src/services/environmentSanitization.js +152 -0
- package/dist/src/services/environmentSanitization.js.map +1 -0
- package/dist/src/telemetry/blackbox-logger/blackbox-logger.d.ts +2 -6
- package/dist/src/telemetry/blackbox-logger/blackbox-logger.js +29 -135
- package/dist/src/telemetry/blackbox-logger/blackbox-logger.js.map +1 -1
- package/dist/src/telemetry/blackbox-logger/blackbox-logger.test.js +1 -1
- package/dist/src/telemetry/blackbox-logger/blackbox-logger.test.js.map +1 -1
- package/dist/src/telemetry/uiTelemetry.d.ts +8 -0
- package/dist/src/telemetry/uiTelemetry.js +17 -0
- package/dist/src/telemetry/uiTelemetry.js.map +1 -1
- package/dist/src/tools/browser-interactive.d.ts +63 -0
- package/dist/src/tools/browser-interactive.js +394 -0
- package/dist/src/tools/browser-interactive.js.map +1 -0
- package/dist/src/tools/browser_use.d.ts +22 -1
- package/dist/src/tools/browser_use.js +403 -23
- package/dist/src/tools/browser_use.js.map +1 -1
- package/dist/src/tools/data-file-constants.d.ts +17 -0
- package/dist/src/tools/data-file-constants.js +30 -0
- package/dist/src/tools/data-file-constants.js.map +1 -0
- package/dist/src/tools/edit.js +44 -7
- package/dist/src/tools/edit.js.map +1 -1
- package/dist/src/tools/ls.js +40 -6
- package/dist/src/tools/ls.js.map +1 -1
- package/dist/src/tools/ls.test.js +4 -4
- package/dist/src/tools/ls.test.js.map +1 -1
- package/dist/src/tools/mcp-client-manager.d.ts +28 -2
- package/dist/src/tools/mcp-client-manager.js +62 -4
- package/dist/src/tools/mcp-client-manager.js.map +1 -1
- package/dist/src/tools/mcp-client.d.ts +5 -3
- package/dist/src/tools/mcp-client.js +39 -11
- package/dist/src/tools/mcp-client.js.map +1 -1
- package/dist/src/tools/mcp-tool.d.ts +3 -1
- package/dist/src/tools/mcp-tool.js +37 -9
- package/dist/src/tools/mcp-tool.js.map +1 -1
- package/dist/src/tools/memoryTool.d.ts +14 -4
- package/dist/src/tools/memoryTool.js +98 -39
- package/dist/src/tools/memoryTool.js.map +1 -1
- package/dist/src/tools/read-data-file.d.ts +31 -0
- package/dist/src/tools/read-data-file.js +469 -0
- package/dist/src/tools/read-data-file.js.map +1 -0
- package/dist/src/tools/read-file.js +64 -5
- package/dist/src/tools/read-file.js.map +1 -1
- package/dist/src/tools/read-file.test.js +40 -6
- package/dist/src/tools/read-file.test.js.map +1 -1
- package/dist/src/tools/shell.d.ts +3 -1
- package/dist/src/tools/shell.js +25 -4
- package/dist/src/tools/shell.js.map +1 -1
- package/dist/src/tools/skill.d.ts +34 -0
- package/dist/src/tools/skill.js +143 -0
- package/dist/src/tools/skill.js.map +1 -0
- package/dist/src/tools/sql_db.d.ts +101 -0
- package/dist/src/tools/sql_db.js +1033 -0
- package/dist/src/tools/sql_db.js.map +1 -0
- package/dist/src/tools/sql_db_configure.d.ts +18 -0
- package/dist/src/tools/sql_db_configure.js +96 -0
- package/dist/src/tools/sql_db_configure.js.map +1 -0
- package/dist/src/tools/taskCompletion.d.ts +29 -0
- package/dist/src/tools/taskCompletion.js +231 -0
- package/dist/src/tools/taskCompletion.js.map +1 -0
- package/dist/src/tools/tool-error.d.ts +3 -1
- package/dist/src/tools/tool-error.js +3 -0
- package/dist/src/tools/tool-error.js.map +1 -1
- package/dist/src/tools/tool-names.d.ts +8 -0
- package/dist/src/tools/tool-names.js +8 -0
- package/dist/src/tools/tool-names.js.map +1 -1
- package/dist/src/tools/tool-registry.d.ts +22 -0
- package/dist/src/tools/tool-registry.js +41 -1
- package/dist/src/tools/tool-registry.js.map +1 -1
- package/dist/src/tools/tools.d.ts +18 -2
- package/dist/src/tools/tools.js +3 -0
- package/dist/src/tools/tools.js.map +1 -1
- package/dist/src/tools/web-fetch.js +24 -4
- package/dist/src/tools/web-fetch.js.map +1 -1
- package/dist/src/tools/web-search.js +160 -2
- package/dist/src/tools/web-search.js.map +1 -1
- package/dist/src/tools/workspace-error-helper.d.ts +9 -0
- package/dist/src/tools/workspace-error-helper.js +43 -0
- package/dist/src/tools/workspace-error-helper.js.map +1 -0
- package/dist/src/tools/workspace-error-helper.test.js +85 -0
- package/dist/src/tools/workspace-error-helper.test.js.map +1 -0
- package/dist/src/tools/write-file.js +42 -7
- package/dist/src/tools/write-file.js.map +1 -1
- package/dist/src/utils/environmentContext.js +3 -1
- package/dist/src/utils/environmentContext.js.map +1 -1
- package/dist/src/utils/environmentContext.test.js +3 -2
- package/dist/src/utils/environmentContext.test.js.map +1 -1
- package/dist/src/utils/fetch.d.ts +3 -1
- package/dist/src/utils/fetch.js +35 -2
- package/dist/src/utils/fetch.js.map +1 -1
- package/dist/src/utils/fileUtils.js +30 -3
- package/dist/src/utils/fileUtils.js.map +1 -1
- package/dist/src/utils/filesearch/fileSearch.d.ts +2 -0
- package/dist/src/utils/filesearch/fileSearch.js +38 -7
- package/dist/src/utils/filesearch/fileSearch.js.map +1 -1
- package/dist/src/utils/git-worktree-utils.d.ts +56 -0
- package/dist/src/utils/git-worktree-utils.js +176 -0
- package/dist/src/utils/git-worktree-utils.js.map +1 -0
- package/dist/src/utils/imageCompression.d.ts +34 -0
- package/dist/src/utils/imageCompression.js +170 -0
- package/dist/src/utils/imageCompression.js.map +1 -0
- package/dist/src/utils/messageTruncator.d.ts +51 -0
- package/dist/src/utils/messageTruncator.js +346 -0
- package/dist/src/utils/messageTruncator.js.map +1 -0
- package/dist/src/utils/pathReader.js +26 -6
- package/dist/src/utils/pathReader.js.map +1 -1
- package/dist/src/utils/skill.d.ts +65 -0
- package/dist/src/utils/skill.js +241 -0
- package/dist/src/utils/skill.js.map +1 -0
- package/dist/src/utils/textCleaning.d.ts +51 -0
- package/dist/src/utils/textCleaning.js +327 -0
- package/dist/src/utils/textCleaning.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +16 -2
- package/dist/src/tools/mcp-client-manager.test.js +0 -39
- package/dist/src/tools/mcp-client-manager.test.js.map +0 -1
- package/dist/src/tools/mcp-client.test.d.ts +0 -6
- package/dist/src/tools/mcp-client.test.js +0 -454
- package/dist/src/tools/mcp-client.test.js.map +0 -1
- package/dist/src/tools/mcp-tool.test.d.ts +0 -6
- package/dist/src/tools/mcp-tool.test.js +0 -576
- package/dist/src/tools/mcp-tool.test.js.map +0 -1
- package/dist/src/tools/memoryTool.test.d.ts +0 -6
- package/dist/src/tools/memoryTool.test.js +0 -420
- package/dist/src/tools/memoryTool.test.js.map +0 -1
- package/dist/src/tools/tool-registry.test.d.ts +0 -6
- package/dist/src/tools/tool-registry.test.js +0 -332
- package/dist/src/tools/tool-registry.test.js.map +0 -1
- /package/dist/src/tools/{mcp-client-manager.test.d.ts → workspace-error-helper.test.d.ts} +0 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Low-level cryptographic utilities extracted from streaming-client.ts
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Convert Uint8Array to base64 string
|
|
6
|
+
*/
|
|
7
|
+
export const toB64 = (u8) => {
|
|
8
|
+
// Handle large arrays by chunking to avoid "Maximum call stack size exceeded"
|
|
9
|
+
if (u8.length > 8192) {
|
|
10
|
+
let result = '';
|
|
11
|
+
for (let i = 0; i < u8.length; i += 8192) {
|
|
12
|
+
const chunk = u8.slice(i, i + 8192);
|
|
13
|
+
result += String.fromCharCode.apply(null, Array.from(chunk));
|
|
14
|
+
}
|
|
15
|
+
return btoa(result);
|
|
16
|
+
}
|
|
17
|
+
return btoa(String.fromCharCode.apply(null, Array.from(u8)));
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Convert base64 string to Uint8Array
|
|
21
|
+
*/
|
|
22
|
+
export const fromB64 = (b64) => new Uint8Array(Array.from(atob(b64), c => c.charCodeAt(0)));
|
|
23
|
+
/**
|
|
24
|
+
* Generate a UUID for identification (moved from streaming-client.ts)
|
|
25
|
+
*/
|
|
26
|
+
export const generateUuid = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
27
|
+
const r = Math.random() * 16 | 0;
|
|
28
|
+
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
|
29
|
+
return v.toString(16);
|
|
30
|
+
});
|
|
31
|
+
/**
|
|
32
|
+
* Generate a P-384 keypair for both ECDSA and ECDH operations (moved from streaming-client.ts)
|
|
33
|
+
* Reuses the same key material for both operations (matching Rust behavior)
|
|
34
|
+
*/
|
|
35
|
+
export async function generateKeyPair() {
|
|
36
|
+
// Generate a single P-384 keypair
|
|
37
|
+
const ecdsaKeyPair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-384' }, true, ['sign', 'verify']);
|
|
38
|
+
// Export the private key to reuse for ECDH
|
|
39
|
+
const pkcs8 = await crypto.subtle.exportKey('pkcs8', ecdsaKeyPair.privateKey);
|
|
40
|
+
// Import the same private key for ECDH operations
|
|
41
|
+
const ecdhPrivate = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'ECDH', namedCurve: 'P-384' }, false, ['deriveBits']);
|
|
42
|
+
return {
|
|
43
|
+
ecdhPrivate,
|
|
44
|
+
ecdsaPrivate: ecdsaKeyPair.privateKey,
|
|
45
|
+
ecdsaPublic: ecdsaKeyPair.publicKey
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function ecdsaRawToDer(raw) {
|
|
49
|
+
// raw is Uint8Array of length 96 for P-384: r(48) || s(48)
|
|
50
|
+
const n = raw.length / 2;
|
|
51
|
+
let r = new Uint8Array(raw.buffer.slice(0, n));
|
|
52
|
+
let s = new Uint8Array(raw.buffer.slice(n));
|
|
53
|
+
// Trim leading zeros
|
|
54
|
+
r = trimZeros(r);
|
|
55
|
+
s = trimZeros(s);
|
|
56
|
+
// Ensure positive (prepend 0x00 if high bit is set)
|
|
57
|
+
if (r[0] & 0x80) {
|
|
58
|
+
const padding = new Uint8Array([0x00]);
|
|
59
|
+
r = concatBytes(padding, r);
|
|
60
|
+
}
|
|
61
|
+
if (s[0] & 0x80) {
|
|
62
|
+
const padding = new Uint8Array([0x00]);
|
|
63
|
+
s = concatBytes(padding, s);
|
|
64
|
+
}
|
|
65
|
+
const rHeader = new Uint8Array([0x02, r.length]);
|
|
66
|
+
const rEnc = concatBytes(rHeader, r);
|
|
67
|
+
const sHeader = new Uint8Array([0x02, s.length]);
|
|
68
|
+
const sEnc = concatBytes(sHeader, s);
|
|
69
|
+
const seqLen = rEnc.length + sEnc.length;
|
|
70
|
+
const seqHeader = new Uint8Array([0x30, seqLen]);
|
|
71
|
+
const der = concatBytes(seqHeader, rEnc, sEnc);
|
|
72
|
+
return der;
|
|
73
|
+
function trimZeros(bytes) {
|
|
74
|
+
let i = 0;
|
|
75
|
+
while (i < bytes.length - 1 && bytes[i] === 0)
|
|
76
|
+
i++;
|
|
77
|
+
const trimmed = new Uint8Array(bytes.length - i);
|
|
78
|
+
for (let j = 0; j < trimmed.length; j++) {
|
|
79
|
+
trimmed[j] = bytes[i + j];
|
|
80
|
+
}
|
|
81
|
+
return trimmed;
|
|
82
|
+
}
|
|
83
|
+
function concatBytes(a, b, c) {
|
|
84
|
+
if (c) {
|
|
85
|
+
const total = a.length + b.length + c.length;
|
|
86
|
+
const out = new Uint8Array(total);
|
|
87
|
+
out.set(a, 0);
|
|
88
|
+
out.set(b, a.length);
|
|
89
|
+
out.set(c, a.length + b.length);
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
const total = a.length + b.length;
|
|
94
|
+
const out = new Uint8Array(total);
|
|
95
|
+
out.set(a, 0);
|
|
96
|
+
out.set(b, a.length);
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// Convert ASN.1 DER signature to WebCrypto raw format (r||s)
|
|
102
|
+
export function ecdsaDerToRaw(der) {
|
|
103
|
+
// Parse DER: SEQUENCE { INTEGER r, INTEGER s }
|
|
104
|
+
if (der[0] !== 0x30) {
|
|
105
|
+
throw new Error('Invalid DER signature: not a SEQUENCE');
|
|
106
|
+
}
|
|
107
|
+
let offset = 2; // Skip SEQUENCE tag and length
|
|
108
|
+
// Parse r
|
|
109
|
+
if (der[offset] !== 0x02) {
|
|
110
|
+
throw new Error('Invalid DER signature: r not an INTEGER');
|
|
111
|
+
}
|
|
112
|
+
offset++;
|
|
113
|
+
const rLen = der[offset++];
|
|
114
|
+
let r = der.slice(offset, offset + rLen);
|
|
115
|
+
offset += rLen;
|
|
116
|
+
// Parse s
|
|
117
|
+
if (der[offset] !== 0x02) {
|
|
118
|
+
throw new Error('Invalid DER signature: s not an INTEGER');
|
|
119
|
+
}
|
|
120
|
+
offset++;
|
|
121
|
+
const sLen = der[offset++];
|
|
122
|
+
let s = der.slice(offset, offset + sLen);
|
|
123
|
+
// Remove leading zero padding if present
|
|
124
|
+
if (r[0] === 0x00 && r.length > 1)
|
|
125
|
+
r = r.slice(1);
|
|
126
|
+
if (s[0] === 0x00 && s.length > 1)
|
|
127
|
+
s = s.slice(1);
|
|
128
|
+
// Pad to 48 bytes for P-384
|
|
129
|
+
const targetLen = 48;
|
|
130
|
+
if (r.length < targetLen) {
|
|
131
|
+
const padded = new Uint8Array(targetLen);
|
|
132
|
+
padded.set(r, targetLen - r.length);
|
|
133
|
+
r = padded;
|
|
134
|
+
}
|
|
135
|
+
if (s.length < targetLen) {
|
|
136
|
+
const padded = new Uint8Array(targetLen);
|
|
137
|
+
padded.set(s, targetLen - s.length);
|
|
138
|
+
s = padded;
|
|
139
|
+
}
|
|
140
|
+
// Concatenate r || s
|
|
141
|
+
const raw = new Uint8Array(targetLen * 2);
|
|
142
|
+
raw.set(r, 0);
|
|
143
|
+
raw.set(s, targetLen);
|
|
144
|
+
return raw;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Serialize a WebCrypto ECDSA/ECDH public key to PEM (SPKI)
|
|
148
|
+
*/
|
|
149
|
+
export async function serializePublicKeyPem(publicKey) {
|
|
150
|
+
const spkiBytes = await crypto.subtle.exportKey('spki', publicKey);
|
|
151
|
+
const spkiArray = new Uint8Array(spkiBytes);
|
|
152
|
+
const b64 = toB64(spkiArray);
|
|
153
|
+
const lines = b64.match(/.{1,64}/g) || [];
|
|
154
|
+
const body = lines.join('\r\n');
|
|
155
|
+
return `-----BEGIN PUBLIC KEY-----\r\n${body}\r\n-----END PUBLIC KEY-----\r\n`;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Deserialize PEM (SPKI) public key string to Uint8Array bytes
|
|
159
|
+
*/
|
|
160
|
+
export function deserializePublicKeyPem(pem) {
|
|
161
|
+
const b64 = pem
|
|
162
|
+
.replace('-----BEGIN PUBLIC KEY-----', '')
|
|
163
|
+
.replace('-----END PUBLIC KEY-----', '')
|
|
164
|
+
.replace(/\s/g, '');
|
|
165
|
+
const binaryString = atob(b64);
|
|
166
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
167
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
168
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
169
|
+
}
|
|
170
|
+
return bytes;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Derive a shared key using ECDH + HKDF (SHA-256) from local private key and server public key (SPKI)
|
|
174
|
+
* Matches the Rust implementation detail (using only X coordinate for HKDF input).
|
|
175
|
+
*/
|
|
176
|
+
export async function deriveSharedKey(localPrivateKey, serverPublicKeySpki) {
|
|
177
|
+
const serverPublicKey = await crypto.subtle.importKey('spki', serverPublicKeySpki.slice().buffer, { name: 'ECDH', namedCurve: 'P-384' }, false, []);
|
|
178
|
+
const sharedSecret = await crypto.subtle.deriveBits({ name: 'ECDH', public: serverPublicKey }, localPrivateKey, 384);
|
|
179
|
+
const sharedSecretBytes = new Uint8Array(sharedSecret);
|
|
180
|
+
// Use X coordinate only (48 bytes for P-384)
|
|
181
|
+
const xCoordinate = sharedSecretBytes.length === 48 ? sharedSecretBytes : sharedSecretBytes.slice(1, 49);
|
|
182
|
+
const hkdfKey = await crypto.subtle.importKey('raw', xCoordinate, 'HKDF', false, ['deriveBits']);
|
|
183
|
+
const derivedKey = await crypto.subtle.deriveBits({
|
|
184
|
+
name: 'HKDF',
|
|
185
|
+
hash: 'SHA-256',
|
|
186
|
+
salt: new Uint8Array(32), // 32 zero bytes for SHA-256
|
|
187
|
+
info: new TextEncoder().encode('handshake data'),
|
|
188
|
+
}, hkdfKey, 256);
|
|
189
|
+
return new Uint8Array(derivedKey);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Encrypt and sign a message using AES-GCM and ECDSA (moved from streaming-client.ts)
|
|
193
|
+
*/
|
|
194
|
+
export async function encryptAndSign(plaintext, sharedKey, signingKey, nonce) {
|
|
195
|
+
const plaintextBytes = new TextEncoder().encode(plaintext);
|
|
196
|
+
const iv = new Uint8Array(12);
|
|
197
|
+
crypto.getRandomValues(iv);
|
|
198
|
+
const aesKey = await crypto.subtle.importKey('raw', sharedKey.slice().buffer, { name: 'AES-GCM' }, false, ['encrypt']);
|
|
199
|
+
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintextBytes);
|
|
200
|
+
const ciphertextArray = new Uint8Array(ciphertext);
|
|
201
|
+
const nonceBytes = new Uint8Array(8);
|
|
202
|
+
const view = new DataView(nonceBytes.buffer);
|
|
203
|
+
view.setBigUint64(0, BigInt(nonce), false);
|
|
204
|
+
const dataToSign = new Uint8Array(nonceBytes.length + iv.length + ciphertextArray.length);
|
|
205
|
+
dataToSign.set(nonceBytes, 0);
|
|
206
|
+
dataToSign.set(iv, nonceBytes.length);
|
|
207
|
+
dataToSign.set(ciphertextArray, nonceBytes.length + iv.length);
|
|
208
|
+
const rawSignature = new Uint8Array(await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, signingKey, dataToSign));
|
|
209
|
+
// Convert to DER format if needed
|
|
210
|
+
let signature;
|
|
211
|
+
if (rawSignature[0] === 0x30) {
|
|
212
|
+
signature = rawSignature;
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
signature = ecdsaRawToDer(rawSignature);
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
nonce,
|
|
219
|
+
iv: toB64(iv),
|
|
220
|
+
ciphertext: toB64(ciphertextArray),
|
|
221
|
+
signature: toB64(signature)
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Decrypt and verify a message using AES-GCM and ECDSA (moved from streaming-client.ts)
|
|
226
|
+
*/
|
|
227
|
+
export async function decryptAndVerify(payload, sharedKey, serverVerifyingKeySpki) {
|
|
228
|
+
const iv = new Uint8Array(Array.from(atob(payload.iv), c => c.charCodeAt(0)));
|
|
229
|
+
const ciphertext = new Uint8Array(Array.from(atob(payload.ciphertext), c => c.charCodeAt(0)));
|
|
230
|
+
const signatureBytes = new Uint8Array(Array.from(atob(payload.signature), c => c.charCodeAt(0)));
|
|
231
|
+
const nonceBytes = new Uint8Array(8);
|
|
232
|
+
const view = new DataView(nonceBytes.buffer);
|
|
233
|
+
view.setBigUint64(0, BigInt(payload.nonce), false);
|
|
234
|
+
const dataToVerify = new Uint8Array(nonceBytes.length + iv.length + ciphertext.length);
|
|
235
|
+
dataToVerify.set(nonceBytes, 0);
|
|
236
|
+
dataToVerify.set(iv, nonceBytes.length);
|
|
237
|
+
dataToVerify.set(ciphertext, nonceBytes.length + iv.length);
|
|
238
|
+
const serverVerifyingKey = await crypto.subtle.importKey('spki', serverVerifyingKeySpki.slice().buffer, { name: 'ECDSA', namedCurve: 'P-384' }, false, ['verify']);
|
|
239
|
+
// Convert DER signature to raw format for WebCrypto verification
|
|
240
|
+
let rawSignature;
|
|
241
|
+
if (signatureBytes[0] === 0x30) {
|
|
242
|
+
// DER format, convert to raw
|
|
243
|
+
rawSignature = ecdsaDerToRaw(signatureBytes);
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
// Already raw format
|
|
247
|
+
rawSignature = signatureBytes;
|
|
248
|
+
}
|
|
249
|
+
const isValid = await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, serverVerifyingKey, rawSignature, dataToVerify);
|
|
250
|
+
if (!isValid) {
|
|
251
|
+
throw new Error('Response signature verification failed');
|
|
252
|
+
}
|
|
253
|
+
const aesKey = await crypto.subtle.importKey('raw', sharedKey.slice().buffer, { name: 'AES-GCM' }, false, ['decrypt']);
|
|
254
|
+
const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, ciphertext);
|
|
255
|
+
return new TextDecoder().decode(plaintext);
|
|
256
|
+
}
|
|
257
|
+
//# sourceMappingURL=crypto-utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crypto-utils.js","sourceRoot":"","sources":["../../../src/encrypt/crypto-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAQH;;GAEG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,EAAc,EAAU,EAAE;IAC9C,8EAA8E;IAC9E,IAAI,EAAE,CAAC,MAAM,GAAG,IAAI,EAAE,CAAC;QACrB,IAAI,MAAM,GAAG,EAAE,CAAC;QAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC;YACzC,MAAM,KAAK,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACpC,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QAC/D,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IACD,OAAO,IAAI,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1C,KAAK,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,CAAC,SAAS,CAAC,CACzE,CAAC;IAEF,MAAM,SAAS,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,OAAO,CAC3C,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,UAAU,CAC5C,CAAC;IAEF,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2025 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*/
|
|
6
|
+
interface ChatMessage {
|
|
7
|
+
role: 'system' | 'user' | 'assistant';
|
|
8
|
+
content: string;
|
|
9
|
+
image_url?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Configuration for history management
|
|
13
|
+
*/
|
|
14
|
+
export declare const HISTORY_CONFIG: {
|
|
15
|
+
maxHistoryBytes: number;
|
|
16
|
+
minMessagesToKeep: number;
|
|
17
|
+
maxMessagesToKeep: number;
|
|
18
|
+
truncationMarker: string;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Truncate history to fit within size limits while preserving context
|
|
22
|
+
*
|
|
23
|
+
* Strategy:
|
|
24
|
+
* 1. Always keep system message (if present)
|
|
25
|
+
* 2. Always keep the most recent messages
|
|
26
|
+
* 3. Truncate older messages if total size exceeds limit
|
|
27
|
+
* 4. Add truncation marker to indicate removed content
|
|
28
|
+
*/
|
|
29
|
+
export declare function truncateHistory(history: ChatMessage[]): ChatMessage[];
|
|
30
|
+
/**
|
|
31
|
+
* Summarize truncated content for logging/debugging
|
|
32
|
+
*/
|
|
33
|
+
export declare function getHistorySummary(original: ChatMessage[], truncated: ChatMessage[]): string;
|
|
34
|
+
/**
|
|
35
|
+
* Get the size of a message array in bytes (for payload size monitoring)
|
|
36
|
+
*/
|
|
37
|
+
export declare function getPayloadSize(messages: ChatMessage[]): number;
|
|
38
|
+
/**
|
|
39
|
+
* Aggressively truncate to fit within a specific byte limit
|
|
40
|
+
* Used for retry logic when 413 errors occur
|
|
41
|
+
*/
|
|
42
|
+
export declare function truncateToSize(messages: ChatMessage[], maxBytes: number): ChatMessage[];
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2025 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for history management
|
|
8
|
+
*/
|
|
9
|
+
export const HISTORY_CONFIG = {
|
|
10
|
+
// Maximum size of history in bytes before truncation
|
|
11
|
+
// VERY aggressive limit accounting for encryption overhead (~33%) and multiple keys
|
|
12
|
+
// 100KB plaintext → ~133KB encrypted → ~400KB with 3 keys
|
|
13
|
+
maxHistoryBytes: 100_000, // 100KB - extremely conservative
|
|
14
|
+
// Minimum number of messages to keep (system + recent exchanges)
|
|
15
|
+
minMessagesToKeep: 3, // system + 1 recent exchange
|
|
16
|
+
// Maximum number of messages to keep
|
|
17
|
+
maxMessagesToKeep: 6, // Very aggressive limit
|
|
18
|
+
// Truncation marker
|
|
19
|
+
truncationMarker: '[... earlier conversation truncated to reduce payload size ...]'
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Calculate the approximate size of a message in bytes
|
|
23
|
+
*/
|
|
24
|
+
function getMessageSize(message) {
|
|
25
|
+
const contentSize = new TextEncoder().encode(message.content).length;
|
|
26
|
+
const imageSize = message.image_url
|
|
27
|
+
? new TextEncoder().encode(message.image_url).length
|
|
28
|
+
: 0;
|
|
29
|
+
return contentSize + imageSize + 50; // +50 for JSON overhead
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Calculate total size of message history
|
|
33
|
+
*/
|
|
34
|
+
function getTotalHistorySize(history) {
|
|
35
|
+
return history.reduce((total, msg) => total + getMessageSize(msg), 0);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Truncate history to fit within size limits while preserving context
|
|
39
|
+
*
|
|
40
|
+
* Strategy:
|
|
41
|
+
* 1. Always keep system message (if present)
|
|
42
|
+
* 2. Always keep the most recent messages
|
|
43
|
+
* 3. Truncate older messages if total size exceeds limit
|
|
44
|
+
* 4. Add truncation marker to indicate removed content
|
|
45
|
+
*/
|
|
46
|
+
export function truncateHistory(history) {
|
|
47
|
+
if (history.length === 0) {
|
|
48
|
+
return history;
|
|
49
|
+
}
|
|
50
|
+
const totalSize = getTotalHistorySize(history);
|
|
51
|
+
// If under limit, return as-is
|
|
52
|
+
if (totalSize <= HISTORY_CONFIG.maxHistoryBytes &&
|
|
53
|
+
history.length <= HISTORY_CONFIG.maxMessagesToKeep) {
|
|
54
|
+
return history;
|
|
55
|
+
}
|
|
56
|
+
// Separate system message from conversation
|
|
57
|
+
const systemMessage = history.find(msg => msg.role === 'system');
|
|
58
|
+
const conversationMessages = history.filter(msg => msg.role !== 'system');
|
|
59
|
+
// Always keep minimum recent messages
|
|
60
|
+
const recentMessages = conversationMessages.slice(-HISTORY_CONFIG.minMessagesToKeep);
|
|
61
|
+
// Build truncated history
|
|
62
|
+
const truncatedHistory = [];
|
|
63
|
+
// Add system message first
|
|
64
|
+
if (systemMessage) {
|
|
65
|
+
truncatedHistory.push(systemMessage);
|
|
66
|
+
}
|
|
67
|
+
// Calculate size so far
|
|
68
|
+
let currentSize = getTotalHistorySize(truncatedHistory);
|
|
69
|
+
const recentSize = getTotalHistorySize(recentMessages);
|
|
70
|
+
// Check if we need to add older messages
|
|
71
|
+
const remainingBudget = HISTORY_CONFIG.maxHistoryBytes - currentSize - recentSize;
|
|
72
|
+
if (remainingBudget > 1000 && conversationMessages.length > HISTORY_CONFIG.minMessagesToKeep) {
|
|
73
|
+
// Try to include some older messages within budget
|
|
74
|
+
const olderMessages = conversationMessages.slice(0, -HISTORY_CONFIG.minMessagesToKeep);
|
|
75
|
+
const includedOlder = [];
|
|
76
|
+
// Add older messages from most recent backwards until budget exhausted
|
|
77
|
+
for (let i = olderMessages.length - 1; i >= 0; i--) {
|
|
78
|
+
const msgSize = getMessageSize(olderMessages[i]);
|
|
79
|
+
if (currentSize + msgSize <= HISTORY_CONFIG.maxHistoryBytes - recentSize) {
|
|
80
|
+
includedOlder.unshift(olderMessages[i]);
|
|
81
|
+
currentSize += msgSize;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// If we truncated any messages, add marker
|
|
88
|
+
if (includedOlder.length < olderMessages.length) {
|
|
89
|
+
truncatedHistory.push({
|
|
90
|
+
role: 'assistant',
|
|
91
|
+
content: HISTORY_CONFIG.truncationMarker
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
truncatedHistory.push(...includedOlder);
|
|
95
|
+
}
|
|
96
|
+
else if (conversationMessages.length > HISTORY_CONFIG.minMessagesToKeep) {
|
|
97
|
+
// No budget for older messages, just add truncation marker
|
|
98
|
+
truncatedHistory.push({
|
|
99
|
+
role: 'assistant',
|
|
100
|
+
content: HISTORY_CONFIG.truncationMarker
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
// Add recent messages
|
|
104
|
+
truncatedHistory.push(...recentMessages);
|
|
105
|
+
return truncatedHistory;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Summarize truncated content for logging/debugging
|
|
109
|
+
*/
|
|
110
|
+
export function getHistorySummary(original, truncated) {
|
|
111
|
+
const originalSize = getTotalHistorySize(original);
|
|
112
|
+
const truncatedSize = getTotalHistorySize(truncated);
|
|
113
|
+
const savedBytes = originalSize - truncatedSize;
|
|
114
|
+
const savedPercent = ((savedBytes / originalSize) * 100).toFixed(1);
|
|
115
|
+
return `History truncated: ${original.length} → ${truncated.length} messages, ` +
|
|
116
|
+
`${(originalSize / 1024).toFixed(1)}KB → ${(truncatedSize / 1024).toFixed(1)}KB ` +
|
|
117
|
+
`(saved ${savedPercent}%)`;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Get the size of a message array in bytes (for payload size monitoring)
|
|
121
|
+
*/
|
|
122
|
+
export function getPayloadSize(messages) {
|
|
123
|
+
const json = JSON.stringify(messages);
|
|
124
|
+
return new TextEncoder().encode(json).length;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Aggressively truncate to fit within a specific byte limit
|
|
128
|
+
* Used for retry logic when 413 errors occur
|
|
129
|
+
*/
|
|
130
|
+
export function truncateToSize(messages, maxBytes) {
|
|
131
|
+
if (getPayloadSize(messages) <= maxBytes) {
|
|
132
|
+
return messages;
|
|
133
|
+
}
|
|
134
|
+
// Separate system message from conversation
|
|
135
|
+
const systemMessage = messages.find(msg => msg.role === 'system');
|
|
136
|
+
const conversationMessages = messages.filter(msg => msg.role !== 'system');
|
|
137
|
+
// Start with just system message + last 2 messages
|
|
138
|
+
let truncated = systemMessage ? [systemMessage] : [];
|
|
139
|
+
const recentMessages = conversationMessages.slice(-2);
|
|
140
|
+
truncated.push(...recentMessages);
|
|
141
|
+
// If still too large, try just system + last message
|
|
142
|
+
if (getPayloadSize(truncated) > maxBytes && conversationMessages.length > 0) {
|
|
143
|
+
truncated = systemMessage ? [systemMessage] : [];
|
|
144
|
+
truncated.push(conversationMessages[conversationMessages.length - 1]);
|
|
145
|
+
}
|
|
146
|
+
// If STILL too large, truncate the system message itself
|
|
147
|
+
if (getPayloadSize(truncated) > maxBytes && systemMessage) {
|
|
148
|
+
const systemSize = getMessageSize(systemMessage);
|
|
149
|
+
if (systemSize > maxBytes * 0.7) {
|
|
150
|
+
// System message is too large - truncate it
|
|
151
|
+
const truncatedSystem = {
|
|
152
|
+
...systemMessage,
|
|
153
|
+
content: systemMessage.content.substring(0, Math.floor(maxBytes * 0.5)) +
|
|
154
|
+
'\n\n[... system prompt truncated due to size constraints ...]'
|
|
155
|
+
};
|
|
156
|
+
truncated = [truncatedSystem];
|
|
157
|
+
if (conversationMessages.length > 0) {
|
|
158
|
+
truncated.push(conversationMessages[conversationMessages.length - 1]);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return truncated;
|
|
163
|
+
}
|
|
164
|
+
//# sourceMappingURL=history-manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"history-manager.js","sourceRoot":"","sources":["../../../src/encrypt/history-manager.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAQH;;GAEG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,qDAAqD;IACrD,oFAAoF;IACpF,0DAA0D;IAC1D,eAAe,EAAE,OAAO,EAAE,iCAAiC;IAE3D,iEAAiE;IACjE,iBAAiB,EAAE,CAAC,EAAE,6BAA6B;IAEnD,qCAAqC;IACrC,iBAAiB,EAAE,CAAC,EAAE,wBAAwB;IAE9C,oBAAoB;IACpB,gBAAgB,EAAE,iEAAiE;CACpF,CAAC;AAEF;;GAEG;AACH,SAAS,cAAc,CAAC,OAAoB;IAC1C,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC;IACrE,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS;QACjC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,MAAM;QACpD,CAAC,CAAC,CAAC,CAAC;IACN,OAAO,WAAW,GAAG,SAAS,GAAG,EAAE,CAAC,CAAC,wBAAwB;AAC/D,CAAC;AAED;;GAEG;AACH,SAAS,mBAAmB,CAAC,OAAsB;IACjD,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,G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
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2025 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*/
|
|
6
|
+
import type { FunctionDeclaration } from '@google/genai';
|
|
7
|
+
export interface MiniMaxMessage {
|
|
8
|
+
role: 'system' | 'user' | 'assistant' | 'tool';
|
|
9
|
+
content: string;
|
|
10
|
+
tool_calls?: Array<{
|
|
11
|
+
name: string;
|
|
12
|
+
arguments: Record<string, unknown>;
|
|
13
|
+
}>;
|
|
14
|
+
reasoning_content?: string;
|
|
15
|
+
current_date?: string;
|
|
16
|
+
current_location?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface MiniMaxSystemMessage {
|
|
19
|
+
content?: string;
|
|
20
|
+
current_date?: string;
|
|
21
|
+
current_location?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* MiniMax template implementation based on the provided Jinja template
|
|
25
|
+
*/
|
|
26
|
+
export declare class MiniMaxTemplate {
|
|
27
|
+
private readonly toolcallBeginToken;
|
|
28
|
+
private readonly toolcallEndToken;
|
|
29
|
+
private readonly modelIdentity;
|
|
30
|
+
/**
|
|
31
|
+
* Render tools for MiniMax format
|
|
32
|
+
*/
|
|
33
|
+
private renderToolNamespace;
|
|
34
|
+
/**
|
|
35
|
+
* Extract visible text from content (handles both string and array formats)
|
|
36
|
+
*/
|
|
37
|
+
private visibleText;
|
|
38
|
+
/**
|
|
39
|
+
* Build system message with model identity and optional date/location
|
|
40
|
+
*/
|
|
41
|
+
private buildSystemMessage;
|
|
42
|
+
/**
|
|
43
|
+
* Format tools for system prompt in MiniMax format
|
|
44
|
+
*/
|
|
45
|
+
formatToolsForSystemPrompt(tools: FunctionDeclaration[]): string;
|
|
46
|
+
/**
|
|
47
|
+
* Apply MiniMax chat template to messages
|
|
48
|
+
*/
|
|
49
|
+
applyTemplate(messages: MiniMaxMessage[], tools?: FunctionDeclaration[], systemMessage?: MiniMaxSystemMessage, addGenerationPrompt?: boolean): string;
|
|
50
|
+
/**
|
|
51
|
+
* Parse tool calls from MiniMax format response
|
|
52
|
+
*/
|
|
53
|
+
parseToolCalls(text: string): Array<{
|
|
54
|
+
name: string;
|
|
55
|
+
arguments: Record<string, unknown>;
|
|
56
|
+
}>;
|
|
57
|
+
/**
|
|
58
|
+
* Remove tool call markup from text
|
|
59
|
+
*/
|
|
60
|
+
removeToolCallMarkup(text: string): string;
|
|
61
|
+
/**
|
|
62
|
+
* Check if text contains MiniMax tool calls
|
|
63
|
+
*/
|
|
64
|
+
hasToolCalls(text: string): boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Escape regex special characters
|
|
67
|
+
*/
|
|
68
|
+
private escapeRegex;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Factory function to create MiniMax template instance
|
|
72
|
+
*/
|
|
73
|
+
export declare function createMiniMaxTemplate(): MiniMaxTemplate;
|