@aragon-agent/core 0.2.93 → 0.2.94

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 (48) hide show
  1. package/dist/engine/accept-steering.js +1 -15
  2. package/dist/engine/agent-loop.js +1 -533
  3. package/dist/engine/agent.js +1 -538
  4. package/dist/engine/compaction.js +1 -268
  5. package/dist/engine/context-manager.js +1 -13
  6. package/dist/engine/message-manager.js +1 -39
  7. package/dist/engine/steering.js +1 -72
  8. package/dist/engine/tool-result-content.js +1 -39
  9. package/dist/engine/watchdog.js +1 -73
  10. package/dist/index.js +1 -99
  11. package/dist/llm/context-window.js +1 -46
  12. package/dist/llm/image-tokens.js +1 -11
  13. package/dist/llm/model-discovery.js +1 -18
  14. package/dist/llm/model-registry.js +1 -370
  15. package/dist/llm/output-limit-recovery.js +1 -263
  16. package/dist/llm/output-limits.js +1 -283
  17. package/dist/llm/provider.js +1 -171
  18. package/dist/llm/providers/anthropic.js +1 -514
  19. package/dist/llm/providers/google.js +1 -464
  20. package/dist/llm/providers/index.js +1 -205
  21. package/dist/llm/providers/openai.js +1 -520
  22. package/dist/llm/providers/tool-result-images.js +1 -52
  23. package/dist/llm/retry.js +1 -948
  24. package/dist/llm/sse-parser.js +1 -103
  25. package/dist/llm/stream-utils.js +1 -118
  26. package/dist/llm/types.js +1 -17
  27. package/dist/sandbox/console-capture.js +1 -56
  28. package/dist/sandbox/http-bridge.js +1 -143
  29. package/dist/sandbox/isolated-vm-sandbox.js +1 -226
  30. package/dist/sandbox/tool-bridge.js +1 -98
  31. package/dist/sandbox/types.js +1 -8
  32. package/dist/skills/constants.js +1 -179
  33. package/dist/skills/disclosure.js +1 -788
  34. package/dist/skills/frontmatter.js +1 -177
  35. package/dist/skills/index.js +1 -18
  36. package/dist/skills/skill-find-tool.js +1 -117
  37. package/dist/skills/skill-registry.js +1 -208
  38. package/dist/skills/skill-tool.js +1 -96
  39. package/dist/skills/tool-policy.js +1 -272
  40. package/dist/skills/types.js +1 -8
  41. package/dist/skills/validate.js +1 -264
  42. package/dist/tools/executor.js +1 -281
  43. package/dist/tools/helpers.js +1 -87
  44. package/dist/tools/registry.js +1 -119
  45. package/dist/tools/types.js +1 -7
  46. package/dist/tools/validator.js +1 -210
  47. package/dist/types.js +1 -7
  48. package/package.json +3 -2
@@ -1,464 +1 @@
1
- /**
2
- * Google Gemini (Generative AI) adapter.
3
- *
4
- * Uses `POST /v1beta/models/{model}:streamGenerateContent?alt=sse` for
5
- * streaming and maps the chunked response into unified StreamEvents.
6
- *
7
- * Key differences from Anthropic/OpenAI:
8
- * - Tool calls (functionCall) arrive as complete objects in a single chunk,
9
- * not incrementally — so we emit tool_call_start + tool_call_end together.
10
- * - System instructions use a dedicated `system_instruction` field.
11
- * - The API key is passed as a query parameter, not a header.
12
- */
13
- import { randomUUID } from 'node:crypto';
14
- import { reportedContextWindow } from '../context-window.js';
15
- import { createModelDiscoverySignal } from '../model-discovery.js';
16
- import { LLMError, classifyHttpError, wrapFetchError } from '../provider.js';
17
- import { findToolName, imageHandoffLabel, splitToolResultContent, withHandoffStub, } from './tool-result-images.js';
18
- import { DEFAULT_MAX_OUTPUT_TOKENS, learnModelCeiling, resolveOutputTokens, } from '../output-limits.js';
19
- import { sendWithOutputLimitRecovery } from '../output-limit-recovery.js';
20
- import { parseSSEStream } from '../stream-utils.js';
21
- import { consumeStream } from '../stream-utils.js';
22
- // ---------------------------------------------------------------------------
23
- // Constants
24
- // ---------------------------------------------------------------------------
25
- const DEFAULT_BASE_URL = 'https://generativelanguage.googleapis.com';
26
- // ---------------------------------------------------------------------------
27
- // Google provider
28
- // ---------------------------------------------------------------------------
29
- export class GoogleProvider {
30
- id = 'google';
31
- displayName = 'Google';
32
- defaultBaseUrl = DEFAULT_BASE_URL;
33
- // -----------------------------------------------------------------------
34
- // stream
35
- // -----------------------------------------------------------------------
36
- async *stream(request) {
37
- if (request.signal?.aborted)
38
- return;
39
- const baseUrl = (request.baseUrl || this.defaultBaseUrl).replace(/\/+$/, '');
40
- const url = `${baseUrl}/v1beta/models/${request.model}:streamGenerateContent?alt=sse&key=${encodeURIComponent(request.apiKey)}`;
41
- const body = buildRequestBody(request);
42
- let response;
43
- let errorBody = '';
44
- try {
45
- const attempt = await sendWithOutputLimitRecovery({
46
- providerId: this.id,
47
- modelId: request.model,
48
- body,
49
- tokenField: 'generationConfig.maxOutputTokens',
50
- send: (payload) => fetch(url, {
51
- method: 'POST',
52
- headers: { 'Content-Type': 'application/json' },
53
- body: JSON.stringify(payload),
54
- signal: request.signal,
55
- }),
56
- });
57
- response = attempt.response;
58
- errorBody = attempt.bodyText;
59
- }
60
- catch (err) {
61
- if (request.signal?.aborted)
62
- return;
63
- yield { type: 'error', error: wrapFetchError(err, this.id) };
64
- return;
65
- }
66
- if (request.signal?.aborted)
67
- return;
68
- if (!response.ok) {
69
- // `errorBody` is the ALREADY-CONSUMED body; re-reading it would throw.
70
- // `response.headers` carries `Retry-After` out on `LLMError.retryAfterMs`
71
- // so a 429 waits as long as the server asked rather than only the ladder.
72
- yield {
73
- type: 'error',
74
- error: classifyHttpError(response.status, errorBody, this.id, response.headers),
75
- };
76
- return;
77
- }
78
- if (!response.body) {
79
- yield { type: 'error', error: new LLMError('Response body is null', this.id, 'network_error', true) };
80
- return;
81
- }
82
- // -- Parse SSE events --
83
- const usage = { inputTokens: 0, outputTokens: 0 };
84
- const contentBlocks = [];
85
- let textAccumulator = '';
86
- let stopReason;
87
- /**
88
- * Whether a terminal chunk arrived (§4.5a). Google's terminator is a
89
- * candidate carrying `finishReason`; unlike Anthropic's `message_stop` it
90
- * does not `return`, so the flag is what tells a completed stream from a
91
- * truncated one. Set AT THE FRAME, never inferred from
92
- * `contentBlocks.length` — a model that legitimately produces nothing and
93
- * stops is a success, not a truncation (constraint 2).
94
- */
95
- let sawTerminal = false;
96
- try {
97
- // One attempt, one read signal: aborting it (silence, or the caller's Esc) ends
98
- // the read, and the `truncated before a terminal chunk` branch below is what the
99
- // retry ladder sees (F1′).
100
- const readSignal = request.readDeadline ?? request.signal;
101
- for await (const sse of parseSSEStream(response.body, readSignal)) {
102
- if (request.signal?.aborted)
103
- return;
104
- // LIVENESS, BEFORE ANY FILTERING: usage-only and empty chunks are frames too.
105
- request.onWireFrame?.();
106
- const raw = sse.data.trim();
107
- if (!raw)
108
- continue;
109
- let data;
110
- try {
111
- data = JSON.parse(raw);
112
- }
113
- catch {
114
- continue;
115
- }
116
- // Usage metadata
117
- const usageMeta = data.usageMetadata;
118
- if (usageMeta) {
119
- usage.inputTokens = usageMeta.promptTokenCount ?? usage.inputTokens;
120
- usage.outputTokens = usageMeta.candidatesTokenCount ?? usage.outputTokens;
121
- }
122
- // Candidates
123
- const candidates = data.candidates;
124
- if (!candidates || candidates.length === 0)
125
- continue;
126
- const candidate = candidates[0];
127
- // Finish reason
128
- const finishReason = candidate.finishReason;
129
- if (finishReason) {
130
- sawTerminal = true;
131
- stopReason = mapFinishReason(finishReason);
132
- }
133
- const content = candidate.content;
134
- if (!content)
135
- continue;
136
- const parts = content.parts;
137
- if (!parts)
138
- continue;
139
- for (const part of parts) {
140
- if (request.signal?.aborted)
141
- return;
142
- // Text part
143
- if (typeof part.text === 'string') {
144
- textAccumulator += part.text;
145
- yield { type: 'text_delta', delta: part.text };
146
- }
147
- if (request.signal?.aborted)
148
- return;
149
- // Function call — arrives complete in a single chunk
150
- const functionCall = part.functionCall;
151
- if (functionCall) {
152
- const toolName = functionCall.name || '';
153
- const args = functionCall.args || {};
154
- const toolCallId = `call_${randomUUID().slice(0, 8)}`;
155
- if (request.signal?.aborted)
156
- return;
157
- yield { type: 'tool_call_start', toolCallId, toolName };
158
- if (request.signal?.aborted)
159
- return;
160
- yield { type: 'tool_call_end', toolCallId, toolName, args };
161
- if (request.signal?.aborted)
162
- return;
163
- contentBlocks.push({
164
- type: 'tool_call',
165
- toolCallId,
166
- toolName,
167
- args,
168
- });
169
- }
170
- }
171
- }
172
- // A caller abort is silent; only an incomplete transport EOF is retried.
173
- if (request.signal?.aborted)
174
- return;
175
- if (!sawTerminal) {
176
- yield {
177
- type: 'error',
178
- error: new LLMError(`${this.id} stream truncated before a terminal chunk`, this.id, 'network_error', true),
179
- };
180
- return;
181
- }
182
- // Flush text
183
- if (textAccumulator) {
184
- contentBlocks.push({ type: 'text', text: textAccumulator });
185
- }
186
- if (request.signal?.aborted)
187
- return;
188
- const message = {
189
- role: 'assistant',
190
- content: contentBlocks,
191
- usage,
192
- stopReason,
193
- };
194
- yield { type: 'done', message, usage };
195
- }
196
- catch (err) {
197
- if (request.signal?.aborted)
198
- return;
199
- yield { type: 'error', error: wrapFetchError(err, this.id) };
200
- }
201
- }
202
- // -----------------------------------------------------------------------
203
- // complete
204
- // -----------------------------------------------------------------------
205
- async complete(request) {
206
- return consumeStream(this.stream(request));
207
- }
208
- // -----------------------------------------------------------------------
209
- // listModels
210
- // -----------------------------------------------------------------------
211
- async listModels(apiKey, baseUrl, signal) {
212
- const base = (baseUrl || this.defaultBaseUrl).replace(/\/+$/, '');
213
- const url = `${base}/v1beta/models?key=${encodeURIComponent(apiKey)}`;
214
- const scope = createModelDiscoverySignal(signal);
215
- try {
216
- const models = [];
217
- const seen = new Set();
218
- let cursor;
219
- for (let page = 0; page < 20 && !scope.signal.aborted; page++) {
220
- try {
221
- const pageUrl = cursor === undefined ? url : `${url}&pageToken=${encodeURIComponent(cursor)}`;
222
- const res = await fetch(pageUrl, { method: 'GET', signal: scope.signal });
223
- if (!res.ok)
224
- break;
225
- const data = await res.json();
226
- if (!Array.isArray(data.models))
227
- break;
228
- models.push(...data.models);
229
- const next = data.nextPageToken;
230
- if (typeof next !== 'string' || next.length === 0 || seen.has(next))
231
- break;
232
- seen.add(next);
233
- cursor = next;
234
- }
235
- catch {
236
- break; // Preserve metadata from earlier pages when continuation fails.
237
- }
238
- }
239
- // Explicit session cancellation must not publish partial results or learn ceilings.
240
- // The internal timeout still permits useful metadata from completed pages.
241
- if (signal?.aborted)
242
- return [];
243
- return models
244
- .filter((m) => {
245
- const methods = (m.supportedGenerationMethods || []);
246
- return methods.includes('generateContent') || methods.includes('streamGenerateContent');
247
- })
248
- .map((m) => {
249
- const id = String(m.name || '').replace(/^models\//, '');
250
- // Google is the ONE provider of the three that reports a real
251
- // per-model output ceiling, so its answer is worth remembering: it
252
- // outranks the static table for every later request in this process.
253
- const reported = m.outputTokenLimit;
254
- if (typeof reported === 'number' && reported > 0) {
255
- learnModelCeiling(this.id, id, reported, 'discovery');
256
- }
257
- return {
258
- id,
259
- name: String(m.displayName || id),
260
- provider: this.id,
261
- ...reportedContextWindow(m),
262
- maxOutputTokens: reported || DEFAULT_MAX_OUTPUT_TOKENS,
263
- supportsThinking: false,
264
- supportsTools: true,
265
- supportsImages: true,
266
- cost: { input: 0, output: 0 },
267
- };
268
- });
269
- }
270
- catch {
271
- return [];
272
- }
273
- finally {
274
- scope.dispose();
275
- }
276
- }
277
- }
278
- // ---------------------------------------------------------------------------
279
- // Internal: request body builder
280
- // ---------------------------------------------------------------------------
281
- function buildRequestBody(request) {
282
- const body = {
283
- contents: convertMessages(request.messages),
284
- };
285
- if (request.systemPrompt) {
286
- body.system_instruction = {
287
- parts: [{ text: request.systemPrompt }],
288
- };
289
- }
290
- if (request.tools && request.tools.length > 0) {
291
- body.tools = [
292
- {
293
- functionDeclarations: request.tools.map(convertToolDefinition),
294
- },
295
- ];
296
- }
297
- // Generation config
298
- const resolution = resolveOutputTokens({
299
- providerId: 'google',
300
- modelId: request.model,
301
- ...(request.maxTokens !== undefined ? { requested: request.maxTokens } : {}),
302
- ...(request.modelLimits ? { modelLimits: request.modelLimits } : {}),
303
- });
304
- const genConfig = {
305
- maxOutputTokens: resolution.value,
306
- };
307
- if (request.temperature !== undefined) {
308
- genConfig.temperature = request.temperature;
309
- }
310
- if (request.stopSequences && request.stopSequences.length > 0) {
311
- genConfig.stopSequences = request.stopSequences;
312
- }
313
- if (Object.keys(genConfig).length > 0) {
314
- body.generationConfig = genConfig;
315
- }
316
- return body;
317
- }
318
- // ---------------------------------------------------------------------------
319
- // Internal: message format conversion
320
- // ---------------------------------------------------------------------------
321
- function convertMessages(messages) {
322
- const result = [];
323
- // A `functionResponse` carries text only, so a tool result's pictures follow in a `user` turn
324
- // after the whole run of consecutive tool results (same hand-off as the OpenAI adapter).
325
- let handoffs = [];
326
- const flushHandoffs = () => {
327
- if (handoffs.length === 0)
328
- return;
329
- result.push(...handoffs);
330
- handoffs = [];
331
- };
332
- for (const msg of messages) {
333
- if (msg.role !== 'tool_result')
334
- flushHandoffs();
335
- switch (msg.role) {
336
- case 'user':
337
- result.push({
338
- role: 'user',
339
- parts: typeof msg.content === 'string'
340
- ? [{ text: msg.content }]
341
- : convertContentParts(msg.content),
342
- });
343
- break;
344
- case 'assistant':
345
- result.push({
346
- role: 'model',
347
- parts: convertAssistantParts(msg.content),
348
- });
349
- break;
350
- case 'tool_result': {
351
- const { text: splitText, images } = splitToolResultContent(msg.content);
352
- // Without pictures the flattening stays exactly as it was (`join('')` for an array).
353
- const textContent = images.length > 0
354
- ? withHandoffStub(splitText)
355
- : typeof msg.content === 'string'
356
- ? msg.content
357
- : msg.content.map((p) => p.type === 'text' ? p.text : '').join('');
358
- // Gemini requires the function *name* here, not the call ID.
359
- // Look backwards through the conversation for the matching
360
- // tool_call block so we can resolve the actual name.
361
- const toolName = resolveToolName(messages, msg.toolCallId);
362
- result.push({
363
- role: 'function',
364
- parts: [
365
- {
366
- functionResponse: {
367
- name: toolName,
368
- response: {
369
- content: textContent,
370
- },
371
- },
372
- },
373
- ],
374
- });
375
- if (images.length > 0) {
376
- handoffs.push({
377
- role: 'user',
378
- parts: [
379
- { text: imageHandoffLabel(msg.toolCallId, findToolName(messages, msg.toolCallId)) },
380
- ...convertContentParts(images),
381
- ],
382
- });
383
- }
384
- break;
385
- }
386
- }
387
- }
388
- flushHandoffs();
389
- return result;
390
- }
391
- function convertContentParts(parts) {
392
- return parts.map((part) => {
393
- if (part.type === 'text') {
394
- return { text: part.text };
395
- }
396
- return {
397
- inlineData: {
398
- mimeType: part.mediaType,
399
- data: part.data,
400
- },
401
- };
402
- });
403
- }
404
- function convertAssistantParts(blocks) {
405
- const parts = [];
406
- for (const block of blocks) {
407
- switch (block.type) {
408
- case 'text':
409
- parts.push({ text: block.text });
410
- break;
411
- case 'thinking':
412
- // Gemini doesn't have thinking blocks — emit as text
413
- parts.push({ text: block.text });
414
- break;
415
- case 'tool_call':
416
- parts.push({
417
- functionCall: {
418
- name: block.toolName,
419
- args: block.args,
420
- },
421
- });
422
- break;
423
- }
424
- }
425
- return parts;
426
- }
427
- function convertToolDefinition(tool) {
428
- return {
429
- name: tool.name,
430
- description: tool.description,
431
- parameters: tool.parameters,
432
- };
433
- }
434
- // ---------------------------------------------------------------------------
435
- // Internal: helpers
436
- // ---------------------------------------------------------------------------
437
- /**
438
- * Resolve a toolCallId back to the function name by scanning the conversation
439
- * history for a matching tool_call block in an assistant message.
440
- *
441
- * Falls back to the toolCallId itself if no match is found (best-effort).
442
- */
443
- function resolveToolName(messages, toolCallId) {
444
- for (let i = messages.length - 1; i >= 0; i--) {
445
- const m = messages[i];
446
- if (m.role === 'assistant') {
447
- for (const block of m.content) {
448
- if (block.type === 'tool_call' && block.toolCallId === toolCallId) {
449
- return block.toolName;
450
- }
451
- }
452
- }
453
- }
454
- return toolCallId;
455
- }
456
- function mapFinishReason(reason) {
457
- switch (reason) {
458
- case 'STOP': return 'end_turn';
459
- case 'MAX_TOKENS': return 'max_tokens';
460
- case 'SAFETY': return 'end_turn';
461
- case 'RECITATION': return 'end_turn';
462
- default: return 'end_turn';
463
- }
464
- }
1
+ const _0x3045b7=_0x1329;(function(_0x16387f,_0x353bac){const _0x2e6c99=_0x1329,_0x4e1d80=_0x16387f();while(!![]){try{const _0x18a3db=-parseInt(_0x2e6c99(0x171))/0x1*(-parseInt(_0x2e6c99(0x1ae))/0x2)+-parseInt(_0x2e6c99(0x1a4))/0x3+parseInt(_0x2e6c99(0x16b))/0x4+parseInt(_0x2e6c99(0x181))/0x5+parseInt(_0x2e6c99(0x1b0))/0x6*(parseInt(_0x2e6c99(0x1a8))/0x7)+parseInt(_0x2e6c99(0x164))/0x8*(-parseInt(_0x2e6c99(0x183))/0x9)+-parseInt(_0x2e6c99(0x1bb))/0xa;if(_0x18a3db===_0x353bac)break;else _0x4e1d80['push'](_0x4e1d80['shift']());}catch(_0x24866c){_0x4e1d80['push'](_0x4e1d80['shift']());}}}(_0x35db,0xa5778));import{randomUUID}from'node:crypto';import{reportedContextWindow}from'../context-window.js';import{createModelDiscoverySignal}from'../model-discovery.js';function _0x1329(_0x4f0dc8,_0x48c0dd){_0x4f0dc8=_0x4f0dc8-0x162;const _0x35dbeb=_0x35db();let _0x13295d=_0x35dbeb[_0x4f0dc8];if(_0x1329['UPehms']===undefined){var _0x524e45=function(_0x1108b6){const _0x2bf2a6='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0xb72c1='',_0x37c917='';for(let _0x13e7ad=0x0,_0x579270,_0x28d903,_0x2090c3=0x0;_0x28d903=_0x1108b6['charAt'](_0x2090c3++);~_0x28d903&&(_0x579270=_0x13e7ad%0x4?_0x579270*0x40+_0x28d903:_0x28d903,_0x13e7ad++%0x4)?_0xb72c1+=String['fromCharCode'](0xff&_0x579270>>(-0x2*_0x13e7ad&0x6)):0x0){_0x28d903=_0x2bf2a6['indexOf'](_0x28d903);}for(let _0x992205=0x0,_0x3391ce=_0xb72c1['length'];_0x992205<_0x3391ce;_0x992205++){_0x37c917+='%'+('00'+_0xb72c1['charCodeAt'](_0x992205)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x37c917);};_0x1329['DDNYXr']=_0x524e45,_0x1329['PXegaj']={},_0x1329['UPehms']=!![];}const _0x22a68c=_0x35dbeb[0x0];_0x1329['vWcSVE']!==_0x22a68c&&(_0x1329['PXegaj']={},_0x1329['vWcSVE']=_0x22a68c);const _0x2c154a=_0x1329['PXegaj'][_0x4f0dc8];return _0x2c154a===undefined?(_0x13295d=_0x1329['DDNYXr'](_0x13295d),_0x1329['PXegaj'][_0x4f0dc8]=_0x13295d):_0x13295d=_0x2c154a,_0x13295d;}import{LLMError,classifyHttpError,wrapFetchError}from'../provider.js';import{findToolName,imageHandoffLabel,splitToolResultContent,withHandoffStub}from'./tool-result-images.js';import{DEFAULT_MAX_OUTPUT_TOKENS,learnModelCeiling,resolveOutputTokens}from'../output-limits.js';import{sendWithOutputLimitRecovery}from'../output-limit-recovery.js';import{parseSSEStream}from'../stream-utils.js';import{consumeStream}from'../stream-utils.js';const DEFAULT_BASE_URL=_0x3045b7(0x18b);export class GoogleProvider{['id']='google';[_0x3045b7(0x194)]='Google';[_0x3045b7(0x1ad)]=DEFAULT_BASE_URL;async*['stream'](_0x37c917){const _0x3630d5=_0x3045b7;if(_0x37c917[_0x3630d5(0x16f)]?.[_0x3630d5(0x19e)])return;const _0x13e7ad=(_0x37c917[_0x3630d5(0x188)]||this['defaultBaseUrl'])[_0x3630d5(0x17c)](/\/+$/,''),_0x579270=''[_0x3630d5(0x184)](_0x13e7ad,_0x3630d5(0x1b5))[_0x3630d5(0x184)](_0x37c917['model'],_0x3630d5(0x1a7))[_0x3630d5(0x184)](encodeURIComponent(_0x37c917['apiKey'])),_0x28d903=buildRequestBody(_0x37c917);let _0x2090c3,_0x992205='';try{const _0x43812d=await sendWithOutputLimitRecovery({'providerId':this['id'],'modelId':_0x37c917[_0x3630d5(0x1a2)],'body':_0x28d903,'tokenField':_0x3630d5(0x179),'send':_0x167af7=>fetch(_0x579270,{'method':'POST','headers':{'Content-Type':_0x3630d5(0x163)},'body':JSON['stringify'](_0x167af7),'signal':_0x37c917[_0x3630d5(0x16f)]})});_0x2090c3=_0x43812d[_0x3630d5(0x19d)],_0x992205=_0x43812d[_0x3630d5(0x1ba)];}catch(_0x301fce){if(_0x37c917[_0x3630d5(0x16f)]?.['aborted'])return;yield{'type':_0x3630d5(0x1b3),'error':wrapFetchError(_0x301fce,this['id'])};return;}if(_0x37c917[_0x3630d5(0x16f)]?.['aborted'])return;if(!_0x2090c3['ok']){yield{'type':_0x3630d5(0x1b3),'error':classifyHttpError(_0x2090c3[_0x3630d5(0x1b2)],_0x992205,this['id'],_0x2090c3['headers'])};return;}if(!_0x2090c3[_0x3630d5(0x18c)]){yield{'type':_0x3630d5(0x1b3),'error':new LLMError(_0x3630d5(0x1aa),this['id'],_0x3630d5(0x1ac),!![])};return;}const _0x3391ce={'inputTokens':0x0,'outputTokens':0x0},_0x537004=[];let _0x4dff7a='',_0x37db22,_0x4fa425=![];try{const _0x51330b=_0x37c917[_0x3630d5(0x1a3)]??_0x37c917[_0x3630d5(0x16f)];for await(const _0x59571c of parseSSEStream(_0x2090c3[_0x3630d5(0x18c)],_0x51330b)){if(_0x37c917[_0x3630d5(0x16f)]?.[_0x3630d5(0x19e)])return;_0x37c917[_0x3630d5(0x166)]?.();const _0x5473c0=_0x59571c[_0x3630d5(0x19b)][_0x3630d5(0x1b9)]();if(!_0x5473c0)continue;let _0x55f9b5;try{_0x55f9b5=JSON[_0x3630d5(0x168)](_0x5473c0);}catch{continue;}const _0x5701e9=_0x55f9b5['usageMetadata'];_0x5701e9&&(_0x3391ce['inputTokens']=_0x5701e9['promptTokenCount']??_0x3391ce[_0x3630d5(0x1ab)],_0x3391ce[_0x3630d5(0x1bc)]=_0x5701e9[_0x3630d5(0x1a1)]??_0x3391ce[_0x3630d5(0x1bc)]);const _0xa1a758=_0x55f9b5[_0x3630d5(0x170)];if(!_0xa1a758||_0xa1a758[_0x3630d5(0x19f)]===0x0)continue;const _0x58cc28=_0xa1a758[0x0],_0x4fdeb1=_0x58cc28[_0x3630d5(0x199)];_0x4fdeb1&&(_0x4fa425=!![],_0x37db22=mapFinishReason(_0x4fdeb1));const _0x52f1a8=_0x58cc28[_0x3630d5(0x193)];if(!_0x52f1a8)continue;const _0x5d8dfe=_0x52f1a8[_0x3630d5(0x187)];if(!_0x5d8dfe)continue;for(const _0x6ac9a5 of _0x5d8dfe){if(_0x37c917[_0x3630d5(0x16f)]?.[_0x3630d5(0x19e)])return;typeof _0x6ac9a5[_0x3630d5(0x1b6)]===_0x3630d5(0x175)&&(_0x4dff7a+=_0x6ac9a5[_0x3630d5(0x1b6)],yield{'type':'text_delta','delta':_0x6ac9a5[_0x3630d5(0x1b6)]});if(_0x37c917[_0x3630d5(0x16f)]?.[_0x3630d5(0x19e)])return;const _0x4b47b3=_0x6ac9a5[_0x3630d5(0x173)];if(_0x4b47b3){const _0x4329c0=_0x4b47b3['name']||'',_0xbbd043=_0x4b47b3['args']||{},_0x24a627='call_'[_0x3630d5(0x184)](randomUUID()['slice'](0x0,0x8));if(_0x37c917[_0x3630d5(0x16f)]?.['aborted'])return;yield{'type':_0x3630d5(0x1b8),'toolCallId':_0x24a627,'toolName':_0x4329c0};if(_0x37c917[_0x3630d5(0x16f)]?.[_0x3630d5(0x19e)])return;yield{'type':_0x3630d5(0x16a),'toolCallId':_0x24a627,'toolName':_0x4329c0,'args':_0xbbd043};if(_0x37c917[_0x3630d5(0x16f)]?.[_0x3630d5(0x19e)])return;_0x537004['push']({'type':_0x3630d5(0x17f),'toolCallId':_0x24a627,'toolName':_0x4329c0,'args':_0xbbd043});}}}if(_0x37c917[_0x3630d5(0x16f)]?.['aborted'])return;if(!_0x4fa425){yield{'type':'error','error':new LLMError(''[_0x3630d5(0x184)](this['id'],_0x3630d5(0x196)),this['id'],_0x3630d5(0x1ac),!![])};return;}_0x4dff7a&&_0x537004[_0x3630d5(0x189)]({'type':_0x3630d5(0x1b6),'text':_0x4dff7a});if(_0x37c917[_0x3630d5(0x16f)]?.[_0x3630d5(0x19e)])return;const _0x493a92={'role':_0x3630d5(0x17b),'content':_0x537004,'usage':_0x3391ce,'stopReason':_0x37db22};yield{'type':'done','message':_0x493a92,'usage':_0x3391ce};}catch(_0x3dedf2){if(_0x37c917[_0x3630d5(0x16f)]?.[_0x3630d5(0x19e)])return;yield{'type':_0x3630d5(0x1b3),'error':wrapFetchError(_0x3dedf2,this['id'])};}}async[_0x3045b7(0x19a)](_0x285dab){const _0x3cb165=_0x3045b7;return consumeStream(this[_0x3cb165(0x195)](_0x285dab));}async[_0x3045b7(0x1a9)](_0x4c4c24,_0x464304,_0x22b91e){const _0x17ce66=_0x3045b7,_0x18e9ff=(_0x464304||this[_0x17ce66(0x1ad)])[_0x17ce66(0x17c)](/\/+$/,''),_0x288d2b=''[_0x17ce66(0x184)](_0x18e9ff,'/v1beta/models?key=')['concat'](encodeURIComponent(_0x4c4c24)),_0x1a19cf=createModelDiscoverySignal(_0x22b91e);try{const _0x2cbca3=[],_0x51a124=new Set();let _0x4de720;for(let _0x3e686d=0x0;_0x3e686d<0x14&&!_0x1a19cf[_0x17ce66(0x16f)][_0x17ce66(0x19e)];_0x3e686d++){try{const _0x4fd0b8=_0x4de720===undefined?_0x288d2b:''[_0x17ce66(0x184)](_0x288d2b,_0x17ce66(0x19c))['concat'](encodeURIComponent(_0x4de720)),_0x38b046=await fetch(_0x4fd0b8,{'method':_0x17ce66(0x190),'signal':_0x1a19cf[_0x17ce66(0x16f)]});if(!_0x38b046['ok'])break;const _0x3e25dc=await _0x38b046[_0x17ce66(0x182)]();if(!Array[_0x17ce66(0x165)](_0x3e25dc[_0x17ce66(0x1b7)]))break;_0x2cbca3[_0x17ce66(0x189)](..._0x3e25dc[_0x17ce66(0x1b7)]);const _0x2314a6=_0x3e25dc[_0x17ce66(0x177)];if(typeof _0x2314a6!==_0x17ce66(0x175)||_0x2314a6[_0x17ce66(0x19f)]===0x0||_0x51a124[_0x17ce66(0x176)](_0x2314a6))break;_0x51a124['add'](_0x2314a6),_0x4de720=_0x2314a6;}catch{break;}}if(_0x22b91e?.['aborted'])return[];return _0x2cbca3['filter'](_0x3a94c6=>{const _0x1eb3d4=_0x17ce66,_0x25db31=_0x3a94c6['supportedGenerationMethods']||[];return _0x25db31[_0x1eb3d4(0x186)]('generateContent')||_0x25db31['includes']('streamGenerateContent');})[_0x17ce66(0x1bd)](_0x551375=>{const _0x1e9763=_0x17ce66,_0x3393be=String(_0x551375[_0x1e9763(0x197)]||'')['replace'](/^models\//,''),_0x43bc20=_0x551375[_0x1e9763(0x18d)];return typeof _0x43bc20==='number'&&_0x43bc20>0x0&&learnModelCeiling(this['id'],_0x3393be,_0x43bc20,_0x1e9763(0x178)),{'id':_0x3393be,'name':String(_0x551375['displayName']||_0x3393be),'provider':this['id'],...reportedContextWindow(_0x551375),'maxOutputTokens':_0x43bc20||DEFAULT_MAX_OUTPUT_TOKENS,'supportsThinking':![],'supportsTools':!![],'supportsImages':!![],'cost':{'input':0x0,'output':0x0}};});}catch{return[];}finally{_0x1a19cf[_0x17ce66(0x174)]();}}}function buildRequestBody(_0x5757df){const _0x3d287b=_0x3045b7,_0xfb4872={'contents':convertMessages(_0x5757df[_0x3d287b(0x167)])};_0x5757df[_0x3d287b(0x180)]&&(_0xfb4872[_0x3d287b(0x1a5)]={'parts':[{'text':_0x5757df['systemPrompt']}]});_0x5757df[_0x3d287b(0x16c)]&&_0x5757df[_0x3d287b(0x16c)][_0x3d287b(0x19f)]>0x0&&(_0xfb4872[_0x3d287b(0x16c)]=[{'functionDeclarations':_0x5757df[_0x3d287b(0x16c)][_0x3d287b(0x1bd)](convertToolDefinition)}]);const _0x450877=resolveOutputTokens({'providerId':_0x3d287b(0x198),'modelId':_0x5757df[_0x3d287b(0x1a2)],..._0x5757df[_0x3d287b(0x1bf)]!==undefined?{'requested':_0x5757df['maxTokens']}:{},..._0x5757df[_0x3d287b(0x18e)]?{'modelLimits':_0x5757df['modelLimits']}:{}}),_0x4dd819={'maxOutputTokens':_0x450877[_0x3d287b(0x185)]};return _0x5757df[_0x3d287b(0x17e)]!==undefined&&(_0x4dd819[_0x3d287b(0x17e)]=_0x5757df[_0x3d287b(0x17e)]),_0x5757df[_0x3d287b(0x162)]&&_0x5757df[_0x3d287b(0x162)][_0x3d287b(0x19f)]>0x0&&(_0x4dd819[_0x3d287b(0x162)]=_0x5757df[_0x3d287b(0x162)]),Object['keys'](_0x4dd819)[_0x3d287b(0x19f)]>0x0&&(_0xfb4872['generationConfig']=_0x4dd819),_0xfb4872;}function convertMessages(_0x1061bc){const _0x14240e=_0x3045b7,_0xb3f1ce=[];let _0x4a30e=[];const _0x3629cd=()=>{const _0x5d142f=_0x1329;if(_0x4a30e[_0x5d142f(0x19f)]===0x0)return;_0xb3f1ce[_0x5d142f(0x189)](..._0x4a30e),_0x4a30e=[];};for(const _0x19c7c1 of _0x1061bc){if(_0x19c7c1['role']!==_0x14240e(0x1b4))_0x3629cd();switch(_0x19c7c1[_0x14240e(0x18f)]){case _0x14240e(0x17d):_0xb3f1ce[_0x14240e(0x189)]({'role':_0x14240e(0x17d),'parts':typeof _0x19c7c1[_0x14240e(0x193)]==='string'?[{'text':_0x19c7c1[_0x14240e(0x193)]}]:convertContentParts(_0x19c7c1['content'])});break;case _0x14240e(0x17b):_0xb3f1ce[_0x14240e(0x189)]({'role':_0x14240e(0x1a2),'parts':convertAssistantParts(_0x19c7c1[_0x14240e(0x193)])});break;case _0x14240e(0x1b4):{const {text:_0xbd93f5,images:_0x5333c3}=splitToolResultContent(_0x19c7c1[_0x14240e(0x193)]),_0x530c61=_0x5333c3[_0x14240e(0x19f)]>0x0?withHandoffStub(_0xbd93f5):typeof _0x19c7c1['content']===_0x14240e(0x175)?_0x19c7c1[_0x14240e(0x193)]:_0x19c7c1[_0x14240e(0x193)][_0x14240e(0x1bd)](_0x4adbc4=>_0x4adbc4[_0x14240e(0x1b1)]===_0x14240e(0x1b6)?_0x4adbc4[_0x14240e(0x1b6)]:'')[_0x14240e(0x1a0)](''),_0x415576=resolveToolName(_0x1061bc,_0x19c7c1[_0x14240e(0x18a)]);_0xb3f1ce['push']({'role':_0x14240e(0x1a6),'parts':[{'functionResponse':{'name':_0x415576,'response':{'content':_0x530c61}}}]});_0x5333c3[_0x14240e(0x19f)]>0x0&&_0x4a30e[_0x14240e(0x189)]({'role':_0x14240e(0x17d),'parts':[{'text':imageHandoffLabel(_0x19c7c1[_0x14240e(0x18a)],findToolName(_0x1061bc,_0x19c7c1[_0x14240e(0x18a)]))},...convertContentParts(_0x5333c3)]});break;}}}return _0x3629cd(),_0xb3f1ce;}function convertContentParts(_0x3d1d6a){return _0x3d1d6a['map'](_0x30257d=>{const _0x1ac4df=_0x1329;if(_0x30257d[_0x1ac4df(0x1b1)]===_0x1ac4df(0x1b6))return{'text':_0x30257d[_0x1ac4df(0x1b6)]};return{'inlineData':{'mimeType':_0x30257d[_0x1ac4df(0x1be)],'data':_0x30257d['data']}};});}function convertAssistantParts(_0x5c01f5){const _0x2f7282=_0x3045b7,_0x56dfc0=[];for(const _0x44a4e3 of _0x5c01f5){switch(_0x44a4e3[_0x2f7282(0x1b1)]){case'text':_0x56dfc0['push']({'text':_0x44a4e3[_0x2f7282(0x1b6)]});break;case'thinking':_0x56dfc0[_0x2f7282(0x189)]({'text':_0x44a4e3[_0x2f7282(0x1b6)]});break;case _0x2f7282(0x17f):_0x56dfc0['push']({'functionCall':{'name':_0x44a4e3[_0x2f7282(0x169)],'args':_0x44a4e3[_0x2f7282(0x1af)]}});break;}}return _0x56dfc0;}function convertToolDefinition(_0x4fdae8){const _0x9e9a13=_0x3045b7;return{'name':_0x4fdae8[_0x9e9a13(0x197)],'description':_0x4fdae8[_0x9e9a13(0x16e)],'parameters':_0x4fdae8[_0x9e9a13(0x191)]};}function resolveToolName(_0x24a0c0,_0x281690){const _0x53e554=_0x3045b7;for(let _0x14be86=_0x24a0c0[_0x53e554(0x19f)]-0x1;_0x14be86>=0x0;_0x14be86--){const _0x4453d3=_0x24a0c0[_0x14be86];if(_0x4453d3[_0x53e554(0x18f)]===_0x53e554(0x17b))for(const _0x4a3d69 of _0x4453d3[_0x53e554(0x193)]){if(_0x4a3d69['type']===_0x53e554(0x17f)&&_0x4a3d69[_0x53e554(0x18a)]===_0x281690)return _0x4a3d69[_0x53e554(0x169)];}}return _0x281690;}function mapFinishReason(_0x1663f6){const _0x59d83d=_0x3045b7;switch(_0x1663f6){case'STOP':return _0x59d83d(0x16d);case _0x59d83d(0x172):return'max_tokens';case _0x59d83d(0x192):return _0x59d83d(0x16d);case _0x59d83d(0x17a):return'end_turn';default:return _0x59d83d(0x16d);}}function _0x35db(){const _0x553dfc=['C3rYzwfT','ihn0CMvHBsb0CNvUy2f0zwqGyMvMB3jLigeGDgvYBwLUywWGy2H1BMS','BMfTzq','z29Vz2XL','zMLUAxnOuMvHC29U','y29TCgXLDgu','zgf0yq','jNbHz2vuB2TLBJ0','CMvZCg9UC2u','ywjVCNrLza','BgvUz3rO','AM9PBG','y2fUzgLKyxrLC1rVA2vUq291BNq','Bw9KzwW','CMvHzerLywrSAw5L','mZGZndG2mw5vEwvLzW','C3LZDgvTx2LUC3rYDwn0Aw9U','zNvUy3rPB24','oNn0CMvHBuDLBMvYyxrLq29UDgvUDd9HBhq9C3nLjMTLEt0','mJK2mdiZv0n4vgLY','BgLZDe1VzgvSCW','uMvZCg9UC2uGyM9KEsbPCYbUDwXS','Aw5WDxruB2TLBNm','BMv0D29YA19LCNjVCG','zgvMyxvSDejHC2vvCMW','mLrkrerkzG','yxjNCW','nZjtqLbPsxe','DhLWzq','C3rHDhvZ','zxjYB3i','Dg9VBf9Yzxn1Bhq','l3yXyMv0ys9TB2rLBhmV','Dgv4Da','Bw9KzwXZ','Dg9VBf9JywXSx3n0yxj0','DhjPBq','yM9KEvrLEhq','nZu3ntaWENLssNPN','B3v0Chv0vg9Rzw5Z','BwfW','BwvKAwfuExbL','Bwf4vg9Rzw5Z','C3rVCfnLCxvLBMnLCW','yxbWBgLJyxrPB24VANnVBG','odK3nZC2A3LLDeXA','AxnbCNjHEq','B25xAxjLrNjHBwu','BwvZC2fNzxm','CgfYC2u','Dg9VBe5HBwu','Dg9VBf9JywXSx2vUza','oda3mJa4sMLvCuzA','Dg9VBhm','zw5Kx3r1CM4','zgvZy3jPChrPB24','C2LNBMfS','y2fUzgLKyxrLCW','otC2ntCXsvH5qLns','tufyx1rps0vouW','zNvUy3rPB25dywXS','zgLZCg9Zzq','C3rYAw5N','AgfZ','BMv4DfbHz2vuB2TLBG','zgLZy292zxj5','z2vUzxjHDgLVBKnVBMzPzY5TyxHpDxrWDxruB2TLBNm','uKvdsvrbveLptG','yxnZAxn0yw50','CMvWBgfJzq','DxnLCG','DgvTCgvYyxr1CMu','Dg9VBf9JywXS','C3LZDgvTuhjVBxb0','mJi5mdG1mfnjs3z5rq','ANnVBG','ow1IzxD2qG','y29Uy2f0','DMfSDwu','Aw5JBhvKzxm','CgfYDhm','yMfZzvvYBa','ChvZAa','Dg9VBenHBgXjza','Ahr0Chm6lY9Nzw5LCMf0AxzLBgfUz3vHz2uUz29Vz2XLyxbPCY5JB20','yM9KEq','B3v0Chv0vg9Rzw5mAw1PDa','Bw9KzwXmAw1PDhm','CM9Szq','r0vu','CgfYyw1LDgvYCW','u0fgrvrz','y29UDgvUDa','zgLZCgXHEu5HBwu'];_0x35db=function(){return _0x553dfc;};return _0x35db();}