@aragon-agent/core 0.2.92 → 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,520 +1 @@
1
- /**
2
- * OpenAI Chat Completions adapter.
3
- *
4
- * Handles all OpenAI-compatible APIs: OpenAI, xAI, Groq, DeepSeek, Cerebras,
5
- * Mistral, and any custom endpoint that speaks the same wire format.
6
- *
7
- * Key challenges this adapter solves:
8
- * - Tool call argument chunks arrive incrementally — we accumulate and parse
9
- * the full JSON only when the tool call finishes.
10
- * - Multiple tool calls can be in-flight in a single completion chunk.
11
- * - The `[DONE]` sentinel terminates the SSE stream.
12
- */
13
- import { LLMError, classifyHttpError, wrapFetchError } from '../provider.js';
14
- import { findToolName, imageHandoffLabel, splitToolResultContent, withHandoffStub, } from './tool-result-images.js';
15
- import { DEFAULT_MAX_OUTPUT_TOKENS, estimatePromptTokens, normalizeModelId, resolveOutputTokens, staticCeilingFor, } from '../output-limits.js';
16
- import { getLearnedTokenField, sendWithOutputLimitRecovery } from '../output-limit-recovery.js';
17
- import { parseSSEStream } from '../stream-utils.js';
18
- import { consumeStream } from '../stream-utils.js';
19
- // ---------------------------------------------------------------------------
20
- // Constants
21
- // ---------------------------------------------------------------------------
22
- import { reportedContextWindow } from '../context-window.js';
23
- import { createModelDiscoverySignal } from '../model-discovery.js';
24
- const DEFAULT_BASE_URL = 'https://api.openai.com/v1';
25
- export const OPENAI_TERMINAL_DRAIN_MS = 750;
26
- /** Reasoning-family models reject `max_tokens` in favour of `max_completion_tokens`. */
27
- const REASONING_MODEL_PATTERN = /^(o1|o3|o4|gpt-5)/;
28
- // Model ID patterns to filter out non-chat models
29
- const NON_CHAT_PATTERNS = [
30
- /^text-embedding/i,
31
- /^text-moderation/i,
32
- /^text-search/i,
33
- /^text-similarity/i,
34
- /^code-search/i,
35
- /^whisper/i,
36
- /^tts/i,
37
- /^dall-e/i,
38
- /^davinci/i,
39
- /^curie/i,
40
- /^babbage/i,
41
- /^ada(?![-])/i,
42
- /embedding/i,
43
- /moderation/i,
44
- ];
45
- function isChatModel(id) {
46
- return !NON_CHAT_PATTERNS.some((pat) => pat.test(id));
47
- }
48
- /**
49
- * Which parameter name carries the cap for this model.
50
- *
51
- * A HEURISTIC, and only the first guess: a proxy fronting an o-series model
52
- * under a `gpt-` alias disagrees with it. `unsupported_field` recovery renames
53
- * the parameter after one round trip and memoizes the answer, which is why the
54
- * learned dialect is consulted first.
55
- */
56
- export function openAiTokenField(modelId) {
57
- const learned = getLearnedTokenField('openai', modelId);
58
- if (learned)
59
- return learned;
60
- return REASONING_MODEL_PATTERN.test(normalizeModelId(modelId))
61
- ? 'max_completion_tokens'
62
- : 'max_tokens';
63
- }
64
- // ---------------------------------------------------------------------------
65
- // OpenAI provider
66
- // ---------------------------------------------------------------------------
67
- export class OpenAIProvider {
68
- id = 'openai';
69
- displayName = 'OpenAI';
70
- defaultBaseUrl = DEFAULT_BASE_URL;
71
- // -----------------------------------------------------------------------
72
- // stream
73
- // -----------------------------------------------------------------------
74
- async *stream(request) {
75
- if (request.signal?.aborted)
76
- return;
77
- const scope = new OpenAIRequestScope(request.signal);
78
- try {
79
- if (request.signal?.aborted)
80
- return;
81
- const attempt = await sendOpenAIRequest(request, this.defaultBaseUrl, scope.signal);
82
- if (request.signal?.aborted)
83
- return;
84
- const response = attempt.response;
85
- if (!response.ok) {
86
- throw classifyHttpError(response.status, attempt.bodyText, this.id, response.headers);
87
- }
88
- if (!response.body) {
89
- throw new LLMError('Response body is null', this.id, 'network_error', true);
90
- }
91
- for await (const event of readOpenAIResponse(response.body, scope, request.readDeadline, request.onWireFrame)) {
92
- if (request.signal?.aborted)
93
- return;
94
- yield event;
95
- if (request.signal?.aborted)
96
- return;
97
- }
98
- }
99
- catch (err) {
100
- if (request.signal?.aborted)
101
- return;
102
- yield { type: 'error', error: wrapFetchError(err, this.id) };
103
- }
104
- finally {
105
- scope.dispose();
106
- }
107
- }
108
- // -----------------------------------------------------------------------
109
- // complete
110
- // -----------------------------------------------------------------------
111
- async complete(request) {
112
- return consumeStream(this.stream(request));
113
- }
114
- // -----------------------------------------------------------------------
115
- // listModels
116
- // -----------------------------------------------------------------------
117
- async listModels(apiKey, baseUrl, signal) {
118
- const base = (baseUrl || this.defaultBaseUrl).replace(/\/+$/, '');
119
- const url = `${base}/models`;
120
- const scope = createModelDiscoverySignal(signal);
121
- try {
122
- if (scope.signal.aborted)
123
- return [];
124
- const res = await fetch(url, {
125
- method: 'GET',
126
- headers: {
127
- 'Authorization': `Bearer ${apiKey}`,
128
- },
129
- signal: scope.signal,
130
- });
131
- if (!res.ok)
132
- return [];
133
- const data = await res.json();
134
- if (signal?.aborted)
135
- return [];
136
- // The OpenAI models endpoint does NOT report an output ceiling, so this
137
- // maps through the static table and deliberately does NOT call
138
- // `learnModelCeiling` — claiming knowledge we do not have would outrank
139
- // the (correct) table entry for every small model.
140
- return (data.data || [])
141
- .filter((m) => isChatModel(String(m.id || '')))
142
- .map((m) => ({
143
- id: String(m.id || ''),
144
- name: String(m.id || ''),
145
- provider: this.id,
146
- ...reportedContextWindow(m),
147
- maxOutputTokens: staticCeilingFor(this.id, String(m.id || '')) ?? DEFAULT_MAX_OUTPUT_TOKENS,
148
- supportsThinking: false,
149
- supportsTools: true,
150
- supportsImages: /gpt-4|o1|o3/i.test(String(m.id)),
151
- cost: { input: 0, output: 0 },
152
- }));
153
- }
154
- catch {
155
- return [];
156
- }
157
- finally {
158
- scope.dispose();
159
- }
160
- }
161
- }
162
- /** Owns the request signal and the absolute, non-renewable terminal deadline. */
163
- class OpenAIRequestScope {
164
- caller;
165
- controller = new AbortController();
166
- timer;
167
- cancelCause = null;
168
- onCallerAbort = () => {
169
- this.cancelCause = 'caller';
170
- this.controller.abort();
171
- };
172
- constructor(caller) {
173
- this.caller = caller;
174
- caller?.addEventListener('abort', this.onCallerAbort, { once: true });
175
- if (caller?.aborted)
176
- this.onCallerAbort();
177
- }
178
- get signal() { return this.controller.signal; }
179
- get callerAborted() { return this.caller?.aborted === true; }
180
- get terminalDrainExpired() { return this.cancelCause === 'terminal-drain'; }
181
- startDrain() {
182
- if (this.timer !== undefined || this.cancelCause !== null)
183
- return;
184
- this.timer = setTimeout(() => {
185
- if (this.callerAborted) {
186
- this.onCallerAbort();
187
- return;
188
- }
189
- this.cancelCause = 'terminal-drain';
190
- this.controller.abort();
191
- }, OPENAI_TERMINAL_DRAIN_MS);
192
- }
193
- dispose() {
194
- if (this.timer !== undefined)
195
- clearTimeout(this.timer);
196
- this.caller?.removeEventListener('abort', this.onCallerAbort);
197
- }
198
- }
199
- function sendOpenAIRequest(request, defaultBaseUrl, signal) {
200
- const baseUrl = (request.baseUrl || defaultBaseUrl).replace(/\/+$/, '');
201
- return sendWithOutputLimitRecovery({
202
- providerId: 'openai',
203
- modelId: request.model,
204
- body: buildRequestBody(request),
205
- tokenField: openAiTokenField(request.model),
206
- send: (payload) => fetch(`${baseUrl}/chat/completions`, {
207
- method: 'POST',
208
- headers: {
209
- 'Content-Type': 'application/json',
210
- 'Authorization': `Bearer ${request.apiKey}`,
211
- },
212
- body: JSON.stringify(payload),
213
- signal,
214
- }),
215
- });
216
- }
217
- async function* readOpenAIResponse(body, scope, readDeadline, onWireFrame) {
218
- const state = new OpenAIStreamState();
219
- try {
220
- // The read signal covers ONE attempt: it aborts on the caller's Esc (so Esc still
221
- // means Esc) and on silence. Aborting the read is what turns a stall into the
222
- // `AbortError` -> `timeout`/`retryable` failure the ladder already handles (F1′).
223
- for await (const sse of parseSSEStream(body, readDeadline ?? scope.signal)) {
224
- if (scope.callerAborted)
225
- return;
226
- // LIVENESS, BEFORE `[DONE]`: a usage-only chunk is still a frame.
227
- onWireFrame?.();
228
- const raw = sse.data.trim();
229
- if (raw === '[DONE]') {
230
- state.sawTerminal = true;
231
- break;
232
- }
233
- for (const event of state.consume(raw, scope)) {
234
- if (scope.callerAborted)
235
- return;
236
- yield event;
237
- if (scope.callerAborted)
238
- return;
239
- }
240
- }
241
- }
242
- catch (err) {
243
- if (scope.callerAborted)
244
- return;
245
- if (!scope.terminalDrainExpired || !state.sawTerminal)
246
- throw err;
247
- }
248
- if (scope.callerAborted)
249
- return;
250
- if (!state.sawTerminal) {
251
- throw new LLMError('openai stream truncated before a terminal chunk', 'openai', 'network_error', true);
252
- }
253
- for (const event of state.finish()) {
254
- if (scope.callerAborted)
255
- return;
256
- yield event;
257
- if (scope.callerAborted)
258
- return;
259
- }
260
- }
261
- class OpenAIStreamState {
262
- usage = { inputTokens: 0, outputTokens: 0 };
263
- sawTerminal = false;
264
- text = '';
265
- thinking = '';
266
- stopReason;
267
- tools = new Map();
268
- *consume(raw, scope) {
269
- let chunk;
270
- try {
271
- chunk = JSON.parse(raw);
272
- }
273
- catch {
274
- return;
275
- }
276
- if (!chunk || typeof chunk !== 'object')
277
- return;
278
- const usage = chunk.usage;
279
- if (usage) {
280
- this.usage.inputTokens = usage.prompt_tokens ?? this.usage.inputTokens;
281
- this.usage.outputTokens = usage.completion_tokens ?? this.usage.outputTokens;
282
- }
283
- if (this.sawTerminal)
284
- return;
285
- const choices = chunk.choices;
286
- if (!Array.isArray(choices) || choices.length === 0)
287
- return;
288
- const choice = choices.find((candidate) => candidate.index === 0)
289
- ?? (choices[0].index === undefined ? choices[0] : undefined);
290
- if (!choice)
291
- return;
292
- if (typeof choice.finish_reason === 'string' && choice.finish_reason.length > 0) {
293
- this.sawTerminal = true;
294
- this.stopReason = mapFinishReason(choice.finish_reason);
295
- // Start at receipt, including when a consumer pauses on this frame's delta.
296
- scope.startDrain();
297
- }
298
- const delta = choice.delta;
299
- if (delta)
300
- yield* this.consumeDelta(delta);
301
- }
302
- *consumeDelta(delta) {
303
- const reasoning = delta.reasoning_content;
304
- if (typeof reasoning === 'string' && reasoning.length > 0) {
305
- if (this.thinking.length === 0)
306
- yield { type: 'thinking_start' };
307
- this.thinking += reasoning;
308
- yield { type: 'thinking_delta', delta: reasoning };
309
- }
310
- if (typeof delta.content === 'string' && delta.content.length > 0) {
311
- this.text += delta.content;
312
- yield { type: 'text_delta', delta: delta.content };
313
- }
314
- const tools = delta.tool_calls;
315
- if (Array.isArray(tools)) {
316
- for (const tool of tools)
317
- yield* this.consumeTool(tool);
318
- }
319
- }
320
- *consumeTool(tool) {
321
- const index = tool.index ?? 0;
322
- const fn = tool.function;
323
- let acc = this.tools.get(index);
324
- if (!acc) {
325
- acc = {
326
- index, toolCallId: tool.id || `call_${index}`,
327
- toolName: fn?.name || '', argsJson: '', started: false,
328
- };
329
- this.tools.set(index, acc);
330
- }
331
- if (fn?.name)
332
- acc.toolName = fn.name;
333
- if (!acc.started && acc.toolName) {
334
- acc.started = true;
335
- yield { type: 'tool_call_start', toolCallId: acc.toolCallId, toolName: acc.toolName };
336
- }
337
- if (typeof fn?.arguments === 'string' && fn.arguments.length > 0) {
338
- acc.argsJson += fn.arguments;
339
- if (acc.started) {
340
- yield { type: 'tool_call_delta', toolCallId: acc.toolCallId, argsDelta: fn.arguments };
341
- }
342
- }
343
- }
344
- *finish() {
345
- const content = [];
346
- if (this.thinking)
347
- content.push({ type: 'thinking', text: this.thinking });
348
- if (this.text)
349
- content.push({ type: 'text', text: this.text });
350
- for (const acc of this.tools.values()) {
351
- let args = {};
352
- try {
353
- args = acc.argsJson ? JSON.parse(acc.argsJson) : {};
354
- }
355
- catch {
356
- args = { __raw: acc.argsJson };
357
- }
358
- content.push({
359
- type: 'tool_call', toolCallId: acc.toolCallId, toolName: acc.toolName, args,
360
- });
361
- yield { type: 'tool_call_end', toolCallId: acc.toolCallId, toolName: acc.toolName, args };
362
- }
363
- const message = {
364
- role: 'assistant', content, usage: this.usage, stopReason: this.stopReason,
365
- };
366
- yield { type: 'done', message, usage: this.usage };
367
- }
368
- }
369
- // ---------------------------------------------------------------------------
370
- // Internal: request body builder
371
- // ---------------------------------------------------------------------------
372
- function buildRequestBody(request) {
373
- const messages = convertMessages(request.messages, request.systemPrompt);
374
- const body = {
375
- model: request.model,
376
- messages,
377
- stream: true,
378
- stream_options: { include_usage: true },
379
- };
380
- const tokenField = openAiTokenField(request.model);
381
- // The prompt estimate is only ever consumed when the caller told us the
382
- // context window, so it is computed only then — walking every message on a
383
- // hot path that cannot use the result would be pure waste.
384
- const contextWindow = request.modelLimits?.contextWindow;
385
- const resolution = resolveOutputTokens({
386
- providerId: 'openai',
387
- modelId: request.model,
388
- ...(request.maxTokens !== undefined ? { requested: request.maxTokens } : {}),
389
- ...(request.modelLimits ? { modelLimits: request.modelLimits } : {}),
390
- ...(contextWindow !== undefined
391
- ? { estimatedPromptTokens: estimatePromptTokens(request.messages, request.systemPrompt) }
392
- : {}),
393
- });
394
- body[tokenField] = resolution.value;
395
- // The reasoning family rejects `temperature` alongside `max_tokens`; sending
396
- // it would just buy a second 400 on a different key.
397
- if (request.temperature !== undefined && tokenField === 'max_tokens') {
398
- body.temperature = request.temperature;
399
- }
400
- if (request.stopSequences && request.stopSequences.length > 0) {
401
- body.stop = request.stopSequences;
402
- }
403
- if (request.tools && request.tools.length > 0) {
404
- body.tools = request.tools.map(convertToolDefinition);
405
- }
406
- return body;
407
- }
408
- // ---------------------------------------------------------------------------
409
- // Internal: message format conversion
410
- // ---------------------------------------------------------------------------
411
- function convertMessages(messages, systemPrompt) {
412
- const result = [];
413
- // The `tool` role cannot carry pictures, so a tool result's images are handed off in a `user`
414
- // message. OpenAI requires every `tool` message answering one assistant turn to follow it
415
- // back to back, so the hand-offs wait here until that run of tool results ends.
416
- let handoffs = [];
417
- const flushHandoffs = () => {
418
- if (handoffs.length === 0)
419
- return;
420
- result.push(...handoffs);
421
- handoffs = [];
422
- };
423
- // System prompt as the first message
424
- if (systemPrompt) {
425
- result.push({ role: 'system', content: systemPrompt });
426
- }
427
- for (const msg of messages) {
428
- if (msg.role !== 'tool_result')
429
- flushHandoffs();
430
- switch (msg.role) {
431
- case 'user':
432
- result.push({
433
- role: 'user',
434
- content: typeof msg.content === 'string'
435
- ? msg.content
436
- : convertContentParts(msg.content),
437
- });
438
- break;
439
- case 'assistant':
440
- result.push(convertAssistantMessage(msg));
441
- break;
442
- case 'tool_result': {
443
- const { text, images } = splitToolResultContent(msg.content);
444
- if (images.length === 0) {
445
- result.push({ role: 'tool', tool_call_id: msg.toolCallId, content: text });
446
- break;
447
- }
448
- result.push({ role: 'tool', tool_call_id: msg.toolCallId, content: withHandoffStub(text) });
449
- handoffs.push({
450
- role: 'user',
451
- content: [
452
- { type: 'text', text: imageHandoffLabel(msg.toolCallId, findToolName(messages, msg.toolCallId)) },
453
- ...convertContentParts(images),
454
- ],
455
- });
456
- break;
457
- }
458
- }
459
- }
460
- flushHandoffs();
461
- return result;
462
- }
463
- function convertContentParts(parts) {
464
- return parts.map((part) => {
465
- if (part.type === 'text') {
466
- return { type: 'text', text: part.text };
467
- }
468
- return {
469
- type: 'image_url',
470
- image_url: {
471
- url: `data:${part.mediaType};base64,${part.data}`,
472
- },
473
- };
474
- });
475
- }
476
- function convertAssistantMessage(msg) {
477
- const result = { role: 'assistant' };
478
- // Extract text content
479
- const textParts = msg.content.filter((b) => b.type === 'text');
480
- if (textParts.length > 0) {
481
- result.content = textParts.map((b) => b.text).join('');
482
- }
483
- else {
484
- result.content = null;
485
- }
486
- // Extract tool calls
487
- const toolCalls = msg.content.filter((b) => b.type === 'tool_call');
488
- if (toolCalls.length > 0) {
489
- result.tool_calls = toolCalls.map((tc) => ({
490
- id: tc.toolCallId,
491
- type: 'function',
492
- function: {
493
- name: tc.toolName,
494
- arguments: JSON.stringify(tc.args),
495
- },
496
- }));
497
- }
498
- return result;
499
- }
500
- function convertToolDefinition(tool) {
501
- return {
502
- type: 'function',
503
- function: {
504
- name: tool.name,
505
- description: tool.description,
506
- parameters: tool.parameters,
507
- },
508
- };
509
- }
510
- // ---------------------------------------------------------------------------
511
- // Internal: helpers
512
- // ---------------------------------------------------------------------------
513
- function mapFinishReason(reason) {
514
- switch (reason) {
515
- case 'stop': return 'end_turn';
516
- case 'tool_calls': return 'tool_use';
517
- case 'length': return 'max_tokens';
518
- default: return 'end_turn';
519
- }
520
- }
1
+ const _0xfcd86a=_0x4c36;function _0x410e(){const _0x385d0c=['zMLUAxnOx3jLyxnVBG','zgvMyxvSDejHC2vvCMW','B25dywXSzxjbyM9YDa','C2f3vgvYBwLUywW','qMvHCMvYia','Dg9VBenHBgXjza','B3bLBMfPihn0CMvHBsb0CNvUy2f0zwqGyMvMB3jLigeGDgvYBwLUywWGy2H1BMS','DhLWzq','DMfSDwu','C3rYAw5N','BwfW','zw5Kx3r1CM4','Dg9VBf9Yzxn1Bhq','y29UDgvUDa','Aw5KzxG','Bwf4vg9Rzw5Z','Dg9VBhm','B25xAxjLrNjHBwu','C3rHDhvZ','Bw9KzwW','ChvZAa','BwvKAwfuExbL','ANnVBG','DxnLCG','mZm1mte3DNrmu2fq','yMfZzvvYBa','zgf0ytO','DgvYBwLUywWTzhjHAw4','nJniwgLQA2O','ndeZmJa5ohflwMHMsa','yM9KEvrLEhq','Dgv4Da','BwvZC2fNzxm','DgLTzxi','Dgv4Df9KzwX0yq','y2HVAwnLCW','CgfYC2u','BMv0D29YA19LCNjVCG','C3rVCa','ywjVCNrLza','DgHPBMTPBMDFC3rHCNq','zgLZCg9Zzq','C3rVCfnLCxvLBMnLCW','y29UC3vTzvrVB2W','zgvSDge','Dg9VBf9JywXSCW','o2jHC2u2ncW','Dg9VBf91C2u','yM9KEq','zMLSDgvY','BgLZDe1VzgvSCW','y29TCgXLDgu','Aw1Hz2vFDxjS','zNvUy3rPB24','r0vu','BMfTzq','zMLUAxnO','l2nOyxqVy29TCgXLDgLVBNm','ndy1mdCYshnkyK1y','y29UDhjVBgXLCG','AM9PBG','Dg9VBf9JywXSx2rLBhrH','C3rHCNrLza','zgf0yq','CMvHC29UAw5Nx2nVBNrLBNq','mtGYnZa4D1HuruDO','DhjPBq','y2fUy2vSq2f1C2u','yxjNCW','B2jQzwn0','mJj3q2LOAK8','y29UC3vTzurLBhrH','C3LZDgvT','Bwf4x2nVBxbSzxrPB25FDg9Rzw5Z','y2fSBf8','y29UC3vTzq','CMvZCg9UC2u','Bwf4x3rVA2vUCW','zxjYB3i','CMvTB3zLrxzLBNrmAxn0zw5LCG','Dg9VBf9JywXSx2vUza','zgLZCgXHEu5HBwu','zMLUza','y29TCgXLDgLVBL90B2TLBNm','DgvTCgvYyxr1CMu','y29UDgv4DfDPBMrVDW','yxjNDw1LBNrZ','nufnzxrZAG','ndu4nti2reTyBLHl','Aw5WDxruB2TLBNm','DgvYBwLUywXeCMfPBKv4CgLYzwq','CMvWBgfJzq','ywjVCNq','AxnbCNjHEq','Dg9VBa','CgfYyw1LDgvYCW','y2fSBgvY','nhnJt2nUsa','y2fSBgvYqwjVCNrLza','yxjNC0PZB24','C3rVCfjLyxnVBG','B3v0Chv0vg9Rzw5Z','BgvUz3rO','C3LZDgvTuhjVBxb0','C3rYAw5NAwz5','y29Uy2f0','z2v0','ue9tva','C2LNBMfS','mta0nZmZmeDVyw13wG','yxnZAxn0yw50','zgvZy3jPChrPB24','C3rHCNreCMfPBG','DgvZDa','mJeYnJi3nevxve9bCG','Dg9VBf9JywXS','ChjVBxb0x3rVA2vUCW','Dg9VBe5HBwu','B3bLBMfP','DxnHz2u','CM9Szq','w0rptKvD','DgHPBMTPBMC','C3rYzwfT','Bw9KzwXmAw1PDhm'];_0x410e=function(){return _0x385d0c;};return _0x410e();}(function(_0x2a3930,_0x25ad69){const _0x5cbf8d=_0x4c36,_0x412e34=_0x2a3930();while(!![]){try{const _0x20b728=parseInt(_0x5cbf8d(0x1d7))/0x1*(parseInt(_0x5cbf8d(0x1a3))/0x2)+-parseInt(_0x5cbf8d(0x19a))/0x3+-parseInt(_0x5cbf8d(0x200))/0x4*(parseInt(_0x5cbf8d(0x199))/0x5)+-parseInt(_0x5cbf8d(0x1b4))/0x6+parseInt(_0x5cbf8d(0x1db))/0x7*(parseInt(_0x5cbf8d(0x1f9))/0x8)+-parseInt(_0x5cbf8d(0x1dc))/0x9+-parseInt(_0x5cbf8d(0x1af))/0xa*(-parseInt(_0x5cbf8d(0x188))/0xb);if(_0x20b728===_0x25ad69)break;else _0x412e34['push'](_0x412e34['shift']());}catch(_0x52d9ce){_0x412e34['push'](_0x412e34['shift']());}}}(_0x410e,0x5f6e6));import{LLMError,classifyHttpError,wrapFetchError}from'../provider.js';import{findToolName,imageHandoffLabel,splitToolResultContent,withHandoffStub}from'./tool-result-images.js';import{DEFAULT_MAX_OUTPUT_TOKENS,estimatePromptTokens,normalizeModelId,resolveOutputTokens,staticCeilingFor}from'../output-limits.js';import{getLearnedTokenField,sendWithOutputLimitRecovery}from'../output-limit-recovery.js';import{parseSSEStream}from'../stream-utils.js';import{consumeStream}from'../stream-utils.js';import{reportedContextWindow}from'../context-window.js';import{createModelDiscoverySignal}from'../model-discovery.js';function _0x4c36(_0x1beb57,_0xa6d04){_0x1beb57=_0x1beb57-0x184;const _0x410efd=_0x410e();let _0x4c363c=_0x410efd[_0x1beb57];if(_0x4c36['kCzEDf']===undefined){var _0x325fba=function(_0x316994){const _0x2959a9='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x858336='',_0x11ca63='';for(let _0x300435=0x0,_0x139f39,_0x35af05,_0x481ad4=0x0;_0x35af05=_0x316994['charAt'](_0x481ad4++);~_0x35af05&&(_0x139f39=_0x300435%0x4?_0x139f39*0x40+_0x35af05:_0x35af05,_0x300435++%0x4)?_0x858336+=String['fromCharCode'](0xff&_0x139f39>>(-0x2*_0x300435&0x6)):0x0){_0x35af05=_0x2959a9['indexOf'](_0x35af05);}for(let _0x36463c=0x0,_0x112abc=_0x858336['length'];_0x36463c<_0x112abc;_0x36463c++){_0x11ca63+='%'+('00'+_0x858336['charCodeAt'](_0x36463c)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x11ca63);};_0x4c36['sXzDht']=_0x325fba,_0x4c36['wJdMag']={},_0x4c36['kCzEDf']=!![];}const _0x2f8df9=_0x410efd[0x0];_0x4c36['DSKNHT']!==_0x2f8df9&&(_0x4c36['wJdMag']={},_0x4c36['DSKNHT']=_0x2f8df9);const _0x105068=_0x4c36['wJdMag'][_0x1beb57];return _0x105068===undefined?(_0x4c363c=_0x4c36['sXzDht'](_0x4c363c),_0x4c36['wJdMag'][_0x1beb57]=_0x4c363c):_0x4c363c=_0x105068,_0x4c363c;}const DEFAULT_BASE_URL='https://api.openai.com/v1';export const OPENAI_TERMINAL_DRAIN_MS=0x2ee;const REASONING_MODEL_PATTERN=/^(o1|o3|o4|gpt-5)/,NON_CHAT_PATTERNS=[/^text-embedding/i,/^text-moderation/i,/^text-search/i,/^text-similarity/i,/^code-search/i,/^whisper/i,/^tts/i,/^dall-e/i,/^davinci/i,/^curie/i,/^babbage/i,/^ada(?![-])/i,/embedding/i,/moderation/i];function isChatModel(_0x11ca63){return!NON_CHAT_PATTERNS['some'](_0x300435=>_0x300435['test'](_0x11ca63));}export function openAiTokenField(_0x139f39){const _0xb11c9=_0x4c36,_0x35af05=getLearnedTokenField(_0xb11c9(0x1b8),_0x139f39);if(_0x35af05)return _0x35af05;return REASONING_MODEL_PATTERN[_0xb11c9(0x1b3)](normalizeModelId(_0x139f39))?_0xb11c9(0x18b):_0xb11c9(0x18f);}export class OpenAIProvider{['id']='openai';[_0xfcd86a(0x193)]='OpenAI';['defaultBaseUrl']=DEFAULT_BASE_URL;async*[_0xfcd86a(0x1bd)](_0x481ad4){const _0x573349=_0xfcd86a;if(_0x481ad4['signal']?.[_0x573349(0x1e6)])return;const _0x36463c=new OpenAIRequestScope(_0x481ad4[_0x573349(0x1ae)]);try{if(_0x481ad4[_0x573349(0x1ae)]?.[_0x573349(0x1e6)])return;const _0x112abc=await sendOpenAIRequest(_0x481ad4,this[_0x573349(0x1c0)],_0x36463c[_0x573349(0x1ae)]);if(_0x481ad4[_0x573349(0x1ae)]?.[_0x573349(0x1e6)])return;const _0x21b043=_0x112abc[_0x573349(0x18e)];if(!_0x21b043['ok'])throw classifyHttpError(_0x21b043[_0x573349(0x1d1)],_0x112abc[_0x573349(0x1dd)],this['id'],_0x21b043['headers']);if(!_0x21b043[_0x573349(0x1ef)])throw new LLMError('Response\x20body\x20is\x20null',this['id'],_0x573349(0x1e4),!![]);for await(const _0x1c3349 of readOpenAIResponse(_0x21b043[_0x573349(0x1ef)],_0x36463c,_0x481ad4['readDeadline'],_0x481ad4[_0x573349(0x1d0)])){if(_0x481ad4['signal']?.[_0x573349(0x1e6)])return;yield _0x1c3349;if(_0x481ad4[_0x573349(0x1ae)]?.['aborted'])return;}}catch(_0x59615f){if(_0x481ad4[_0x573349(0x1ae)]?.[_0x573349(0x1e6)])return;yield{'type':_0x573349(0x190),'error':wrapFetchError(_0x59615f,this['id'])};}finally{_0x36463c[_0x573349(0x1e8)]();}}async[_0xfcd86a(0x1f2)](_0x3f4cc0){const _0x187f78=_0xfcd86a;return consumeStream(this[_0x187f78(0x1bd)](_0x3f4cc0));}async[_0xfcd86a(0x1f1)](_0x30d525,_0x388d27,_0x51854e){const _0x2475cd=_0xfcd86a,_0x40bea0=(_0x388d27||this[_0x2475cd(0x1c0)])[_0x2475cd(0x19d)](/\/+$/,''),_0x2e9bf9=''['concat'](_0x40bea0,'/models'),_0x1f2b50=createModelDiscoverySignal(_0x51854e);try{if(_0x1f2b50[_0x2475cd(0x1ae)][_0x2475cd(0x1e6)])return[];const _0x4d8ab4=await fetch(_0x2e9bf9,{'method':_0x2475cd(0x1f5),'headers':{'Authorization':_0x2475cd(0x1c3)[_0x2475cd(0x1ab)](_0x30d525)},'signal':_0x1f2b50[_0x2475cd(0x1ae)]});if(!_0x4d8ab4['ok'])return[];const _0x29e357=await _0x4d8ab4[_0x2475cd(0x1d5)]();if(_0x51854e?.['aborted'])return[];return(_0x29e357[_0x2475cd(0x1fe)]||[])[_0x2475cd(0x1f0)](_0x2f61de=>isChatModel(String(_0x2f61de['id']||'')))[_0x2475cd(0x1c9)](_0x35ef8f=>({'id':String(_0x35ef8f['id']||''),'name':String(_0x35ef8f['id']||''),'provider':this['id'],...reportedContextWindow(_0x35ef8f),'maxOutputTokens':staticCeilingFor(this['id'],String(_0x35ef8f['id']||''))??DEFAULT_MAX_OUTPUT_TOKENS,'supportsThinking':![],'supportsTools':!![],'supportsImages':/gpt-4|o1|o3/i[_0x2475cd(0x1b3)](String(_0x35ef8f['id'])),'cost':{'input':0x0,'output':0x0}}));}catch{return[];}finally{_0x1f2b50[_0x2475cd(0x1e8)]();}}}class OpenAIRequestScope{['caller'];[_0xfcd86a(0x1fa)]=new AbortController();['timer'];['cancelCause']=null;[_0xfcd86a(0x1c1)]=()=>{const _0x126829=_0xfcd86a;this[_0x126829(0x185)]='caller',this['controller'][_0x126829(0x19e)]();};constructor(_0x4e7a88){const _0x2ea528=_0xfcd86a;this[_0x2ea528(0x1a2)]=_0x4e7a88,_0x4e7a88?.['addEventListener'](_0x2ea528(0x19e),this['onCallerAbort'],{'once':!![]});if(_0x4e7a88?.[_0x2ea528(0x1e6)])this[_0x2ea528(0x1c1)]();}get[_0xfcd86a(0x1ae)](){return this['controller']['signal'];}get[_0xfcd86a(0x1a4)](){const _0x15ff9d=_0xfcd86a;return this[_0x15ff9d(0x1a2)]?.[_0x15ff9d(0x1e6)]===!![];}get['terminalDrainExpired'](){const _0x51f65c=_0xfcd86a;return this[_0x51f65c(0x185)]===_0x51f65c(0x1da);}[_0xfcd86a(0x1b2)](){const _0x30e72b=_0xfcd86a;if(this[_0x30e72b(0x1e0)]!==undefined||this['cancelCause']!==null)return;this[_0x30e72b(0x1e0)]=setTimeout(()=>{const _0x1386dd=_0x30e72b;if(this[_0x1386dd(0x1a4)]){this[_0x1386dd(0x1c1)]();return;}this[_0x1386dd(0x185)]='terminal-drain',this['controller'][_0x1386dd(0x19e)]();},OPENAI_TERMINAL_DRAIN_MS);}[_0xfcd86a(0x1e8)](){const _0x26f35d=_0xfcd86a;if(this['timer']!==undefined)clearTimeout(this[_0x26f35d(0x1e0)]);this['caller']?.[_0x26f35d(0x191)](_0x26f35d(0x19e),this[_0x26f35d(0x1c1)]);}}function sendOpenAIRequest(_0x3b6de4,_0x12089f,_0x89827f){const _0x5a52fa=_0xfcd86a,_0x3c58d0=(_0x3b6de4[_0x5a52fa(0x1d8)]||_0x12089f)['replace'](/\/+$/,'');return sendWithOutputLimitRecovery({'providerId':'openai','modelId':_0x3b6de4['model'],'body':buildRequestBody(_0x3b6de4),'tokenField':openAiTokenField(_0x3b6de4[_0x5a52fa(0x1d2)]),'send':_0x3e4244=>fetch(''[_0x5a52fa(0x1ab)](_0x3c58d0,_0x5a52fa(0x1f8)),{'method':_0x5a52fa(0x1ad),'headers':{'Content-Type':'application/json','Authorization':_0x5a52fa(0x1c3)['concat'](_0x3b6de4['apiKey'])},'body':JSON['stringify'](_0x3e4244),'signal':_0x89827f})});}async function*readOpenAIResponse(_0x437bab,_0x257bbc,_0x145ddb,_0x1bd8c1){const _0x30d6ca=_0xfcd86a,_0x5f2375=new OpenAIStreamState();try{for await(const _0x3ff98f of parseSSEStream(_0x437bab,_0x145ddb??_0x257bbc[_0x30d6ca(0x1ae)])){if(_0x257bbc['callerAborted'])return;_0x1bd8c1?.();const _0x532462=_0x3ff98f['data'][_0x30d6ca(0x184)]();if(_0x532462===_0x30d6ca(0x1bb)){_0x5f2375[_0x30d6ca(0x1c2)]=!![];break;}for(const _0x11a7ea of _0x5f2375[_0x30d6ca(0x18d)](_0x532462,_0x257bbc)){if(_0x257bbc[_0x30d6ca(0x1a4)])return;yield _0x11a7ea;if(_0x257bbc[_0x30d6ca(0x1a4)])return;}}}catch(_0x2ea49d){if(_0x257bbc[_0x30d6ca(0x1a4)])return;if(!_0x257bbc[_0x30d6ca(0x19c)]||!_0x5f2375['sawTerminal'])throw _0x2ea49d;}if(_0x257bbc[_0x30d6ca(0x1a4)])return;if(!_0x5f2375[_0x30d6ca(0x1c2)])throw new LLMError(_0x30d6ca(0x1c5),_0x30d6ca(0x1b8),_0x30d6ca(0x1e4),!![]);for(const _0x455f9f of _0x5f2375[_0x30d6ca(0x1f7)]()){if(_0x257bbc[_0x30d6ca(0x1a4)])return;yield _0x455f9f;if(_0x257bbc[_0x30d6ca(0x1a4)])return;}}class OpenAIStreamState{[_0xfcd86a(0x1b9)]={'inputTokens':0x0,'outputTokens':0x0};['sawTerminal']=![];['text']='';[_0xfcd86a(0x1bc)]='';[_0xfcd86a(0x1a6)];[_0xfcd86a(0x1cf)]=new Map();*[_0xfcd86a(0x18d)](_0x4113ef,_0x274556){const _0x54bbe2=_0xfcd86a;let _0x5beb2a;try{_0x5beb2a=JSON[_0x54bbe2(0x1e3)](_0x4113ef);}catch{return;}if(!_0x5beb2a||typeof _0x5beb2a!==_0x54bbe2(0x187))return;const _0x2dd73a=_0x5beb2a['usage'];_0x2dd73a&&(this['usage'][_0x54bbe2(0x19b)]=_0x2dd73a[_0x54bbe2(0x1b6)]??this[_0x54bbe2(0x1b9)][_0x54bbe2(0x19b)],this[_0x54bbe2(0x1b9)][_0x54bbe2(0x1a7)]=_0x2dd73a[_0x54bbe2(0x195)]??this[_0x54bbe2(0x1b9)][_0x54bbe2(0x1a7)]);if(this['sawTerminal'])return;const _0x212257=_0x5beb2a[_0x54bbe2(0x1e2)];if(!Array[_0x54bbe2(0x19f)](_0x212257)||_0x212257[_0x54bbe2(0x1a8)]===0x0)return;const _0x10ac38=_0x212257[_0x54bbe2(0x194)](_0x576ce7=>_0x576ce7[_0x54bbe2(0x1cd)]===0x0)??(_0x212257[0x0]['index']===undefined?_0x212257[0x0]:undefined);if(!_0x10ac38)return;typeof _0x10ac38[_0x54bbe2(0x1bf)]===_0x54bbe2(0x1c8)&&_0x10ac38['finish_reason'][_0x54bbe2(0x1a8)]>0x0&&(this[_0x54bbe2(0x1c2)]=!![],this[_0x54bbe2(0x1a6)]=mapFinishReason(_0x10ac38[_0x54bbe2(0x1bf)]),_0x274556[_0x54bbe2(0x1b2)]());const _0x1d728f=_0x10ac38[_0x54bbe2(0x1eb)];if(_0x1d728f)yield*this[_0x54bbe2(0x189)](_0x1d728f);}*[_0xfcd86a(0x189)](_0x2bd6b9){const _0x37646b=_0xfcd86a,_0xed80d8=_0x2bd6b9[_0x37646b(0x1ff)];if(typeof _0xed80d8===_0x37646b(0x1c8)&&_0xed80d8[_0x37646b(0x1a8)]>0x0){if(this[_0x37646b(0x1bc)][_0x37646b(0x1a8)]===0x0)yield{'type':_0x37646b(0x1e7)};this['thinking']+=_0xed80d8,yield{'type':'thinking_delta','delta':_0xed80d8};}typeof _0x2bd6b9[_0x37646b(0x1cc)]===_0x37646b(0x1c8)&&_0x2bd6b9[_0x37646b(0x1cc)][_0x37646b(0x1a8)]>0x0&&(this[_0x37646b(0x1de)]+=_0x2bd6b9[_0x37646b(0x1cc)],yield{'type':_0x37646b(0x1e1),'delta':_0x2bd6b9[_0x37646b(0x1cc)]});const _0x5f16e2=_0x2bd6b9[_0x37646b(0x1ec)];if(Array[_0x37646b(0x19f)](_0x5f16e2)){for(const _0x56e0b5 of _0x5f16e2)yield*this[_0x37646b(0x1ea)](_0x56e0b5);}}*[_0xfcd86a(0x1ea)](_0x2b9519){const _0x3589a2=_0xfcd86a,_0x17d187=_0x2b9519[_0x3589a2(0x1cd)]??0x0,_0x1ff851=_0x2b9519['function'];let _0x1c0bc2=this[_0x3589a2(0x1cf)][_0x3589a2(0x1ac)](_0x17d187);!_0x1c0bc2&&(_0x1c0bc2={'index':_0x17d187,'toolCallId':_0x2b9519['id']||_0x3589a2(0x18c)[_0x3589a2(0x1ab)](_0x17d187),'toolName':_0x1ff851?.[_0x3589a2(0x1f6)]||'','argsJson':'','started':![]},this['tools']['set'](_0x17d187,_0x1c0bc2));if(_0x1ff851?.[_0x3589a2(0x1f6)])_0x1c0bc2[_0x3589a2(0x1b7)]=_0x1ff851[_0x3589a2(0x1f6)];!_0x1c0bc2['started']&&_0x1c0bc2['toolName']&&(_0x1c0bc2[_0x3589a2(0x1fd)]=!![],yield{'type':'tool_call_start','toolCallId':_0x1c0bc2[_0x3589a2(0x1c4)],'toolName':_0x1c0bc2['toolName']}),typeof _0x1ff851?.[_0x3589a2(0x198)]===_0x3589a2(0x1c8)&&_0x1ff851['arguments']['length']>0x0&&(_0x1c0bc2['argsJson']+=_0x1ff851[_0x3589a2(0x198)],_0x1c0bc2[_0x3589a2(0x1fd)]&&(yield{'type':_0x3589a2(0x1fc),'toolCallId':_0x1c0bc2[_0x3589a2(0x1c4)],'argsDelta':_0x1ff851[_0x3589a2(0x198)]}));}*[_0xfcd86a(0x1f7)](){const _0x5594df=_0xfcd86a,_0x52e3e8=[];if(this[_0x5594df(0x1bc)])_0x52e3e8[_0x5594df(0x1d3)]({'type':_0x5594df(0x1bc),'text':this['thinking']});if(this['text'])_0x52e3e8[_0x5594df(0x1d3)]({'type':_0x5594df(0x1de),'text':this[_0x5594df(0x1de)]});for(const _0x4dacd3 of this[_0x5594df(0x1cf)]['values']()){let _0x657402={};try{_0x657402=_0x4dacd3['argsJson']?JSON[_0x5594df(0x1e3)](_0x4dacd3[_0x5594df(0x1a5)]):{};}catch{_0x657402={'__raw':_0x4dacd3[_0x5594df(0x1a5)]};}_0x52e3e8[_0x5594df(0x1d3)]({'type':_0x5594df(0x1b5),'toolCallId':_0x4dacd3[_0x5594df(0x1c4)],'toolName':_0x4dacd3[_0x5594df(0x1b7)],'args':_0x657402}),yield{'type':_0x5594df(0x192),'toolCallId':_0x4dacd3[_0x5594df(0x1c4)],'toolName':_0x4dacd3[_0x5594df(0x1b7)],'args':_0x657402};}const _0x57c7a5={'role':_0x5594df(0x1b0),'content':_0x52e3e8,'usage':this[_0x5594df(0x1b9)],'stopReason':this[_0x5594df(0x1a6)]};yield{'type':'done','message':_0x57c7a5,'usage':this[_0x5594df(0x1b9)]};}}function buildRequestBody(_0x3fe084){const _0x1a7cbf=_0xfcd86a,_0x1fe3bb=convertMessages(_0x3fe084[_0x1a7cbf(0x1df)],_0x3fe084['systemPrompt']),_0x1723b4={'model':_0x3fe084[_0x1a7cbf(0x1d2)],'messages':_0x1fe3bb,'stream':!![],'stream_options':{'include_usage':!![]}},_0x41c654=openAiTokenField(_0x3fe084[_0x1a7cbf(0x1d2)]),_0x3bd565=_0x3fe084['modelLimits']?.[_0x1a7cbf(0x197)],_0x5b1fb4=resolveOutputTokens({'providerId':'openai','modelId':_0x3fe084[_0x1a7cbf(0x1d2)],..._0x3fe084[_0x1a7cbf(0x1ce)]!==undefined?{'requested':_0x3fe084[_0x1a7cbf(0x1ce)]}:{},..._0x3fe084[_0x1a7cbf(0x1be)]?{'modelLimits':_0x3fe084[_0x1a7cbf(0x1be)]}:{},..._0x3bd565!==undefined?{'estimatedPromptTokens':estimatePromptTokens(_0x3fe084[_0x1a7cbf(0x1df)],_0x3fe084[_0x1a7cbf(0x1a9)])}:{}});return _0x1723b4[_0x41c654]=_0x5b1fb4[_0x1a7cbf(0x1c7)],_0x3fe084['temperature']!==undefined&&_0x41c654===_0x1a7cbf(0x18f)&&(_0x1723b4[_0x1a7cbf(0x196)]=_0x3fe084[_0x1a7cbf(0x196)]),_0x3fe084[_0x1a7cbf(0x1e9)]&&_0x3fe084[_0x1a7cbf(0x1e9)]['length']>0x0&&(_0x1723b4[_0x1a7cbf(0x1e5)]=_0x3fe084[_0x1a7cbf(0x1e9)]),_0x3fe084['tools']&&_0x3fe084['tools'][_0x1a7cbf(0x1a8)]>0x0&&(_0x1723b4[_0x1a7cbf(0x1cf)]=_0x3fe084[_0x1a7cbf(0x1cf)][_0x1a7cbf(0x1c9)](convertToolDefinition)),_0x1723b4;}function convertMessages(_0x4ef035,_0x38edd7){const _0x40c530=_0xfcd86a,_0x5b749c=[];let _0x44d4ee=[];const _0x3ed9d2=()=>{const _0xc5c59b=_0x4c36;if(_0x44d4ee[_0xc5c59b(0x1a8)]===0x0)return;_0x5b749c[_0xc5c59b(0x1d3)](..._0x44d4ee),_0x44d4ee=[];};_0x38edd7&&_0x5b749c[_0x40c530(0x1d3)]({'role':_0x40c530(0x18a),'content':_0x38edd7});for(const _0x2d9036 of _0x4ef035){if(_0x2d9036[_0x40c530(0x1ba)]!==_0x40c530(0x1cb))_0x3ed9d2();switch(_0x2d9036[_0x40c530(0x1ba)]){case _0x40c530(0x1d6):_0x5b749c['push']({'role':_0x40c530(0x1d6),'content':typeof _0x2d9036['content']==='string'?_0x2d9036[_0x40c530(0x1cc)]:convertContentParts(_0x2d9036[_0x40c530(0x1cc)])});break;case _0x40c530(0x1b0):_0x5b749c[_0x40c530(0x1d3)](convertAssistantMessage(_0x2d9036));break;case _0x40c530(0x1cb):{const {text:_0x1fdbbe,images:_0x270f0a}=splitToolResultContent(_0x2d9036[_0x40c530(0x1cc)]);if(_0x270f0a[_0x40c530(0x1a8)]===0x0){_0x5b749c['push']({'role':_0x40c530(0x1a0),'tool_call_id':_0x2d9036['toolCallId'],'content':_0x1fdbbe});break;}_0x5b749c['push']({'role':_0x40c530(0x1a0),'tool_call_id':_0x2d9036[_0x40c530(0x1c4)],'content':withHandoffStub(_0x1fdbbe)}),_0x44d4ee['push']({'role':_0x40c530(0x1d6),'content':[{'type':_0x40c530(0x1de),'text':imageHandoffLabel(_0x2d9036[_0x40c530(0x1c4)],findToolName(_0x4ef035,_0x2d9036['toolCallId']))},...convertContentParts(_0x270f0a)]});break;}}}return _0x3ed9d2(),_0x5b749c;}function convertContentParts(_0x214a10){const _0x261aa7=_0xfcd86a;return _0x214a10[_0x261aa7(0x1c9)](_0x352b37=>{const _0x3745e9=_0x261aa7;if(_0x352b37[_0x3745e9(0x1c6)]==='text')return{'type':_0x3745e9(0x1de),'text':_0x352b37[_0x3745e9(0x1de)]};return{'type':_0x3745e9(0x1f3),'image_url':{'url':_0x3745e9(0x1d9)[_0x3745e9(0x1ab)](_0x352b37[_0x3745e9(0x1d4)],_0x3745e9(0x1ed))['concat'](_0x352b37[_0x3745e9(0x1fe)])}};});}function convertAssistantMessage(_0x1e02a7){const _0x25141f=_0xfcd86a,_0x4a2e71={'role':'assistant'},_0x5c09a1=_0x1e02a7['content']['filter'](_0x4b5d4d=>_0x4b5d4d[_0x25141f(0x1c6)]===_0x25141f(0x1de));_0x5c09a1[_0x25141f(0x1a8)]>0x0?_0x4a2e71[_0x25141f(0x1cc)]=_0x5c09a1['map'](_0x1dfc14=>_0x1dfc14[_0x25141f(0x1de)])[_0x25141f(0x1fb)](''):_0x4a2e71[_0x25141f(0x1cc)]=null;const _0x5e3445=_0x1e02a7[_0x25141f(0x1cc)][_0x25141f(0x1f0)](_0x12f7b1=>_0x12f7b1[_0x25141f(0x1c6)]===_0x25141f(0x1b5));return _0x5e3445[_0x25141f(0x1a8)]>0x0&&(_0x4a2e71[_0x25141f(0x1ec)]=_0x5e3445['map'](_0x47f0af=>({'id':_0x47f0af['toolCallId'],'type':_0x25141f(0x1f4),'function':{'name':_0x47f0af[_0x25141f(0x1b7)],'arguments':JSON[_0x25141f(0x1aa)](_0x47f0af[_0x25141f(0x186)])}}))),_0x4a2e71;}function convertToolDefinition(_0xfc6ce6){const _0x597d89=_0xfcd86a;return{'type':_0x597d89(0x1f4),'function':{'name':_0xfc6ce6[_0x597d89(0x1f6)],'description':_0xfc6ce6[_0x597d89(0x1b1)],'parameters':_0xfc6ce6[_0x597d89(0x1a1)]}};}function mapFinishReason(_0xa3bac8){const _0x29a605=_0xfcd86a;switch(_0xa3bac8){case'stop':return _0x29a605(0x1ca);case'tool_calls':return _0x29a605(0x1ee);case _0x29a605(0x1a8):return _0x29a605(0x18f);default:return'end_turn';}}
@@ -1,52 +1 @@
1
- /**
2
- * Shared helpers for tool results that carry pictures (agent-image-reading P1).
3
- *
4
- * INTERNAL: not exported from `index.ts` (a new runtime export would have to be mirrored in
5
- * the barrel, `public-api.test.ts` and `API.md`).
6
- *
7
- * Anthropic accepts images inside a `tool_result` block, so it does not need this module.
8
- * OpenAI Chat Completions (`role: 'tool'`) and Gemini (`functionResponse`) do not: for them
9
- * the text stays in the tool message and the pictures travel in a `user` message that follows
10
- * the whole run of consecutive tool results of that assistant turn.
11
- */
12
- /** Appended to the tool message text so the model knows the picture is not missing. */
13
- export const IMAGE_HANDOFF_STUB = '(the image follows in the next message)';
14
- /**
15
- * Split a tool result into the text the tool message carries and the images that must be
16
- * handed off. Text blocks are joined with `\n`, the same rule the agent loop uses to flatten
17
- * a text-only result; a plain string result has no images.
18
- */
19
- export function splitToolResultContent(content) {
20
- if (typeof content === 'string')
21
- return { text: content, images: [] };
22
- const texts = [];
23
- const images = [];
24
- for (const part of content) {
25
- if (part.type === 'text')
26
- texts.push(part.text);
27
- else
28
- images.push(part);
29
- }
30
- return { text: texts.join('\n'), images };
31
- }
32
- /** Tool message text for a result whose pictures are handed off: the text, then the stub. */
33
- export function withHandoffStub(text) {
34
- return `${text}${text ? '\n' : ''}${IMAGE_HANDOFF_STUB}`;
35
- }
36
- /** First text block of the follow-up user message: ties the pictures to their tool call. */
37
- export function imageHandoffLabel(toolCallId, toolName) {
38
- return `[Image returned by tool call ${toolCallId}${toolName ? ` (${toolName})` : ''}]`;
39
- }
40
- /** Name of the tool a result answers, or `undefined` when the call is not in the history. */
41
- export function findToolName(messages, toolCallId) {
42
- for (let index = messages.length - 1; index >= 0; index -= 1) {
43
- const message = messages[index];
44
- if (message.role !== 'assistant')
45
- continue;
46
- for (const block of message.content) {
47
- if (block.type === 'tool_call' && block.toolCallId === toolCallId)
48
- return block.toolName;
49
- }
50
- }
51
- return undefined;
52
- }
1
+ (function(_0x24a0fb,_0xf56f35){const _0x3b65e1=_0x240c,_0x439c1e=_0x24a0fb();while(!![]){try{const _0x2b6901=parseInt(_0x3b65e1(0x17d))/0x1*(parseInt(_0x3b65e1(0x180))/0x2)+parseInt(_0x3b65e1(0x17b))/0x3+-parseInt(_0x3b65e1(0x183))/0x4*(parseInt(_0x3b65e1(0x16e))/0x5)+-parseInt(_0x3b65e1(0x179))/0x6*(-parseInt(_0x3b65e1(0x173))/0x7)+-parseInt(_0x3b65e1(0x175))/0x8*(-parseInt(_0x3b65e1(0x17e))/0x9)+-parseInt(_0x3b65e1(0x16d))/0xa+parseInt(_0x3b65e1(0x16f))/0xb*(-parseInt(_0x3b65e1(0x17a))/0xc);if(_0x2b6901===_0xf56f35)break;else _0x439c1e['push'](_0x439c1e['shift']());}catch(_0x6a6fed){_0x439c1e['push'](_0x439c1e['shift']());}}}(_0x43a0,0xb5d00));export const IMAGE_HANDOFF_STUB='(the\x20image\x20follows\x20in\x20the\x20next\x20message)';function _0x240c(_0x13ae3b,_0x2e1558){_0x13ae3b=_0x13ae3b-0x16d;const _0x43a0d7=_0x43a0();let _0x240cbe=_0x43a0d7[_0x13ae3b];if(_0x240c['jELEum']===undefined){var _0x1e3bbd=function(_0x1c1962){const _0x4f81ea='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x5f0604='',_0x133b9a='';for(let _0x1acd79=0x0,_0x2f978f,_0x37cf2b,_0x7dd94d=0x0;_0x37cf2b=_0x1c1962['charAt'](_0x7dd94d++);~_0x37cf2b&&(_0x2f978f=_0x1acd79%0x4?_0x2f978f*0x40+_0x37cf2b:_0x37cf2b,_0x1acd79++%0x4)?_0x5f0604+=String['fromCharCode'](0xff&_0x2f978f>>(-0x2*_0x1acd79&0x6)):0x0){_0x37cf2b=_0x4f81ea['indexOf'](_0x37cf2b);}for(let _0x38242a=0x0,_0x5344fa=_0x5f0604['length'];_0x38242a<_0x5344fa;_0x38242a++){_0x133b9a+='%'+('00'+_0x5f0604['charCodeAt'](_0x38242a)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x133b9a);};_0x240c['doAusR']=_0x1e3bbd,_0x240c['EnhTmN']={},_0x240c['jELEum']=!![];}const _0x50e883=_0x43a0d7[0x0];_0x240c['hFrAtp']!==_0x50e883&&(_0x240c['EnhTmN']={},_0x240c['hFrAtp']=_0x50e883);const _0x138b1d=_0x240c['EnhTmN'][_0x13ae3b];return _0x138b1d===undefined?(_0x240cbe=_0x240c['doAusR'](_0x240cbe),_0x240c['EnhTmN'][_0x13ae3b]=_0x240cbe):_0x240cbe=_0x138b1d,_0x240cbe;}export function splitToolResultContent(_0x133b9a){const _0x3deec3=_0x240c;if(typeof _0x133b9a===_0x3deec3(0x172))return{'text':_0x133b9a,'images':[]};const _0x1acd79=[],_0x2f978f=[];for(const _0x37cf2b of _0x133b9a){if(_0x37cf2b[_0x3deec3(0x182)]===_0x3deec3(0x170))_0x1acd79['push'](_0x37cf2b[_0x3deec3(0x170)]);else _0x2f978f[_0x3deec3(0x181)](_0x37cf2b);}return{'text':_0x1acd79[_0x3deec3(0x184)]('\x0a'),'images':_0x2f978f};}export function withHandoffStub(_0x7dd94d){const _0x938553=_0x240c;return''[_0x938553(0x174)](_0x7dd94d)[_0x938553(0x174)](_0x7dd94d?'\x0a':'')[_0x938553(0x174)](IMAGE_HANDOFF_STUB);}function _0x43a0(){const _0x4daca9=['Dgv4Da','w0LTywDLihjLDhvYBMvKigj5ihrVB2WGy2fSBca','C3rYAw5N','ndjJEKrcAKK','y29Uy2f0','ndG0mdb4whLjCKG','Dg9VBenHBgXjza','BgvUz3rO','y29UDgvUDa','mZmZmZy2EK5pDKDp','mZzlAK9zB2S','mZuYmtCXoe5uBND1vW','yxnZAxn0yw50','mta0oteXn29pDvnbBG','oti3DxnxzgrK','Dg9VBf9JywXS','mMzKt0TqyG','ChvZAa','DhLWzq','mZGXnKXWEwDbsW','AM9PBG','nZKXotq4mgXgDNPewq','nte2mgXIyM5XsW','mJqXmZK4m1LNB3DUqW'];_0x43a0=function(){return _0x4daca9;};return _0x43a0();}export function imageHandoffLabel(_0x38242a,_0x5344fa){const _0x1e1d93=_0x240c;return _0x1e1d93(0x171)['concat'](_0x38242a)[_0x1e1d93(0x174)](_0x5344fa?'\x20('['concat'](_0x5344fa,')'):'',']');}export function findToolName(_0x3a3b92,_0x56ae16){const _0x14737e=_0x240c;for(let _0x25ad49=_0x3a3b92[_0x14737e(0x177)]-0x1;_0x25ad49>=0x0;_0x25ad49-=0x1){const _0x257886=_0x3a3b92[_0x25ad49];if(_0x257886['role']!==_0x14737e(0x17c))continue;for(const _0x3fe284 of _0x257886[_0x14737e(0x178)]){if(_0x3fe284[_0x14737e(0x182)]===_0x14737e(0x17f)&&_0x3fe284[_0x14737e(0x176)]===_0x56ae16)return _0x3fe284['toolName'];}}return undefined;}