@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,15 +1 @@
1
- /** Accept one batch atomically with respect to async work and receipt listeners. */
2
- export function acceptSteering(ctx) {
3
- if (ctx.signal.aborted)
4
- return;
5
- const items = ctx.messageQueueManager.drainSteeringItems();
6
- const ids = [];
7
- for (const item of items) {
8
- ctx.messageManager.push({ role: 'user', content: item.parts ?? item.text, timestamp: Date.now() });
9
- if (item.id !== undefined)
10
- ids.push(item.id);
11
- }
12
- // The entire batch must be in history before listeners can abort or enqueue more work.
13
- if (ids.length > 0)
14
- ctx.emit({ type: 'steering_accepted', ids });
15
- }
1
+ (function(_0x53c3bc,_0xa6794e){const _0x46c878=_0x49d5,_0x1be63a=_0x53c3bc();while(!![]){try{const _0x4bf92b=-parseInt(_0x46c878(0x149))/0x1+parseInt(_0x46c878(0x14e))/0x2*(parseInt(_0x46c878(0x142))/0x3)+-parseInt(_0x46c878(0x144))/0x4+parseInt(_0x46c878(0x13e))/0x5*(parseInt(_0x46c878(0x13c))/0x6)+parseInt(_0x46c878(0x146))/0x7*(-parseInt(_0x46c878(0x148))/0x8)+-parseInt(_0x46c878(0x14d))/0x9+parseInt(_0x46c878(0x13f))/0xa*(parseInt(_0x46c878(0x14b))/0xb);if(_0x4bf92b===_0xa6794e)break;else _0x1be63a['push'](_0x1be63a['shift']());}catch(_0x4ba751){_0x1be63a['push'](_0x1be63a['shift']());}}}(_0x25ad,0xe135d));function _0x49d5(_0x564f05,_0x3daecf){_0x564f05=_0x564f05-0x13b;const _0x25ad4c=_0x25ad();let _0x49d5c8=_0x25ad4c[_0x564f05];if(_0x49d5['dNxVOH']===undefined){var _0x14ea15=function(_0x5bc311){const _0x58f05d='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x140b6c='',_0x3b98bc='';for(let _0x536745=0x0,_0x48dced,_0xd78328,_0x5726e0=0x0;_0xd78328=_0x5bc311['charAt'](_0x5726e0++);~_0xd78328&&(_0x48dced=_0x536745%0x4?_0x48dced*0x40+_0xd78328:_0xd78328,_0x536745++%0x4)?_0x140b6c+=String['fromCharCode'](0xff&_0x48dced>>(-0x2*_0x536745&0x6)):0x0){_0xd78328=_0x58f05d['indexOf'](_0xd78328);}for(let _0x285eed=0x0,_0x45ac31=_0x140b6c['length'];_0x285eed<_0x45ac31;_0x285eed++){_0x3b98bc+='%'+('00'+_0x140b6c['charCodeAt'](_0x285eed)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x3b98bc);};_0x49d5['yuAWPS']=_0x14ea15,_0x49d5['jiKgFF']={},_0x49d5['dNxVOH']=!![];}const _0x1b5c28=_0x25ad4c[0x0];_0x49d5['iJzvWm']!==_0x1b5c28&&(_0x49d5['jiKgFF']={},_0x49d5['iJzvWm']=_0x1b5c28);const _0x1d88b1=_0x49d5['jiKgFF'][_0x564f05];return _0x1d88b1===undefined?(_0x49d5c8=_0x49d5['yuAWPS'](_0x49d5c8),_0x49d5['jiKgFF'][_0x564f05]=_0x49d5c8):_0x49d5c8=_0x1d88b1,_0x49d5c8;}export function acceptSteering(_0x3b98bc){const _0x22b664=_0x49d5;if(_0x3b98bc[_0x22b664(0x140)]['aborted'])return;const _0x536745=_0x3b98bc[_0x22b664(0x13b)][_0x22b664(0x147)](),_0x48dced=[];for(const _0xd78328 of _0x536745){_0x3b98bc['messageManager'][_0x22b664(0x14f)]({'role':_0x22b664(0x143),'content':_0xd78328[_0x22b664(0x13d)]??_0xd78328['text'],'timestamp':Date[_0x22b664(0x14a)]()});if(_0xd78328['id']!==undefined)_0x48dced['push'](_0xd78328['id']);}if(_0x48dced[_0x22b664(0x14c)]>0x0)_0x3b98bc[_0x22b664(0x141)]({'type':_0x22b664(0x145),'ids':_0x48dced});}function _0x25ad(){const _0x59638b=['C2LNBMfS','zw1PDa','otKZmhPdzMLyra','DxnLCG','ntq0nJy4nhjOAhzvAq','C3rLzxjPBMDFywnJzxb0zwq','mtC1rxfPzu5W','zhjHAw5tDgvLCMLUz0L0zw1Z','ndu5mteYAxvzExfW','mJGZmtu1EhPysgju','BM93','mZyZzMPLALzx','BgvUz3rO','nZuZmZaXofvXqMfUta','nte0CeTtrNPk','ChvZAa','BwvZC2fNzvf1zxvLtwfUywDLCG','mJG0nJq0mLjrt3D1DW','CgfYDhm','mtvfzKL2zhC','nZC3mZeWB0fsAunc'];_0x25ad=function(){return _0x59638b;};return _0x25ad();}
@@ -1,533 +1 @@
1
- /**
2
- * Core Agent Loop — the heart of the engine.
3
- *
4
- * Implements the LLM call -> stream consumption -> tool execution -> loop
5
- * cycle, with steering/follow-up checkpoints and optional CodeAct code
6
- * block detection and execution.
7
- */
8
- import { validateHistory } from './compaction.js';
9
- import { acceptSteering } from './accept-steering.js';
10
- import { estimatePromptTokens } from '../llm/output-limits.js';
11
- import { toToolResultMessageContent } from './tool-result-content.js';
12
- // ---------------------------------------------------------------------------
13
- // Compaction checkpoint (context-auto-compaction §3.3)
14
- // ---------------------------------------------------------------------------
15
- /**
16
- * A CEILING, NOT A POLICY (P1-3). It must sit STRICTLY ABOVE the largest wall
17
- * clock a well-behaved host can legitimately spend, or it starts firing on
18
- * correct hosts and the failure ladder's rungs stop being reachable. The CLI's
19
- * worst legal case is two `callTimeoutMs` calls back to back (45 s + 45 s = 90 s)
20
- * plus the digest render, so 90 s would be exactly the boundary — this is 120 s,
21
- * leaving 30 s of slack.
22
- *
23
- * It is deliberately longer than `DEFAULT_IDLE_TIMEOUT` (60 s): `compaction_start`
24
- * PAUSES the watchdog, so across this call this is the only clock running. An
25
- * `await` with no ceiling here would be strictly worse than the pre-feature
26
- * behaviour — a host that returns a non-settling promise would hang the run AND
27
- * there would be nothing left to notice.
28
- */
29
- export const COMPACTION_HARD_TIMEOUT_MS = 120_000;
30
- function errText(err) {
31
- return err instanceof Error ? err.message : String(err);
32
- }
33
- /**
34
- * Coerce whatever the host resolved with into a `CompactionOutcome`.
35
- *
36
- * THE TYPE IS NOT THE GUARANTEE (implementation finding IF-2). `ContextManager`
37
- * is an interface a host implements in its own package, so at this boundary the
38
- * value is untyped at runtime: a stub, a mock, a host that forgot a `return`, or
39
- * a `Promise<void>` all arrive here as `undefined`. Reading `.action` off that
40
- * throws OUTSIDE the inner `catch` — after `compaction_end` has been emitted from
41
- * the `finally`, so the watchdog is correctly resumed, but the throw still
42
- * escapes `runCompaction` and kills the run.
43
- *
44
- * That is exactly the failure §3.3 step 4 says must not happen: "a host that
45
- * breaks its own contract must degrade to 'compaction did not happen', never to
46
- * 'the run died'". The inner `catch` covers a REJECTED promise; this covers a
47
- * promise that resolves with the wrong thing, which is the commoner mistake.
48
- */
49
- function normalizeOutcome(value) {
50
- const outcome = value;
51
- if (!outcome || typeof outcome !== 'object') {
52
- return { action: 'keep', reason: 'manager_bad_outcome' };
53
- }
54
- if (outcome.action === 'replace') {
55
- if (!Array.isArray(outcome.messages)) {
56
- return { action: 'keep', reason: 'manager_bad_outcome' };
57
- }
58
- return outcome;
59
- }
60
- if (outcome.action === 'keep')
61
- return outcome;
62
- return { action: 'keep', reason: 'manager_bad_outcome' };
63
- }
64
- /**
65
- * Race the host's promise against the run's signal and a hard ceiling.
66
- *
67
- * RESOLVES rather than rejects on both loss conditions, so the two ladder rungs
68
- * stay distinguishable in the event and in the log. The losing promise is left
69
- * to settle on its own; its result is dropped, and it cannot reach `restore`
70
- * because `applied` is decided by the caller.
71
- */
72
- async function raceCompaction(work, signal, timeoutMs) {
73
- if (signal.aborted)
74
- return { action: 'keep', reason: 'aborted' };
75
- let timer;
76
- let onAbort;
77
- try {
78
- return await Promise.race([
79
- work,
80
- new Promise((resolve) => {
81
- timer = setTimeout(() => resolve({ action: 'keep', reason: 'manager_timeout' }), timeoutMs);
82
- }),
83
- new Promise((resolve) => {
84
- onAbort = () => resolve({ action: 'keep', reason: 'aborted' });
85
- signal.addEventListener('abort', onAbort, { once: true });
86
- }),
87
- ]);
88
- }
89
- finally {
90
- if (timer !== undefined)
91
- clearTimeout(timer);
92
- if (onAbort)
93
- signal.removeEventListener('abort', onAbort);
94
- }
95
- }
96
- /**
97
- * One compaction checkpoint. Returns whether a new history was ADOPTED.
98
- *
99
- * Five steps, and step 5 is the whole reason the engine is involved at all
100
- * (D-4): the host proposes, the engine validates, and an invalid history is
101
- * refused rather than adopted.
102
- */
103
- async function runCompaction(ctx, params) {
104
- const cm = ctx.contextManager;
105
- if (!cm)
106
- return false; // 1. off: zero cost, zero allocation
107
- const probe = {
108
- messageCount: ctx.messageManager.length,
109
- trigger: params.trigger,
110
- turnIndex: params.turnIndex,
111
- ...(params.lastUsage ? { lastUsage: params.lastUsage } : {}),
112
- };
113
- let wanted = false;
114
- try {
115
- wanted = cm.shouldCompact(probe); // 2. sync gate
116
- }
117
- catch (err) {
118
- // A throwing predicate is a host bug, and it must not take the run down.
119
- ctx.emit({ type: 'compaction_start', trigger: params.trigger, messageCount: probe.messageCount });
120
- ctx.emit({
121
- type: 'compaction_end',
122
- applied: false,
123
- mode: 'none',
124
- reason: `manager_threw: ${errText(err)}`,
125
- messagesBefore: probe.messageCount,
126
- messagesAfter: probe.messageCount,
127
- droppedMessages: 0,
128
- estimatedTokensBefore: 0,
129
- estimatedTokensAfter: 0,
130
- durationMs: 0,
131
- });
132
- return false;
133
- }
134
- if (!wanted)
135
- return false;
136
- // A SHALLOW COPY, NOT THE LIVE ARRAY (P1-2). `getAll()` hands back the internal
137
- // array; `as Message[]` would launder away the only thing stopping a host from
138
- // mutating engine state in place, before step 5 can see it.
139
- const before = [...ctx.messageManager.getAll()];
140
- const estimatedTokensBefore = estimatePromptTokens(before, ctx.systemPrompt);
141
- // 3. Pauses the watchdog (`Agent.applyWatchdogPolicy`), applied BEFORE the
142
- // listeners so a subscriber that throws cannot leave the run armed.
143
- ctx.emit({ type: 'compaction_start', trigger: params.trigger, messageCount: before.length });
144
- const started = Date.now();
145
- let applied = false;
146
- let mode = 'none';
147
- let reason;
148
- let summary;
149
- let after = before;
150
- try {
151
- let outcome;
152
- try {
153
- // 4. BOUNDED AND RACED, because step 3 just switched the idle detector off.
154
- // NORMALIZED, because the interface is not enforced at this boundary.
155
- outcome = normalizeOutcome(await raceCompaction(cm.compact({
156
- ...probe,
157
- messages: before,
158
- systemPrompt: ctx.systemPrompt,
159
- model: ctx.model,
160
- signal: ctx.signal,
161
- }), ctx.signal, params.hardTimeoutMs ?? ctx.timeouts.compactionHardTimeout ?? COMPACTION_HARD_TIMEOUT_MS));
162
- }
163
- catch (err) {
164
- outcome = { action: 'keep', reason: `manager_threw: ${errText(err)}` };
165
- }
166
- if (outcome.action === 'keep') {
167
- reason = outcome.reason;
168
- }
169
- else {
170
- // 5. THE STRUCTURAL GATE. Positional `previousLength` keeps the `grew`
171
- // rung live.
172
- const check = validateHistory(outcome.messages, { previousLength: before.length });
173
- if (check.ok) {
174
- ctx.messageManager.restore(outcome.messages);
175
- after = outcome.messages;
176
- applied = true;
177
- mode = outcome.mode;
178
- summary = outcome.summary;
179
- reason = outcome.reason;
180
- }
181
- else {
182
- reason = `invalid_history: ${check.reason}`;
183
- }
184
- }
185
- }
186
- finally {
187
- // IN A `finally`. `compaction_end` is what RESUMES the watchdog, so it must
188
- // be emitted on every exit from this function — including a `throw` that
189
- // escapes the two guards above. A compaction that failed to emit its `end`
190
- // leaves the run permanently deaf.
191
- ctx.emit({
192
- type: 'compaction_end',
193
- applied,
194
- mode,
195
- ...(reason !== undefined ? { reason } : {}),
196
- messagesBefore: before.length,
197
- messagesAfter: after.length,
198
- droppedMessages: Math.max(0, before.length - after.length),
199
- estimatedTokensBefore,
200
- estimatedTokensAfter: applied
201
- ? estimatePromptTokens(after, ctx.systemPrompt)
202
- : estimatedTokensBefore,
203
- ...(summary !== undefined ? { summary } : {}),
204
- durationMs: Date.now() - started,
205
- });
206
- }
207
- return applied;
208
- }
209
- // ---------------------------------------------------------------------------
210
- // CodeAct regex for extracting ```execute-js blocks
211
- // ---------------------------------------------------------------------------
212
- const CODEACT_REGEX = /```execute-js\n([\s\S]*?)```/g;
213
- /**
214
- * Extract all execute-js code blocks from assistant text.
215
- */
216
- function extractCodeBlocks(text) {
217
- const blocks = [];
218
- let match;
219
- // Reset lastIndex for safety when reusing the regex.
220
- CODEACT_REGEX.lastIndex = 0;
221
- while ((match = CODEACT_REGEX.exec(text)) !== null) {
222
- const code = match[1];
223
- if (code && code.trim().length > 0) {
224
- blocks.push(code);
225
- }
226
- }
227
- return blocks;
228
- }
229
- /**
230
- * Collect all text content from an AssistantMessage's content blocks.
231
- */
232
- function getAssistantText(message) {
233
- return message.content
234
- .filter((b) => b.type === 'text')
235
- .map((b) => b.text)
236
- .join('\n');
237
- }
238
- /**
239
- * Collect tool call blocks from an AssistantMessage.
240
- */
241
- function getToolCalls(message) {
242
- return message.content.filter((b) => b.type === 'tool_call');
243
- }
244
- /** Close the outstanding tool batch before steering creates the next user turn. */
245
- function acceptToolSteering(ctx, remainingCalls) {
246
- if (ctx.signal.aborted || !ctx.messageQueueManager.hasSteering())
247
- return false;
248
- for (const skipped of remainingCalls) {
249
- ctx.messageManager.push({
250
- role: 'tool_result',
251
- toolCallId: skipped.toolCallId,
252
- content: 'Tool execution skipped due to steering interrupt.',
253
- isError: true,
254
- });
255
- }
256
- acceptSteering(ctx);
257
- return true;
258
- }
259
- // ---------------------------------------------------------------------------
260
- // runAgentLoop
261
- // ---------------------------------------------------------------------------
262
- /**
263
- * Run the Agent loop until completion, steering exhaustion, or abort.
264
- *
265
- * This function is invoked by `Agent.prompt()` and `Agent.continue()`.
266
- * It mutates the messageManager and emits events through the provided
267
- * context. All errors are caught — the caller (Agent) is responsible
268
- * for emitting `agent_end` in its own finally block.
269
- */
270
- export async function runAgentLoop(ctx) {
271
- // ----- Compaction bookkeeping (context-auto-compaction §3.3) --------------
272
- //
273
- // ALL THREE ARE HOISTED ABOVE THE `while`, and only two of them are ever reset
274
- // inside it — after a stream COMPLETES, never at the top of the loop.
275
- /** Authoritative usage of the most recently completed turn (P1-1). */
276
- let lastUsage;
277
- /** 1-based, ONE PER ITERATION — guard 1's cooldown unit (P2-1). */
278
- let turnIndex = 0;
279
- /** NOT RESET AT THE TOP OF THE LOOP (P0-1). See the note at `turn_end`. */
280
- let overflowRecovered = false;
281
- while (!ctx.signal.aborted) {
282
- // ----- Steering checkpoint (before LLM call) -----
283
- acceptSteering(ctx);
284
- turnIndex += 1;
285
- // ----- Context pressure checkpoint (context-auto-compaction §3.3) -----
286
- //
287
- // PLACEMENT IS LOAD-BEARING IN THREE WAYS.
288
- // 1. AFTER the steering drain, so a message the user just steered in is
289
- // part of the history being measured and is inside the retained tail by
290
- // construction (it is the newest message).
291
- // 2. BEFORE `turn_start`, so the UI reads compaction as a phase of its own
292
- // rather than as a stall inside a turn.
293
- // 3. INSIDE the `while`, not before it. A run that starts under the
294
- // threshold and crosses it at turn 12 is the normal case, and it is the
295
- // case an `agent_end`-based design cannot serve at all (D-1).
296
- if (await runCompaction(ctx, { trigger: 'pressure', lastUsage, turnIndex })) {
297
- lastUsage = undefined;
298
- }
299
- if (ctx.signal.aborted)
300
- break;
301
- // ----- Turn start -----
302
- ctx.emit({ type: 'turn_start' });
303
- // ----- Build LLM request -----
304
- const apiKey = ctx.getApiKey(ctx.model.providerId);
305
- if (!apiKey) {
306
- throw new Error(`No API key available for provider "${ctx.model.providerId}". ` +
307
- 'Please configure the API key in Settings.');
308
- }
309
- const toolDefs = ctx.toolRegistry.toToolDefinitions();
310
- const stored = ctx.messageManager.getAll();
311
- const messages = ctx.projectMessages
312
- ? ctx.projectMessages(stored)
313
- : stored;
314
- // ----- Stream LLM response -----
315
- let assistantMessage;
316
- let usage = { inputTokens: 0, outputTokens: 0 };
317
- const stream = ctx.providerRegistry.stream(ctx.model.providerId, {
318
- model: ctx.model.modelId,
319
- messages,
320
- systemPrompt: ctx.systemPrompt,
321
- tools: toolDefs.length > 0 ? toolDefs : undefined,
322
- apiKey,
323
- baseUrl: ctx.model.baseUrl,
324
- signal: ctx.signal,
325
- ...(ctx.timeouts.idleTimeout !== undefined
326
- ? { idleWatchdogMs: ctx.timeouts.idleTimeout }
327
- : {}),
328
- thinkingLevel: ctx.thinkingLevel,
329
- maxTokens: ctx.maxTokens,
330
- // THE ONLY PLACE IN THE WHOLE REPOSITORY THAT SETS `retryEscalation`
331
- // (tiered-reconnect §4.4, pinned by a source scan in AC-12). Both keys stay
332
- // absent when the host did not opt in, so the request body is unchanged.
333
- ...(ctx.escalation?.policy ? { retryEscalation: ctx.escalation.policy } : {}),
334
- ...(ctx.escalation?.startRung ? { startRung: ctx.escalation.startRung } : {}),
335
- });
336
- try {
337
- for await (const event of stream) {
338
- if (ctx.signal.aborted)
339
- break;
340
- // Forward every stream event to subscribers.
341
- ctx.emit({ type: 'message_update', streamEvent: event });
342
- if (event.type === 'done') {
343
- assistantMessage = event.message;
344
- usage = event.usage;
345
- }
346
- else if (event.type === 'error') {
347
- throw event.error;
348
- }
349
- }
350
- }
351
- catch (err) {
352
- // ----- Reactive compaction (context-auto-compaction §3.5) -----
353
- //
354
- // The static context window is a GUESS for anything the table has not seen
355
- // (`buildRuntimeModel` returns 128 000 for every unknown model), so a proxy
356
- // in front of a 32 k model refuses the request before the proactive trigger
357
- // could ever fire. One recovery turns that from a dead run into a re-send.
358
- //
359
- // STRUCTURAL CHECK, NOT `instanceof LLMError`: the error may have crossed a
360
- // module boundary or been rebuilt, and an identity check on the class is the
361
- // version of this test that fails in production and passes in the unit test
362
- // (`retry.ts::isRetryableError` records the same reasoning).
363
- const errorType = err?.errorType;
364
- if (errorType !== 'context_overflow' || overflowRecovered || !ctx.contextManager)
365
- throw err;
366
- overflowRecovered = true;
367
- const recovered = await runCompaction(ctx, { trigger: 'overflow', lastUsage, turnIndex });
368
- if (recovered)
369
- lastUsage = undefined;
370
- if (!recovered)
371
- throw err;
372
- if (ctx.signal.aborted)
373
- break;
374
- continue; // re-send this turn against the compacted history
375
- }
376
- if (ctx.signal.aborted)
377
- break;
378
- if (!assistantMessage) {
379
- // Stream ended without a 'done' event — treat as an error.
380
- throw new Error('LLM stream ended without producing a done event');
381
- }
382
- // ----- Turn end -----
383
- ctx.emit({ type: 'turn_end', message: assistantMessage, usage });
384
- // THE TWO LINES THE COMPACTION PROBE DEPENDS ON, and both are cleared HERE
385
- // rather than at the top of the loop.
386
- //
387
- // Without the first, `lastUsage` is forever `undefined`, every trigger runs
388
- // on the crude estimate, and the status bar and the trigger diverge — the
389
- // exact defect the shared `occupiedTokens` exists to close, reintroduced
390
- // silently (P1-1).
391
- //
392
- // Without the second — or with it moved to the top of the `while` — the
393
- // one-shot overflow guard would not exist at all: §3.5's recovery ends in
394
- // `continue`, which re-enters the loop, so a top-of-loop reset would clear
395
- // the flag on the way back in and a session whose tail alone cannot fit
396
- // would compact on every pass (P0-1). Clearing it after a stream COMPLETES
397
- // is the correct expression of the intent: the flag means "this turn has
398
- // already spent its one overflow recovery", and a turn that never produced a
399
- // `done` event has not finished.
400
- lastUsage = usage;
401
- overflowRecovered = false;
402
- ctx.messageManager.push(assistantMessage);
403
- if (ctx.signal.aborted)
404
- break;
405
- // ----- Process tool calls -----
406
- const toolCalls = getToolCalls(assistantMessage);
407
- const hasToolCalls = toolCalls.length > 0;
408
- let steeringInterrupted = false;
409
- if (hasToolCalls) {
410
- // Steering checkpoint: if steering arrived during the LLM call,
411
- // skip tool execution and inject steering messages instead.
412
- if (acceptToolSteering(ctx, toolCalls)) {
413
- // Loop continues — LLM will see the steering messages.
414
- continue;
415
- }
416
- // Execute each tool call sequentially.
417
- for (const toolCall of toolCalls) {
418
- if (ctx.signal.aborted)
419
- break;
420
- // Check steering between individual tool executions.
421
- if (acceptToolSteering(ctx, toolCalls.slice(toolCalls.indexOf(toolCall)))) {
422
- steeringInterrupted = true;
423
- break;
424
- }
425
- ctx.emit({
426
- type: 'tool_execution_start',
427
- toolCallId: toolCall.toolCallId,
428
- toolName: toolCall.toolName,
429
- args: toolCall.args,
430
- });
431
- const execResult = await ctx.toolExecutor.execute(toolCall.toolCallId, toolCall.toolName, toolCall.args, ctx.signal);
432
- ctx.emit({
433
- type: 'tool_execution_end',
434
- toolCallId: toolCall.toolCallId,
435
- toolName: toolCall.toolName,
436
- result: execResult.result,
437
- isError: execResult.isError,
438
- duration: execResult.duration,
439
- });
440
- // Build and push tool result message. Images in a successful result are kept
441
- // (agent-image-reading); text-only and error results flatten exactly as before.
442
- ctx.messageManager.push({
443
- role: 'tool_result',
444
- toolCallId: toolCall.toolCallId,
445
- content: toToolResultMessageContent(execResult.result, execResult.isError),
446
- isError: execResult.isError,
447
- });
448
- }
449
- if (ctx.signal.aborted)
450
- break;
451
- // If steering interrupted tool execution, skip CodeAct and continue
452
- // to the next loop iteration where the LLM sees the steering messages.
453
- if (steeringInterrupted)
454
- continue;
455
- }
456
- // ----- CodeAct code block detection -----
457
- const assistantText = getAssistantText(assistantMessage);
458
- const codeBlocks = extractCodeBlocks(assistantText);
459
- let hasCodeBlocks = codeBlocks.length > 0 && ctx.sandbox != null;
460
- if (hasCodeBlocks && ctx.sandbox) {
461
- for (const code of codeBlocks) {
462
- if (ctx.signal.aborted)
463
- break;
464
- ctx.emit({ type: 'code_execution_start', code, language: 'javascript' });
465
- const startTime = Date.now();
466
- let output = '';
467
- let error;
468
- try {
469
- const result = await ctx.sandbox.execute(code, {
470
- timeout: ctx.timeouts.codeTimeout,
471
- signal: ctx.signal,
472
- });
473
- // Build output from console entries and return value.
474
- const parts = [];
475
- for (const entry of result.consoleOutput) {
476
- const prefix = entry.level === 'log' ? '' : `[${entry.level}] `;
477
- parts.push(`${prefix}${entry.args.join(' ')}`);
478
- }
479
- if (result.returnValue !== undefined) {
480
- parts.push(`=> ${result.returnValue}`);
481
- }
482
- output = parts.join('\n');
483
- error = result.error?.message;
484
- }
485
- catch (err) {
486
- error = err instanceof Error ? err.message : String(err);
487
- }
488
- const duration = Date.now() - startTime;
489
- ctx.emit({ type: 'code_execution_end', output, error, duration });
490
- // Inject code execution result as a user message.
491
- let resultContent = '[Code Execution Result]\n';
492
- if (output) {
493
- resultContent += `Output: ${output}\n`;
494
- }
495
- if (error) {
496
- resultContent += `---\nError: ${error}\n`;
497
- }
498
- if (!output && !error) {
499
- resultContent += 'Output: (no output)\n';
500
- }
501
- const codeResultMsg = {
502
- role: 'user',
503
- content: resultContent,
504
- timestamp: Date.now(),
505
- };
506
- ctx.messageManager.push(codeResultMsg);
507
- }
508
- if (ctx.signal.aborted)
509
- break;
510
- // After code execution, continue the loop so LLM can react to results.
511
- continue;
512
- }
513
- // ----- Exit or follow-up checkpoint -----
514
- if (!hasToolCalls && !hasCodeBlocks) {
515
- // Give streaming and turn_end steering priority over follow-up and normal exit.
516
- if (ctx.messageQueueManager.hasSteering())
517
- continue;
518
- if (ctx.messageQueueManager.hasFollowUp()) {
519
- const followUpMessages = ctx.messageQueueManager.drainFollowUp();
520
- for (const text of followUpMessages) {
521
- const userMsg = { role: 'user', content: text, timestamp: Date.now() };
522
- ctx.messageManager.push(userMsg);
523
- }
524
- // Continue loop with follow-up messages.
525
- continue;
526
- }
527
- // No more work — exit the loop.
528
- break;
529
- }
530
- // If we had tool calls (and they were executed), continue the loop
531
- // so the LLM can process tool results.
532
- }
533
- }
1
+ (function(_0x58bcd9,_0xf9d783){const _0x5efe8a=_0x2c60,_0x35b53f=_0x58bcd9();while(!![]){try{const _0x28f30c=parseInt(_0x5efe8a(0x1e9))/0x1+-parseInt(_0x5efe8a(0x1cc))/0x2*(parseInt(_0x5efe8a(0x1d8))/0x3)+parseInt(_0x5efe8a(0x1a0))/0x4*(-parseInt(_0x5efe8a(0x1c2))/0x5)+-parseInt(_0x5efe8a(0x17f))/0x6+-parseInt(_0x5efe8a(0x1e6))/0x7*(-parseInt(_0x5efe8a(0x197))/0x8)+parseInt(_0x5efe8a(0x19d))/0x9*(-parseInt(_0x5efe8a(0x1be))/0xa)+-parseInt(_0x5efe8a(0x1bd))/0xb*(-parseInt(_0x5efe8a(0x1d3))/0xc);if(_0x28f30c===_0xf9d783)break;else _0x35b53f['push'](_0x35b53f['shift']());}catch(_0x1b113f){_0x35b53f['push'](_0x35b53f['shift']());}}}(_0x27ab,0x6fe05));import{validateHistory}from'./compaction.js';import{acceptSteering}from'./accept-steering.js';import{estimatePromptTokens}from'../llm/output-limits.js';function _0x2c60(_0x314d6c,_0xb3c21b){_0x314d6c=_0x314d6c-0x17b;const _0x27abaa=_0x27ab();let _0x2c60c2=_0x27abaa[_0x314d6c];if(_0x2c60['jsPute']===undefined){var _0x368bf0=function(_0xc75b65){const _0x5775c7='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x1bec8e='',_0x111e43='';for(let _0x30c047=0x0,_0x56e82c,_0x3ebc94,_0x61bdec=0x0;_0x3ebc94=_0xc75b65['charAt'](_0x61bdec++);~_0x3ebc94&&(_0x56e82c=_0x30c047%0x4?_0x56e82c*0x40+_0x3ebc94:_0x3ebc94,_0x30c047++%0x4)?_0x1bec8e+=String['fromCharCode'](0xff&_0x56e82c>>(-0x2*_0x30c047&0x6)):0x0){_0x3ebc94=_0x5775c7['indexOf'](_0x3ebc94);}for(let _0x2dfddc=0x0,_0x464d06=_0x1bec8e['length'];_0x2dfddc<_0x464d06;_0x2dfddc++){_0x111e43+='%'+('00'+_0x1bec8e['charCodeAt'](_0x2dfddc)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x111e43);};_0x2c60['uwbtIM']=_0x368bf0,_0x2c60['tXEjkz']={},_0x2c60['jsPute']=!![];}const _0x35d657=_0x27abaa[0x0];_0x2c60['ozkWIq']!==_0x35d657&&(_0x2c60['tXEjkz']={},_0x2c60['ozkWIq']=_0x35d657);const _0x16a571=_0x2c60['tXEjkz'][_0x314d6c];return _0x16a571===undefined?(_0x2c60c2=_0x2c60['uwbtIM'](_0x2c60c2),_0x2c60['tXEjkz'][_0x314d6c]=_0x2c60c2):_0x2c60c2=_0x16a571,_0x2c60c2;}import{toToolResultMessageContent}from'./tool-result-content.js';export const COMPACTION_HARD_TIMEOUT_MS=0x1d4c0;function errText(_0x111e43){const _0xf678b=_0x2c60;return _0x111e43 instanceof Error?_0x111e43[_0xf678b(0x1ad)]:String(_0x111e43);}function normalizeOutcome(_0x30c047){const _0x2ff455=_0x2c60,_0x56e82c=_0x30c047;if(!_0x56e82c||typeof _0x56e82c!=='object')return{'action':_0x2ff455(0x1dd),'reason':_0x2ff455(0x196)};if(_0x56e82c['action']===_0x2ff455(0x1b5)){if(!Array[_0x2ff455(0x1a1)](_0x56e82c['messages']))return{'action':_0x2ff455(0x1dd),'reason':_0x2ff455(0x196)};return _0x56e82c;}if(_0x56e82c[_0x2ff455(0x1a6)]===_0x2ff455(0x1dd))return _0x56e82c;return{'action':'keep','reason':_0x2ff455(0x196)};}async function raceCompaction(_0x3ebc94,_0x61bdec,_0x2dfddc){const _0x304255=_0x2c60;if(_0x61bdec[_0x304255(0x1b7)])return{'action':_0x304255(0x1dd),'reason':'aborted'};let _0x464d06,_0x5e0d9a;try{return await Promise[_0x304255(0x195)]([_0x3ebc94,new Promise(_0x443e0a=>{_0x464d06=setTimeout(()=>_0x443e0a({'action':'keep','reason':'manager_timeout'}),_0x2dfddc);}),new Promise(_0x4b4773=>{const _0x2f93a9=_0x304255;_0x5e0d9a=()=>_0x4b4773({'action':_0x2f93a9(0x1dd),'reason':_0x2f93a9(0x1b7)}),_0x61bdec[_0x2f93a9(0x1ce)]('abort',_0x5e0d9a,{'once':!![]});})]);}finally{if(_0x464d06!==undefined)clearTimeout(_0x464d06);if(_0x5e0d9a)_0x61bdec[_0x304255(0x1aa)](_0x304255(0x18a),_0x5e0d9a);}}async function runCompaction(_0x736767,_0x554240){const _0x4d2d60=_0x2c60,_0x3f0d31=_0x736767[_0x4d2d60(0x1e2)];if(!_0x3f0d31)return![];const _0xffe8d8={'messageCount':_0x736767[_0x4d2d60(0x1df)]['length'],'trigger':_0x554240['trigger'],'turnIndex':_0x554240[_0x4d2d60(0x1de)],..._0x554240[_0x4d2d60(0x1cb)]?{'lastUsage':_0x554240['lastUsage']}:{}};let _0x14e943=![];try{_0x14e943=_0x3f0d31['shouldCompact'](_0xffe8d8);}catch(_0x5475f6){return _0x736767[_0x4d2d60(0x183)]({'type':'compaction_start','trigger':_0x554240[_0x4d2d60(0x1ab)],'messageCount':_0xffe8d8[_0x4d2d60(0x19c)]}),_0x736767[_0x4d2d60(0x183)]({'type':_0x4d2d60(0x1af),'applied':![],'mode':'none','reason':_0x4d2d60(0x1a4)['concat'](errText(_0x5475f6)),'messagesBefore':_0xffe8d8[_0x4d2d60(0x19c)],'messagesAfter':_0xffe8d8[_0x4d2d60(0x19c)],'droppedMessages':0x0,'estimatedTokensBefore':0x0,'estimatedTokensAfter':0x0,'durationMs':0x0}),![];}if(!_0x14e943)return![];const _0x211e1d=[..._0x736767[_0x4d2d60(0x1df)]['getAll']()],_0x2938e1=estimatePromptTokens(_0x211e1d,_0x736767[_0x4d2d60(0x1e1)]);_0x736767['emit']({'type':_0x4d2d60(0x1ae),'trigger':_0x554240[_0x4d2d60(0x1ab)],'messageCount':_0x211e1d[_0x4d2d60(0x1a3)]});const _0x5a8610=Date[_0x4d2d60(0x1a5)]();let _0xc16aab=![],_0x595a1a='none',_0x283c5e,_0x33f8d2,_0x45171f=_0x211e1d;try{let _0x694d15;try{_0x694d15=normalizeOutcome(await raceCompaction(_0x3f0d31[_0x4d2d60(0x18e)]({..._0xffe8d8,'messages':_0x211e1d,'systemPrompt':_0x736767[_0x4d2d60(0x1e1)],'model':_0x736767['model'],'signal':_0x736767['signal']}),_0x736767['signal'],_0x554240[_0x4d2d60(0x19b)]??_0x736767[_0x4d2d60(0x1c8)][_0x4d2d60(0x1c1)]??COMPACTION_HARD_TIMEOUT_MS));}catch(_0x15393b){_0x694d15={'action':_0x4d2d60(0x1dd),'reason':_0x4d2d60(0x1a4)[_0x4d2d60(0x184)](errText(_0x15393b))};}if(_0x694d15[_0x4d2d60(0x1a6)]===_0x4d2d60(0x1dd))_0x283c5e=_0x694d15['reason'];else{const _0x5eecef=validateHistory(_0x694d15[_0x4d2d60(0x1b3)],{'previousLength':_0x211e1d[_0x4d2d60(0x1a3)]});_0x5eecef['ok']?(_0x736767[_0x4d2d60(0x1df)][_0x4d2d60(0x1cd)](_0x694d15[_0x4d2d60(0x1b3)]),_0x45171f=_0x694d15[_0x4d2d60(0x1b3)],_0xc16aab=!![],_0x595a1a=_0x694d15[_0x4d2d60(0x1c5)],_0x33f8d2=_0x694d15[_0x4d2d60(0x1e5)],_0x283c5e=_0x694d15['reason']):_0x283c5e='invalid_history:\x20'[_0x4d2d60(0x184)](_0x5eecef[_0x4d2d60(0x189)]);}}finally{_0x736767[_0x4d2d60(0x183)]({'type':_0x4d2d60(0x1af),'applied':_0xc16aab,'mode':_0x595a1a,..._0x283c5e!==undefined?{'reason':_0x283c5e}:{},'messagesBefore':_0x211e1d['length'],'messagesAfter':_0x45171f['length'],'droppedMessages':Math['max'](0x0,_0x211e1d[_0x4d2d60(0x1a3)]-_0x45171f[_0x4d2d60(0x1a3)]),'estimatedTokensBefore':_0x2938e1,'estimatedTokensAfter':_0xc16aab?estimatePromptTokens(_0x45171f,_0x736767[_0x4d2d60(0x1e1)]):_0x2938e1,..._0x33f8d2!==undefined?{'summary':_0x33f8d2}:{},'durationMs':Date['now']()-_0x5a8610});}return _0xc16aab;}const CODEACT_REGEX=/```execute-js\n([\s\S]*?)```/g;function _0x27ab(){const _0x11ecfe=['C3LZDgvTuhjVBxb0','y29UDgv4De1HBMfNzxi','Cg9SAwn5','AgfZrM9SBg93vxa','C3vTBwfYEq','mZi2ow1dC25PDW','DgHPBMTPBMDmzxzLBa','vg9VBcbLEgvJDxrPB24GC2TPChbLzcbKDwuGDg8GC3rLzxjPBMCGAw50zxjYDxb0lG','mZa3ntm0zKTqCMLn','Dg9VBe5HBwu','Dg9uB29SrgvMAw5PDgLVBNm','DhLWzq','Dg9VBf9Yzxn1Bhq','ndmXodqWnhHjDwfsqW','CMvZDwX0','C2LNBMfS','zMLSDgvY','zw1PDa','y29Uy2f0','ls0TcKvYCM9YoIa','t3v0Chv0oIa','y29KzvrPBwvVDxq','BwvZC2fNzv91CgrHDgu','CMvHC29U','ywjVCNq','Dg9VBf9LEgvJDxrPB25Fzw5K','DhvYBL9LBMq','ugXLyxnLignVBMzPz3vYzsb0AguGqvbjigTLEsbPBIbtzxr0Aw5NCY4','y29TCgfJDa','AM9PBG','zxHLyW','iI4G','Bgv2zwW','Dg9VBf9LEgvJDxrPB25FC3rHCNq','ChjLC3n1CMu','CMfJzq','BwfUywDLCL9IywrFB3v0y29Tzq','nJq3mNDZBvL3BG','C3rHCNrsDw5N','zxHLy3v0zq','teXnihn0CMvHBsbLBMrLzcb3AxrOB3v0ihbYB2r1y2LUzYbHigrVBMuGzxzLBNq','AgfYzfrPBwvVDxrnCW','BwvZC2fNzunVDw50','mtHwA09Iuuy','BwvZC2fNzvf1zxvLtwfUywDLCG','Aw5KzxHpzG','mtzMz3fjDwm','AxnbCNjHEq','zhvYyxrPB24','BgvUz3rO','BwfUywDLCL90AhjLDZOG','BM93','ywn0Aw9U','Bw9KzwW','ChjVAMvJDe1LC3nHz2vZ','C2fUzgjVEa','CMvTB3zLrxzLBNrmAxn0zw5LCG','DhjPz2DLCG','z2v0qxbPs2v5','BwvZC2fNzq','y29TCgfJDgLVBL9ZDgfYDa','y29TCgfJDgLVBL9LBMq','Bw9KzwXjza','BgfZDeLUzgv4','zg9Uzq','BwvZC2fNzxm','yxjNCW','CMvWBgfJzq','zxjYB3juExbL','ywjVCNrLza','zxnJywXHDgLVBG','Dgv4Da','y29UDgvUDa','AxnfCNjVCG','Dg9VBenHBgXjza','ntu3mdi5B09zqune','mta4mZe4mhrusxbtzG','Dg9VBf9JywXS','yMfZzvvYBa','y29TCgfJDgLVBKHHCMruAw1LB3v0','nZG4odiWshDVBMzY','y29Kzv9LEgvJDxrPB25Fzw5K','Bwf4vg9Rzw5Z','Bw9Kzq','y29UDgv4Df9VDMvYzMXVDW','C3rYzwfT','DgLTzw91Dhm','CMv0DxjUvMfSDwu','ChjVDMLKzxjszwDPC3rYEq','BgfZDfvZywDL','ote3otbuuNnqqvy','CMvZDg9Yzq','ywrKrxzLBNrmAxn0zw5LCG','w0nVzguGrxHLy3v0Aw9UifjLC3vSDf0k','y29Kzv9LEgvJDxrPB25FC3rHCNq','zxjYB3i','AwrSzvrPBwvVDxq','mZCYq0HjzxjS','t3v0Chv0oIaOBM8GB3v0Chv0kqO','AgfZu3rLzxjPBMC','AMf2yxnJCMLWDa','z2v0qwXS','mtvLAwjorhq','tM8GqvbjigTLEsbHDMfPBgfIBguGzM9YihbYB3zPzgvYici','ChvZAa','pt4G','DxnLCG','A2vLCa','DhvYBKLUzgv4','BwvZC2fNzu1HBMfNzxi','ChjVDMLKzxjjza'];_0x27ab=function(){return _0x11ecfe;};return _0x27ab();}function extractCodeBlocks(_0xd4294e){const _0x3ef8bd=_0x2c60,_0x9b565=[];let _0x5d6a56;CODEACT_REGEX[_0x3ef8bd(0x1b1)]=0x0;while((_0x5d6a56=CODEACT_REGEX[_0x3ef8bd(0x190)](_0xd4294e))!==null){const _0x531cf2=_0x5d6a56[0x1];_0x531cf2&&_0x531cf2['trim']()[_0x3ef8bd(0x1a3)]>0x0&&_0x9b565[_0x3ef8bd(0x1da)](_0x531cf2);}return _0x9b565;}function getAssistantText(_0x43a31d){const _0x507444=_0x2c60;return _0x43a31d[_0x507444(0x1ba)][_0x507444(0x182)](_0x439b0a=>_0x439b0a['type']===_0x507444(0x1b9))['map'](_0x36c070=>_0x36c070[_0x507444(0x1b9)])['join']('\x0a');}function getToolCalls(_0x521f18){const _0x46c58a=_0x2c60;return _0x521f18[_0x46c58a(0x1ba)][_0x46c58a(0x182)](_0x4a1d48=>_0x4a1d48[_0x46c58a(0x17d)]===_0x46c58a(0x1bf));}function acceptToolSteering(_0x4df2c6,_0x41c7ea){const _0x5acec6=_0x2c60;if(_0x4df2c6[_0x5acec6(0x181)][_0x5acec6(0x1b7)]||!_0x4df2c6[_0x5acec6(0x19e)][_0x5acec6(0x1d5)]())return![];for(const _0x1f24b4 of _0x41c7ea){_0x4df2c6['messageManager'][_0x5acec6(0x1da)]({'role':_0x5acec6(0x17e),'toolCallId':_0x1f24b4[_0x5acec6(0x1bc)],'content':_0x5acec6(0x1e8),'isError':!![]});}return acceptSteering(_0x4df2c6),!![];}export async function runAgentLoop(_0x40c9ad){const _0x3620c7=_0x2c60;let _0x5631e2,_0x362309=0x0,_0x51b86b=![];while(!_0x40c9ad[_0x3620c7(0x181)][_0x3620c7(0x1b7)]){acceptSteering(_0x40c9ad),_0x362309+=0x1;await runCompaction(_0x40c9ad,{'trigger':_0x3620c7(0x194),'lastUsage':_0x5631e2,'turnIndex':_0x362309})&&(_0x5631e2=undefined);if(_0x40c9ad['signal']['aborted'])break;_0x40c9ad[_0x3620c7(0x183)]({'type':'turn_start'});const _0x43e40b=_0x40c9ad[_0x3620c7(0x1ac)](_0x40c9ad[_0x3620c7(0x1a7)][_0x3620c7(0x1e0)]);if(!_0x43e40b)throw new Error(_0x3620c7(0x1d9)[_0x3620c7(0x184)](_0x40c9ad['model'][_0x3620c7(0x1e0)],_0x3620c7(0x191))+_0x3620c7(0x18d));const _0x481f26=_0x40c9ad['toolRegistry'][_0x3620c7(0x17c)](),_0x28f6aa=_0x40c9ad[_0x3620c7(0x1df)][_0x3620c7(0x1d7)](),_0xa66b9e=_0x40c9ad['projectMessages']?_0x40c9ad[_0x3620c7(0x1a8)](_0x28f6aa):_0x28f6aa;let _0x6510e1,_0x4aba2b={'inputTokens':0x0,'outputTokens':0x0};const _0x5b731e=_0x40c9ad[_0x3620c7(0x1ca)][_0x3620c7(0x1c7)](_0x40c9ad['model'][_0x3620c7(0x1e0)],{'model':_0x40c9ad[_0x3620c7(0x1a7)][_0x3620c7(0x1b0)],'messages':_0xa66b9e,'systemPrompt':_0x40c9ad[_0x3620c7(0x1e1)],'tools':_0x481f26[_0x3620c7(0x1a3)]>0x0?_0x481f26:undefined,'apiKey':_0x43e40b,'baseUrl':_0x40c9ad[_0x3620c7(0x1a7)][_0x3620c7(0x1c0)],'signal':_0x40c9ad[_0x3620c7(0x181)],..._0x40c9ad[_0x3620c7(0x1c8)][_0x3620c7(0x1d2)]!==undefined?{'idleWatchdogMs':_0x40c9ad[_0x3620c7(0x1c8)][_0x3620c7(0x1d2)]}:{},'thinkingLevel':_0x40c9ad[_0x3620c7(0x1e7)],'maxTokens':_0x40c9ad[_0x3620c7(0x1c4)],..._0x40c9ad[_0x3620c7(0x1b8)]?.['policy']?{'retryEscalation':_0x40c9ad['escalation'][_0x3620c7(0x1e3)]}:{},..._0x40c9ad[_0x3620c7(0x1b8)]?.[_0x3620c7(0x198)]?{'startRung':_0x40c9ad['escalation']['startRung']}:{}});try{for await(const _0x523984 of _0x5b731e){if(_0x40c9ad[_0x3620c7(0x181)][_0x3620c7(0x1b7)])break;_0x40c9ad[_0x3620c7(0x183)]({'type':_0x3620c7(0x188),'streamEvent':_0x523984});if(_0x523984[_0x3620c7(0x17d)]===_0x3620c7(0x1b2))_0x6510e1=_0x523984[_0x3620c7(0x1ad)],_0x4aba2b=_0x523984['usage'];else{if(_0x523984[_0x3620c7(0x17d)]==='error')throw _0x523984[_0x3620c7(0x1d1)];}}}catch(_0x527b67){const _0xa331be=_0x527b67?.[_0x3620c7(0x1b6)];if(_0xa331be!==_0x3620c7(0x1c6)||_0x51b86b||!_0x40c9ad['contextManager'])throw _0x527b67;_0x51b86b=!![];const _0x4c0134=await runCompaction(_0x40c9ad,{'trigger':'overflow','lastUsage':_0x5631e2,'turnIndex':_0x362309});if(_0x4c0134)_0x5631e2=undefined;if(!_0x4c0134)throw _0x527b67;if(_0x40c9ad[_0x3620c7(0x181)][_0x3620c7(0x1b7)])break;continue;}if(_0x40c9ad[_0x3620c7(0x181)][_0x3620c7(0x1b7)])break;if(!_0x6510e1)throw new Error(_0x3620c7(0x19a));_0x40c9ad['emit']({'type':_0x3620c7(0x18c),'message':_0x6510e1,'usage':_0x4aba2b}),_0x5631e2=_0x4aba2b,_0x51b86b=![],_0x40c9ad[_0x3620c7(0x1df)][_0x3620c7(0x1da)](_0x6510e1);if(_0x40c9ad['signal'][_0x3620c7(0x1b7)])break;const _0x1ee54a=getToolCalls(_0x6510e1),_0x3f5259=_0x1ee54a[_0x3620c7(0x1a3)]>0x0;let _0x4e815f=![];if(_0x3f5259){if(acceptToolSteering(_0x40c9ad,_0x1ee54a))continue;for(const _0x4c9aea of _0x1ee54a){if(_0x40c9ad[_0x3620c7(0x181)][_0x3620c7(0x1b7)])break;if(acceptToolSteering(_0x40c9ad,_0x1ee54a['slice'](_0x1ee54a[_0x3620c7(0x19f)](_0x4c9aea)))){_0x4e815f=!![];break;}_0x40c9ad[_0x3620c7(0x183)]({'type':_0x3620c7(0x193),'toolCallId':_0x4c9aea['toolCallId'],'toolName':_0x4c9aea[_0x3620c7(0x17b)],'args':_0x4c9aea['args']});const _0x544baf=await _0x40c9ad['toolExecutor'][_0x3620c7(0x199)](_0x4c9aea[_0x3620c7(0x1bc)],_0x4c9aea[_0x3620c7(0x17b)],_0x4c9aea['args'],_0x40c9ad['signal']);_0x40c9ad[_0x3620c7(0x183)]({'type':_0x3620c7(0x18b),'toolCallId':_0x4c9aea[_0x3620c7(0x1bc)],'toolName':_0x4c9aea[_0x3620c7(0x17b)],'result':_0x544baf[_0x3620c7(0x180)],'isError':_0x544baf['isError'],'duration':_0x544baf[_0x3620c7(0x1a2)]}),_0x40c9ad[_0x3620c7(0x1df)][_0x3620c7(0x1da)]({'role':'tool_result','toolCallId':_0x4c9aea[_0x3620c7(0x1bc)],'content':toToolResultMessageContent(_0x544baf[_0x3620c7(0x180)],_0x544baf[_0x3620c7(0x1bb)]),'isError':_0x544baf[_0x3620c7(0x1bb)]});}if(_0x40c9ad['signal']['aborted'])break;if(_0x4e815f)continue;}const _0x24d0dd=getAssistantText(_0x6510e1),_0x187efc=extractCodeBlocks(_0x24d0dd);let _0x585a14=_0x187efc[_0x3620c7(0x1a3)]>0x0&&_0x40c9ad[_0x3620c7(0x1a9)]!=null;if(_0x585a14&&_0x40c9ad[_0x3620c7(0x1a9)]){for(const _0x8609a0 of _0x187efc){if(_0x40c9ad['signal'][_0x3620c7(0x1b7)])break;_0x40c9ad['emit']({'type':_0x3620c7(0x1d0),'code':_0x8609a0,'language':_0x3620c7(0x1d6)});const _0x316554=Date[_0x3620c7(0x1a5)]();let _0x471dd3='',_0x3ad43c;try{const _0xc4fb2c=await _0x40c9ad[_0x3620c7(0x1a9)]['execute'](_0x8609a0,{'timeout':_0x40c9ad[_0x3620c7(0x1c8)][_0x3620c7(0x187)],'signal':_0x40c9ad[_0x3620c7(0x181)]}),_0x5d069b=[];for(const _0x962c2 of _0xc4fb2c['consoleOutput']){const _0x295244=_0x962c2[_0x3620c7(0x192)]==='log'?'':'['[_0x3620c7(0x184)](_0x962c2[_0x3620c7(0x192)],']\x20');_0x5d069b[_0x3620c7(0x1da)](''[_0x3620c7(0x184)](_0x295244)[_0x3620c7(0x184)](_0x962c2[_0x3620c7(0x1b4)][_0x3620c7(0x18f)]('\x20')));}_0xc4fb2c[_0x3620c7(0x1c9)]!==undefined&&_0x5d069b['push'](_0x3620c7(0x1db)[_0x3620c7(0x184)](_0xc4fb2c[_0x3620c7(0x1c9)])),_0x471dd3=_0x5d069b[_0x3620c7(0x18f)]('\x0a'),_0x3ad43c=_0xc4fb2c[_0x3620c7(0x1d1)]?.[_0x3620c7(0x1ad)];}catch(_0x5b550f){_0x3ad43c=_0x5b550f instanceof Error?_0x5b550f[_0x3620c7(0x1ad)]:String(_0x5b550f);}const _0x456ae3=Date[_0x3620c7(0x1a5)]()-_0x316554;_0x40c9ad[_0x3620c7(0x183)]({'type':_0x3620c7(0x1c3),'output':_0x471dd3,'error':_0x3ad43c,'duration':_0x456ae3});let _0x244ec0=_0x3620c7(0x1cf);_0x471dd3&&(_0x244ec0+=_0x3620c7(0x186)[_0x3620c7(0x184)](_0x471dd3,'\x0a'));_0x3ad43c&&(_0x244ec0+=_0x3620c7(0x185)['concat'](_0x3ad43c,'\x0a'));!_0x471dd3&&!_0x3ad43c&&(_0x244ec0+=_0x3620c7(0x1d4));const _0x2412d6={'role':'user','content':_0x244ec0,'timestamp':Date[_0x3620c7(0x1a5)]()};_0x40c9ad[_0x3620c7(0x1df)][_0x3620c7(0x1da)](_0x2412d6);}if(_0x40c9ad[_0x3620c7(0x181)][_0x3620c7(0x1b7)])break;continue;}if(!_0x3f5259&&!_0x585a14){if(_0x40c9ad['messageQueueManager'][_0x3620c7(0x1d5)]())continue;if(_0x40c9ad['messageQueueManager'][_0x3620c7(0x1e4)]()){const _0x5ee105=_0x40c9ad[_0x3620c7(0x19e)]['drainFollowUp']();for(const _0x5e2043 of _0x5ee105){const _0x491bb1={'role':_0x3620c7(0x1dc),'content':_0x5e2043,'timestamp':Date['now']()};_0x40c9ad[_0x3620c7(0x1df)][_0x3620c7(0x1da)](_0x491bb1);}continue;}break;}}}