@cerebriline/agents 4.100.240

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.
@@ -0,0 +1,607 @@
1
+ import { type GatewayProviderSettings } from "@cerebriline/llms";
2
+ import type { AgentMessage, AgentModel, AgentRunResult, AgentRuntimeEvent, AgentRuntimeStateSnapshot, AgentRuntimeConfig as BaseAgentRuntimeConfig, ToolCallRejection } from "@cerebriline/shared";
3
+ /** Most characters of one call's arguments written to the log. */
4
+ export declare const TOOL_ARGUMENTS_LOG_CHARS = 32000;
5
+ /**
6
+ * One log line with a tool call's arguments as the model sent them, before
7
+ * they are parsed, repaired or validated. The session file keeps only what
8
+ * came out of that, and the log kept only the tool's name: a lead that said
9
+ * it had sent `count: 3` could not be checked against the wire (pandorum
10
+ * xs8kv, 2026-10-04). Long arguments keep their head and tail, and the line
11
+ * says how long they were.
12
+ */
13
+ export declare function describeToolArguments(iteration: number, toolName: string, toolCallId: string, inputText: string, parsedInput: unknown): string;
14
+ /**
15
+ * How many truncated turns in a row are retried before the run ends.
16
+ *
17
+ * Bounded because each attempt costs a whole generation — up to the output cap
18
+ * itself, which on a local model is minutes of GPU time. Two is enough for the
19
+ * case this exists for: a model that reasoned past the cap once and, told so,
20
+ * produces a shorter reply. A model that truncates three times running is not
21
+ * going to be talked out of it, and ending the run beats burning the window.
22
+ *
23
+ * The counter is consecutive, not per-run: any turn that finishes resets it, so
24
+ * a long session gets the same protection at every point rather than spending a
25
+ * single allowance early.
26
+ */
27
+ export declare const DEFAULT_MAX_TOKENS_TURN_RETRIES = 2;
28
+ /**
29
+ * The reminder for a call the engine rejected and said why.
30
+ *
31
+ * `swallowed_key` is the one measured shape (opencoti bug-3601, 16 workers of
32
+ * a 75-agent swarm): a long string argument full of code was ended with a
33
+ * backtick from that code, so the parser read the next argument as part of
34
+ * the value. The generic "it did not parse, make it smaller" sends the model
35
+ * back to write the same call the same way. Naming the argument it ran into
36
+ * and the cause gives it the one thing to do differently. Any other reason
37
+ * gets the generic text, since there is nothing specific to say about a rule
38
+ * we have not seen.
39
+ */
40
+ export declare function toolCallUnparsableReminder(rejection?: ToolCallRejection): string;
41
+ /**
42
+ * The nudge budget for hosts that want it without picking a number.
43
+ *
44
+ * Off by default, because "a turn with no tool calls ends the run" is the
45
+ * runtime's contract and not an oversight. A bound is what keeps the nudge
46
+ * from being a way to make a run immortal. The counter resets on any turn that
47
+ * does call tools, so the limit applies to consecutive silent turns rather
48
+ * than to the run as a whole.
49
+ *
50
+ * One, not two. The nudge asks a question with two branches — keep working, or
51
+ * say you are finished in one short sentence — and both are answered in a
52
+ * single turn. Sending it twice asks a model that has already answered to
53
+ * answer again, and it costs a full provider round trip to learn nothing.
54
+ * Measured on a 438-message session: the model was nudged, replied "The task
55
+ * is fully complete — all syntax errors have been resolved and verified",
56
+ * was nudged again with the identical text, and replied with the same
57
+ * sentence. The second nudge has never once changed an outcome.
58
+ */
59
+ export declare const DEFAULT_MAX_NO_TOOL_CALL_NUDGES = 1;
60
+ /**
61
+ * Consecutive turns without a tool call before the run is told so.
62
+ *
63
+ * The counter above is spent by the *first* silent turn and reset by the first
64
+ * working one, which makes it blind to the run that alternates: think at
65
+ * length, call nothing, be answered by a transaction message or a reminder,
66
+ * think at length again. `consecutiveNoToolCallNudges` reads that as one
67
+ * silent turn repeatedly, because nothing between them was a nudge.
68
+ *
69
+ * Three, from the corpus this was measured on: 106 assistant turns across
70
+ * eight runs of one model, where a threshold of three fired exactly once, on
71
+ * the run that spent six turns and ~226,000 characters of reasoning producing
72
+ * nothing. Two would have fired twice; four also fires once. Three is the
73
+ * conservative end of the range that still catches the case.
74
+ *
75
+ * The sample is small and the bound is honest about it: zero false triggers in
76
+ * 105 turns puts the 95% ceiling near 3%, not at zero. That is affordable only
77
+ * because this nudges and never ends a run.
78
+ */
79
+ export declare const DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT = 3;
80
+ /**
81
+ * Reasoning a silent turn must carry to count toward the streak.
82
+ *
83
+ * Without this the guard fires on the opposite failure: a model that has
84
+ * finished, answers a completion boundary in one terse sentence, is asked
85
+ * again, and answers again. Three short replies are not a run that has stopped
86
+ * converging -- they are a run being nagged, and telling it to "stop analysing
87
+ * and make one tool call" is exactly wrong.
88
+ *
89
+ * Found by the test for it, not by inspection. On the measured corpus the
90
+ * separation is not close: the silent turns of the run that failed carried
91
+ * 26,000 to 41,000 characters of reasoning each, while every barren turn under
92
+ * 4,000 characters was a final answer (270, 420, 755, 800). Two thousand sits
93
+ * in the empty middle, and adding it removed five of the seven turn-pairs a
94
+ * threshold of two would have fired on while leaving the real one untouched.
95
+ *
96
+ * A turn below the floor resets the streak rather than being skipped. Both
97
+ * behave identically on the corpus, so the guard takes the one that fires
98
+ * less.
99
+ */
100
+ export declare const NON_CONVERGENCE_MIN_REASONING_CHARS = 2000;
101
+ /**
102
+ * Terminal message when a context-window overflow cannot be recovered because
103
+ * there is no conversation history to compact — the system prompt, tools, and
104
+ * current input alone exceed the window.
105
+ */
106
+ export declare const CONTEXT_WINDOW_OVERFLOW_NOTHING_TO_COMPACT_MESSAGE = "The request exceeds the model's context window and there is no conversation history to compact \u2014 the system prompt, tools, and current input alone are too large. Reduce attached content or switch to a model with a larger context window.";
107
+ /**
108
+ * Terminal message when a context-window overflow persists after the runtime
109
+ * already compacted the conversation and retried once.
110
+ */
111
+ export declare const CONTEXT_WINDOW_OVERFLOW_RECOVERY_FAILED_MESSAGE = "The conversation still exceeds the model's context window after compacting it. Start a new session or switch to a model with a larger context window.";
112
+ /**
113
+ * Terminal message when no compaction pipeline is available to recover from a
114
+ * context-window overflow (e.g. compaction disabled).
115
+ */
116
+ export declare const CONTEXT_WINDOW_OVERFLOW_NO_RECOVERY_MESSAGE = "The conversation exceeds the model's context window. Compact the conversation, start a new session, or switch to a model with a larger context window.";
117
+ export type AgentRunInput = string | AgentMessage | readonly AgentMessage[];
118
+ export type AgentEventListener = (event: AgentRuntimeEvent) => void;
119
+ /**
120
+ * Advanced form: caller supplies a pre-built `AgentModel`. Used by
121
+ * `@cerebriline/core`, which constructs models itself to share gateway/telemetry
122
+ * wiring with the rest of the session runtime.
123
+ */
124
+ export interface AgentRuntimeConfigWithModel extends BaseAgentRuntimeConfig {
125
+ model: AgentModel;
126
+ }
127
+ /**
128
+ * Friendly form: caller supplies provider/model IDs and credentials, and the
129
+ * runtime builds an `AgentModel` internally via `@cerebriline/llms`. This is the
130
+ * entry point most standalone users want.
131
+ */
132
+ export interface AgentRuntimeConfigWithProvider extends Omit<BaseAgentRuntimeConfig, "model"> {
133
+ /** Provider ID (e.g., "anthropic", "openai") */
134
+ providerId: string;
135
+ /** Model ID to use */
136
+ modelId: string;
137
+ /** API key for the provider */
138
+ apiKey?: string;
139
+ /** Custom base URL for the API */
140
+ baseUrl?: string;
141
+ /** Additional headers for API requests */
142
+ headers?: Record<string, string>;
143
+ /** Provider-specific gateway options */
144
+ options?: GatewayProviderSettings["options"];
145
+ }
146
+ /**
147
+ * Config accepted by `new AgentRuntime(...)` / `createAgentRuntime(...)` /
148
+ * `new Agent(...)` / `createAgent(...)`. Either supply a pre-built `model`
149
+ * (advanced) or `providerId` + `modelId` (+ credentials) and the runtime will
150
+ * construct the model itself via `@cerebriline/llms`.
151
+ */
152
+ export type AgentRuntimeConfig = AgentRuntimeConfigWithModel | AgentRuntimeConfigWithProvider;
153
+ export declare class AgentRuntimeAbortError extends Error {
154
+ readonly reason?: unknown;
155
+ constructor(reason?: unknown);
156
+ }
157
+ /**
158
+ * How many tool calls from one assistant message run at once when nothing
159
+ * says otherwise.
160
+ *
161
+ * Eight is not a new number: it is the documented default of
162
+ * `AgentConfig.maxParallelToolCalls` and of `AgentConfigSchema`, and it had
163
+ * never once been applied. `resolveToolExecution` read the field as a
164
+ * yes/no, no host on the extension path set it, so the runtime fell through
165
+ * to `"sequential"` -- while every prompt template in
166
+ * `core/assets/prompt-templates` tells the model to emit its independent
167
+ * reads, searches and commands together. The batch arrived and was run one
168
+ * call at a time, and delegation was the visible half of it: several
169
+ * `spawn_agent` calls in one message waited for each other, so a model that
170
+ * said it would run agents in parallel never did.
171
+ */
172
+ export declare const DEFAULT_MAX_PARALLEL_TOOL_CALLS = 8;
173
+ /**
174
+ * The one number both tool-execution fields resolve to.
175
+ *
176
+ * `toolExecution: "sequential"` is an explicit request for one at a time and
177
+ * wins over any count. Otherwise the count decides, floored at 1, and its
178
+ * absence means the documented default. Keeping this in one function is the
179
+ * point: a mode field and a count field that can disagree are two homes for
180
+ * one setting, and the last three bugs here were a field with two readers.
181
+ */
182
+ export declare function resolveParallelToolCallBound(config: {
183
+ toolExecution?: "sequential" | "parallel";
184
+ maxParallelToolCalls?: number;
185
+ }): number;
186
+ export declare class AgentRuntime {
187
+ private config;
188
+ private readonly listeners;
189
+ private readonly tools;
190
+ private hooks;
191
+ /**
192
+ * `appendContext` blocks collected from beforeTool/afterTool hooks during
193
+ * the current iteration's tool executions, flushed as one user message
194
+ * after the tool results so tool-result parts stay contiguous for
195
+ * providers that require them first in the following turn.
196
+ */
197
+ private pendingHookContexts;
198
+ private readonly state;
199
+ /**
200
+ * What the engine said was wrong with the last tool call it rejected.
201
+ * Replaced on every failed turn, so it only ever describes `lastError`.
202
+ */
203
+ private lastToolCallRejection;
204
+ /** One automatic overflow-recovery attempt per run. */
205
+ private overflowRecoveryAttempted;
206
+ /**
207
+ * The last request that completed, prompt and reply: what the engine held
208
+ * for this session at the least. Named in an eviction's bug report.
209
+ */
210
+ private lastRequestTokens;
211
+ /**
212
+ * Compact before the next request, whatever the trigger concludes.
213
+ *
214
+ * Set when a turn was cut off at the output cap. Re-prompting on its own only
215
+ * asks the model to be briefer, which does nothing when the cap is small
216
+ * because the prompt has taken the window -- the retry then hits the same
217
+ * wall, and the run spends its whole retry budget on identical failures.
218
+ * Making room is the part that changes the outcome.
219
+ */
220
+ private compactBeforeNextTurn;
221
+ /**
222
+ * Whether this run has already dropped images after a model refused them.
223
+ * Once is enough: the second refusal means images were not the problem.
224
+ */
225
+ private imageRecoveryAttempted;
226
+ /** Consecutive turns nudged for producing no tool calls; reset by any turn that does. */
227
+ private consecutiveNoToolCallNudges;
228
+ /**
229
+ * Whether this run has ever called a tool.
230
+ *
231
+ * Separates a task in progress from a conversation. Never reset: a run that
232
+ * has acted once is a run with work in it, and a later quiet turn is the
233
+ * silence the nudge was built for.
234
+ */
235
+ private hasCalledAnyTool;
236
+ /**
237
+ * Consecutive turns that produced no tool call, whatever answered them.
238
+ *
239
+ * Counted separately from the nudges above because the two ask different
240
+ * questions: that one is "how many times have we asked", this one is "how
241
+ * long has this run gone without doing anything". Reset at the same place,
242
+ * by the same event -- a turn that calls tools.
243
+ */
244
+ private consecutiveNoToolCallTurns;
245
+ /** Reasoning characters accumulated over the current silent streak. */
246
+ private noToolCallStreakReasoningChars;
247
+ /** Whether the run has spent its one non-convergence nudge. */
248
+ private nonConvergenceNudgeSpent;
249
+ /**
250
+ * Whether the run has already spent its one nudge for a tool call the
251
+ * provider could not read. Bounded for the reason every nudge here is: a
252
+ * model that cannot emit a clean block twice will not on the third ask, and
253
+ * an unbounded nudge makes a run immortal.
254
+ */
255
+ private unparsedCallNudgeSpent;
256
+ /**
257
+ * Whether the one intent-specific nudge has been used.
258
+ *
259
+ * Not a consecutive counter like the one above, and not reset by a turn
260
+ * that calls tools: this is the last word before a run that keeps
261
+ * announcing is allowed to end, and it is worth exactly once.
262
+ */
263
+ private intentNudgeSpent;
264
+ /**
265
+ * The self-repetition nudger, built on first use because `this.config` is
266
+ * not assigned yet when field initialisers run. It stays `undefined` when
267
+ * the host turned the guard off.
268
+ */
269
+ private repetitionNudger;
270
+ private repetitionNudgerBuilt;
271
+ /**
272
+ * A message arrived mid-run and the model has not been asked to resume yet.
273
+ *
274
+ * Cleared as soon as the resume nudge is sent, so an interjection costs one
275
+ * extra turn at most and a model that means to stop still can.
276
+ */
277
+ private steerAwaitingResume;
278
+ /** Consecutive turns cut off at the output cap; reset by any turn that completes. */
279
+ private consecutiveMaxTokensRetries;
280
+ /**
281
+ * Consecutive turns whose tool call the provider could not parse; reset by
282
+ * any turn that reaches the tool-call stage, malformed or not.
283
+ */
284
+ private toolCallParseRetries;
285
+ /** Thinking-only turns taken again, in a row; see `THINKING_ONLY_REMINDER`. */
286
+ private thinkingOnlyRetries;
287
+ /**
288
+ * The cap that truncated the last turn, when the cap was the request's own.
289
+ *
290
+ * Kept so the retry can ask for less. Unset when the window was what
291
+ * truncated the turn: that cap is the room the prompt left, compaction is
292
+ * about to change it, and halving it would take away room the retry needs.
293
+ */
294
+ private truncatedOutputCapTokens;
295
+ private initialization?;
296
+ private abortController?;
297
+ /**
298
+ * Turns cut in a row because the reasoning channel collapsed. Cutting the
299
+ * request stops one degenerate draw; this bounds a model that redraws the
300
+ * same collapse every turn. Reset by any turn that streams cleanly.
301
+ */
302
+ private reasoningLoopStreak;
303
+ private readonly telemetryProviderId?;
304
+ private readonly telemetryModelId?;
305
+ constructor(config: AgentRuntimeConfig);
306
+ run(input: AgentRunInput): Promise<AgentRunResult>;
307
+ continue(input?: AgentRunInput): Promise<AgentRunResult>;
308
+ abort(reason?: unknown): void;
309
+ subscribe(listener: AgentEventListener): () => void;
310
+ /**
311
+ * Replace the conversation with a fresh set of messages, discarding any
312
+ * in-flight run and usage state while preserving the underlying model,
313
+ * tools, hooks, plugins, and active event subscribers.
314
+ *
315
+ * Useful for standalone callers that persist conversations externally and
316
+ * want to re-seed the runtime from storage without recreating subscribers.
317
+ */
318
+ restore(messages: readonly AgentMessage[]): void;
319
+ /**
320
+ * The run's state as an event carries it.
321
+ *
322
+ * `messages` is deep-copied when somebody reads it, not when the snapshot is
323
+ * made. Every emitted event carries a snapshot and a delta event arrives per
324
+ * token, so cloning the transcript here meant copying the whole conversation
325
+ * -- every message, every content part -- thousands of times a turn, for a
326
+ * field the delta events' consumers never read. Only `message-added` and
327
+ * `assistant-message` read it, and those arrive once each.
328
+ *
329
+ * Measured in a user's extension log: 165,195 events in one window against a
330
+ * conversation of 554,681 characters. The work is quadratic in the same
331
+ * shape as the `accumulated` string that used to be logged per delta, and it
332
+ * lands on the extension host's only thread -- which is where a Cline panel
333
+ * that has gone blank while the task keeps running is looked for.
334
+ *
335
+ * The array is copied eagerly, so a message appended after the event was
336
+ * emitted cannot appear in a clone taken later; the messages already in it
337
+ * are never mutated in place, so their copy can wait for a reader.
338
+ */
339
+ snapshot(): AgentRuntimeStateSnapshot;
340
+ private ensureInitialized;
341
+ private initialize;
342
+ private registerHooks;
343
+ private getRequiredCompletionToolNames;
344
+ private getCompletionToolReminderMessage;
345
+ /**
346
+ * Ask the host's boundary hook whether this run may end.
347
+ *
348
+ * Kept apart from `getCompletionReminderMessages` because it is a different
349
+ * kind of question and is allowed to take time over it: the reminders are
350
+ * strings a host computed in advance, while this may run a command before it
351
+ * answers. Both ways a run can end come through here.
352
+ */
353
+ private runCompletionBoundary;
354
+ private getCompletionReminderMessages;
355
+ /**
356
+ * The nudge for a turn that produced no tool calls, or undefined once the
357
+ * consecutive limit is reached and the run should be allowed to end.
358
+ */
359
+ private getNoToolCallNudgeMessage;
360
+ /**
361
+ * The nudge for a turn whose reasoning re-derives what it already concluded,
362
+ * or nothing.
363
+ *
364
+ * On unless the host passes `reasoningRepetition: false`, matching the
365
+ * streaming guard rather than the silence budget: this one never ends a turn
366
+ * and never cuts a draw, it appends one paragraph, and across 3,229 recorded
367
+ * blocks from 21 model families it fires on 1.2% of them.
368
+ *
369
+ * Deliberately not gated on `nudgesEnabled` here. That gate answers "does a
370
+ * silent turn end the run", which is a different question -- the silent path
371
+ * applies it at the call site, and the tool-calling path, where the run
372
+ * continues either way, does not.
373
+ */
374
+ private repetitionNudgeFor;
375
+ /** Whether this host asks a silent turn to continue at all. */
376
+ private nudgesEnabled;
377
+ /**
378
+ * Whether the run has gone long enough without acting to be told so.
379
+ *
380
+ * Gated on `nudgesEnabled` like every other extension of the nudge policy:
381
+ * a host that set the budget to zero has said a silent turn ends the run,
382
+ * and this must not be a second door into the same room. Once per run, and
383
+ * only while the run could still act on being told.
384
+ */
385
+ private shouldNudgeNonConvergence;
386
+ /**
387
+ * Retries allowed for turns truncated at the output cap.
388
+ *
389
+ * Defaulted on rather than opted into, unlike the no-tool-call nudge: a
390
+ * nudge asks a model that has finished to keep going, which is a policy
391
+ * question, while this recovers a turn the model never got to finish. A
392
+ * host that wants the old behaviour sets it to zero.
393
+ */
394
+ /**
395
+ * Whether the turn generated anything at all, whatever became of it.
396
+ *
397
+ * The difference between a model that reasoned itself out of room and a
398
+ * provider handing back empty responses as fast as it can. The first is worth
399
+ * another turn; the second would spin, and is left to fail as it did before.
400
+ */
401
+ private turnProducedOutputTokens;
402
+ /**
403
+ * Condense a truncated turn's reasoning, if the host asked to be given the
404
+ * chance, and never at the cost of the retry it exists to help.
405
+ *
406
+ * A condenser that throws, or that has nothing to say, leaves the discard
407
+ * exactly as it was.
408
+ */
409
+ private noteDiscardedReasoning;
410
+ /**
411
+ * What the retry after a truncated turn is allowed to spend.
412
+ *
413
+ * A turn that just spent its whole cap without producing a tool call gets
414
+ * less on the retry, halving with each consecutive failure. Handing back the
415
+ * same cap invites the same turn, and the same wait: measured on one run,
416
+ * four turns ended at exactly 32,000 output tokens -- 6m15s, 5m13s, 5m39s,
417
+ * 5m30s -- for 22m37s of a 31m43s session generated and thrown away, none of
418
+ * it window-bound (input ran 29,527 to 53,842 against a 110,000 window).
419
+ *
420
+ * It also asks for what the reminder asks for. "One tool call, or one short
421
+ * paragraph" does not need 32,000 tokens, and the turns that recovered on
422
+ * that same run did it in 5,568, 3,082 and 2,852 -- so the floor here is
423
+ * still comfortably above the largest turn that ever succeeded after one of
424
+ * these, and a relapse costs about a minute instead of six.
425
+ *
426
+ * Returns `undefined` when nothing should change: no truncation to answer
427
+ * for, or one the window caused, where the cap is the room the prompt left
428
+ * rather than a budget the model overran.
429
+ */
430
+ private getRetryOutputCap;
431
+ private getMaxTokensRetryBudget;
432
+ private addUserReminderMessage;
433
+ private execute;
434
+ private callBeforeRunHooks;
435
+ private callAfterRunHooks;
436
+ /**
437
+ * Run a model turn, and take it again for as long as it fails on a fault
438
+ * that is not the model's: the server restarted or dropped the connection
439
+ * (`transport`), or declined to run it now (`refusal`).
440
+ *
441
+ * Only with a `recoverTurnFault` configured, which does the waiting -- for
442
+ * the server to answer again, or a backoff -- and decides whether to go on.
443
+ * Without one, such a turn fails the run exactly as it always did.
444
+ *
445
+ * Replaying is safe because a turn that failed committed nothing: the
446
+ * message is discarded here, before it can enter the transcript, and no tool
447
+ * in it has run. Measured on 1tmrl: ten agents ended on `server is shutting
448
+ * down` mid-stream and eighteen on an admission refusal of a later turn,
449
+ * every one of them a turn that could simply have been sent again.
450
+ *
451
+ * Unbounded on purpose; the user's Stop is the bound. The abort signal wins
452
+ * over every wait, and is checked again before each re-send.
453
+ */
454
+ private generateAssistantMessageRecoveringFaults;
455
+ /**
456
+ * Run a model turn, recovering once per run from a provider-rejected
457
+ * context-window overflow: force a compaction through `prepareTurn` and
458
+ * retry the request. Terminal (unrecoverable) overflow states throw with
459
+ * an actionable message instead of the raw provider error.
460
+ */
461
+ private generateAssistantMessageWithOverflowRecovery;
462
+ /**
463
+ * Ask the model to send a tool call the provider could not parse again.
464
+ *
465
+ * Returns whether the turn was recovered, so both call sites can `continue`
466
+ * on true and fall through to their own error on false.
467
+ *
468
+ * A call that would not parse is a wasted turn, not a failed run: nothing
469
+ * executed, nothing changed, and whatever the model wrote before it is
470
+ * still in the transcript — usually the expensive part. Measured: a
471
+ * transaction that had already carried a broken file past its syntax error
472
+ * ended on `XML syntax error on line 12: element <parameter> closed by
473
+ * </function>` at 3,449s of a 7,200s budget. An hour of clock went unused
474
+ * because one malformed call was treated as the end of the run.
475
+ *
476
+ * What this deliberately does not do is repair the payload. A call
477
+ * truncated mid-argument, patched up and executed, writes the fragment over
478
+ * the file it names and reports success.
479
+ */
480
+ private recoverUnparsableToolCall;
481
+ /**
482
+ * Whether the model refused the turn because it carried an image.
483
+ *
484
+ * Measured: a tester ran DeepSeek on Ollama Cloud, the `browser` tool
485
+ * attached a screenshot, and the session ended on "this model does not
486
+ * support image input". Tools guard on `modelSupportsImages`, but that flag
487
+ * defaults to true for any model with no declared capabilities — every model
488
+ * outside the shipped catalog, including the local ones this fork runs.
489
+ * Tightening the default would trade one broken setup for another, so the
490
+ * refusal itself is what we act on.
491
+ *
492
+ * It used to act on it only where nobody had declared the capability, on the
493
+ * grounds that a declared answer means the tools were told before they
494
+ * attached anything. That reasoning does not survive contact with the other
495
+ * ways an image arrives: the user pastes one, or a vision model is switched
496
+ * on and the attach guards defer to it. A tester hit exactly that — Ollama
497
+ * declared the model reads no images, `imageSupportDeclared` was therefore
498
+ * true, the vision toggle let the paste through with no describer behind it,
499
+ * and the run ended on the provider's refusal with no retry. Dropping the
500
+ * images and taking the turn again is strictly better than failing it, so
501
+ * the declaration no longer vetoes the recovery. What still bounds it is
502
+ * that the error says image input specifically, that images are actually
503
+ * present, and that this is tried once.
504
+ */
505
+ private isRecoverableImageTurn;
506
+ private hasImageContent;
507
+ /**
508
+ * Drop every image from the transcript and take the turn again.
509
+ *
510
+ * The images are replaced with a line saying so rather than deleted: a tool
511
+ * result that silently loses its screenshot reads as a tool that did
512
+ * nothing, and the model would call it again. What remains is the text the
513
+ * same tool returned — for `browser`, the console output and page state,
514
+ * which is the part a non-vision model could act on anyway.
515
+ *
516
+ * Retried once. A second refusal means images were not the cause, and that
517
+ * error belongs to the caller unchanged.
518
+ */
519
+ private retryWithoutImages;
520
+ /**
521
+ * Replace images in the transcript with a second model's description of them.
522
+ *
523
+ * Returns how many were replaced. Images the describer could not handle are
524
+ * left exactly as they were: this runs on every turn when a vision model is
525
+ * configured, including for primary models that read images perfectly well,
526
+ * and a describer that is briefly unreachable must not cost the primary
527
+ * model its screenshot.
528
+ *
529
+ * Text that shared the message with an image is passed along as context —
530
+ * for a browser screenshot that is the URL and console output, which is what
531
+ * makes the difference between "a web page" and "the login form, with an
532
+ * error under the password field".
533
+ */
534
+ private describeImagesInTranscript;
535
+ private isRecoverableOverflowTurn;
536
+ private generateAssistantMessage;
537
+ private openTaskLifecycleStream;
538
+ private captureTaskLifecycleFailure;
539
+ private captureTaskLifecycle;
540
+ private getTelemetryProviderId;
541
+ private getTelemetryModelId;
542
+ private isAbortError;
543
+ private captureUnexpectedReasoningTokens;
544
+ private prepareTurnForModelRequest;
545
+ private consumePendingUserMessage;
546
+ private updateUsage;
547
+ private executeToolCalls;
548
+ private findCompletingToolMessage;
549
+ private prepareToolExecution;
550
+ private requestToolApproval;
551
+ private executePreparedTool;
552
+ private finishRun;
553
+ private findLastAssistantMessage;
554
+ /**
555
+ * A reasoning block collapsed into repetition and the request was cut.
556
+ *
557
+ * The turn keeps whatever it produced before the cut and continues, so the
558
+ * model gets a chance to recover -- but a model that collapses the same way
559
+ * every turn is not recovering, and the streak ends the run.
560
+ */
561
+ private onReasoningLoopCut;
562
+ private throwIfAborted;
563
+ private normalizeAbortError;
564
+ /**
565
+ * Per-hook time spent inside `emit`, keyed `"<event type>#<hook index>"`.
566
+ *
567
+ * Instrumentation for the ~660ms floor every tool call pays even when the
568
+ * tool does nothing: `task_progress` and `plan` write a string and still
569
+ * took 661ms and 662ms at the median across 19,803 archived calls, and the
570
+ * post-tool client gap is only 29ms, so the cost is inside the call. `emit`
571
+ * awaits every `onEvent` hook in series and is awaited twice per tool, which
572
+ * is the right shape for it. Totals are kept per hook because naming the
573
+ * slow one is the whole point.
574
+ */
575
+ private readonly eventHookMs;
576
+ private noteEventHookMs;
577
+ /** The hooks that cost the most, worst first, as `key=total/count`. */
578
+ private topEventHooks;
579
+ /**
580
+ * One boundary of the agent loop, to stderr under `CLINE_TIMING` and to the
581
+ * logger's debug channel always.
582
+ *
583
+ * Both, because the two runners surface different halves: the CLI wires no
584
+ * debug channel at all (an instrumented run through it produced zero lines),
585
+ * and the extension host has no stderr a tester can read. The volume is one
586
+ * line per turn and per tool call — not per token, which is the mistake that
587
+ * put 260,774 lines in one session.
588
+ */
589
+ private trace;
590
+ private emit;
591
+ private applyStopControl;
592
+ }
593
+ export declare function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime;
594
+ /**
595
+ * `Agent` is the user-friendly name for `AgentRuntime`. They are the same
596
+ * class; this alias exists so standalone callers can write:
597
+ *
598
+ * const agent = new Agent({ providerId, modelId, apiKey });
599
+ * await agent.run("hello");
600
+ *
601
+ * while `@cerebriline/core` (which owns model construction) continues to use
602
+ * the `AgentRuntime` name with `{ model, ... }` configs.
603
+ */
604
+ export declare const Agent: typeof AgentRuntime;
605
+ export type Agent = AgentRuntime;
606
+ export declare function createAgent(config: AgentRuntimeConfig): AgentRuntime;
607
+ //# sourceMappingURL=agent-runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../src/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,uBAAuB,EAC5B,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAKX,YAAY,EAEZ,UAAU,EAKV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAO5C,iBAAiB,EAEjB,MAAM,eAAe,CAAC;AA0EvB,kEAAkE;AAClE,eAAO,MAAM,wBAAwB,QAAS,CAAC;AAE/C;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACpC,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,OAAO,GAClB,MAAM,CAmBR;AAKD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AA0MjD;;;;;;;;;;;GAWG;AACH,wBAAgB,0BAA0B,CACzC,SAAS,CAAC,EAAE,iBAAiB,GAC3B,MAAM,CAcR;AAYD;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAEjD;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MA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AACH,eAAO,MAAM,KAAK,qBAAe,CAAC;AAClC,MAAM,MAAM,KAAK,GAAG,YAAY,CAAC;AAEjC,wBAAgB,WAAW,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAEpE"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @cline/agents
3
+ *
4
+ * Browser-safe agent runtime for the next-generation Cline SDK.
5
+ *
6
+ * Exports:
7
+ * - `AgentRuntime` / `Agent` — the agentic loop class (two names for the
8
+ * same class). Use `Agent` when supplying provider/model IDs, or
9
+ * `AgentRuntime` when supplying a pre-built `AgentModel`.
10
+ * - `createAgentRuntime` / `createAgent` — factory-function equivalents.
11
+ * - `AgentRuntimeConfig` and its two variants (`AgentRuntimeConfigWithModel`,
12
+ * `AgentRuntimeConfigWithProvider`) — the discriminated config union.
13
+ * - `AgentRunInput` / `AgentEventListener` — convenience type aliases.
14
+ * - `createTool` — re-exported from `@cerebriline/shared` for authoring tools.
15
+ *
16
+ * Shared types (`AgentMessage`, `AgentRunResult`, etc.) should be imported
17
+ * directly from `@cerebriline/shared`.
18
+ */
19
+ export type { AgentAfterToolResult, AgentBeforeModelResult, AgentBeforeToolResult, AgentMessage, AgentMessagePart, AgentModel, AgentModelFinishReason, AgentModelRequest, AgentRunResult, AgentRuntimeConfig as BaseAgentRuntimeConfig, AgentRuntimeEvent, AgentRuntimeHooks, AgentRuntimeStateSnapshot, AgentStopControl, AgentTool, AgentToolCallPart, AgentToolDefinition, AgentToolResult, AgentUsage, ToolApprovalResult, ToolPolicy, } from "@cerebriline/shared";
20
+ export { createTool } from "@cerebriline/shared";
21
+ export type { AgentEventListener, AgentRunInput, AgentRuntimeConfig, AgentRuntimeConfigWithModel, AgentRuntimeConfigWithProvider, } from "./agent-runtime";
22
+ export { Agent, AgentRuntime, AgentRuntimeAbortError, createAgent, createAgentRuntime, DEFAULT_MAX_NO_TOOL_CALL_NUDGES, DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT, NON_CONVERGENCE_MIN_REASONING_CHARS, } from "./agent-runtime";
23
+ export type { ReasoningLoopGuardConfig, ReasoningLoopKind, ReasoningLoopVerdict, } from "./reasoning-loop-guard";
24
+ export { DEFAULT_REASONING_LOOP_GUARD, describeReasoningLoop, ReasoningLoopGuard, } from "./reasoning-loop-guard";
25
+ export type { ReasoningRepetitionConfig, RepetitionMeasurement, RepetitionNudger, } from "./reasoning-repetition";
26
+ export { createRepetitionNudger, DEFAULT_REASONING_REPETITION, describeRepetition, isRepetitionLoop, measureReasoningRepetition, } from "./reasoning-repetition";
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,YAAY,EACX,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,EACrB,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,sBAAsB,EACtB,iBAAiB,EACjB,cAAc,EACd,kBAAkB,IAAI,sBAAsB,EAC5C,iBAAiB,EACjB,iBAAiB,EACjB,yBAAyB,EACzB,gBAAgB,EAChB,SAAS,EACT,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,UAAU,GACV,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,YAAY,EACX,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,2BAA2B,EAC3B,8BAA8B,GAC9B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACN,KAAK,EACL,YAAY,EACZ,sBAAsB,EACtB,WAAW,EACX,kBAAkB,EAClB,+BAA+B,EAC/B,sCAAsC,EACtC,mCAAmC,GACnC,MAAM,iBAAiB,CAAC;AACzB,YAAY,EACX,wBAAwB,EACxB,iBAAiB,EACjB,oBAAoB,GACpB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACN,4BAA4B,EAC5B,qBAAqB,EACrB,kBAAkB,GAClB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACX,yBAAyB,EACzB,qBAAqB,EACrB,gBAAgB,GAChB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACN,sBAAsB,EACtB,4BAA4B,EAC5B,kBAAkB,EAClB,gBAAgB,EAChB,0BAA0B,GAC1B,MAAM,wBAAwB,CAAC"}