@aragon-agent/core 0.2.62 → 0.2.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +384 -357
- package/dist/engine/accept-steering.js +1 -1
- package/dist/engine/agent-loop.d.ts +3 -1
- package/dist/engine/agent-loop.js +8 -6
- package/dist/engine/agent.d.ts +10 -2
- package/dist/engine/agent.js +5 -2
- package/dist/engine/steering.d.ts +8 -2
- package/dist/engine/steering.js +6 -2
- package/dist/engine/tool-result-content.d.ts +22 -0
- package/dist/engine/tool-result-content.js +39 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/llm/image-tokens.d.ts +11 -0
- package/dist/llm/image-tokens.js +11 -0
- package/dist/llm/model-registry.d.ts +7 -0
- package/dist/llm/model-registry.js +16 -0
- package/dist/llm/output-limits.js +2 -1
- package/dist/llm/providers/google.js +29 -3
- package/dist/llm/providers/openai.js +28 -7
- package/dist/llm/providers/tool-result-images.d.ts +29 -0
- package/dist/llm/providers/tool-result-images.js +52 -0
- package/package.json +1 -1
|
@@ -5,7 +5,7 @@ export function acceptSteering(ctx) {
|
|
|
5
5
|
const items = ctx.messageQueueManager.drainSteeringItems();
|
|
6
6
|
const ids = [];
|
|
7
7
|
for (const item of items) {
|
|
8
|
-
ctx.messageManager.push({ role: 'user', content: item.text, timestamp: Date.now() });
|
|
8
|
+
ctx.messageManager.push({ role: 'user', content: item.parts ?? item.text, timestamp: Date.now() });
|
|
9
9
|
if (item.id !== undefined)
|
|
10
10
|
ids.push(item.id);
|
|
11
11
|
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* cycle, with steering/follow-up checkpoints and optional CodeAct code
|
|
6
6
|
* block detection and execution.
|
|
7
7
|
*/
|
|
8
|
-
import type { ThinkingLevel } from '../llm/types.js';
|
|
8
|
+
import type { Message, ThinkingLevel } from '../llm/types.js';
|
|
9
9
|
import type { ProviderRegistry } from '../llm/providers/index.js';
|
|
10
10
|
import type { ToolExecutor } from '../tools/executor.js';
|
|
11
11
|
import type { ToolRegistry } from '../tools/registry.js';
|
|
@@ -45,6 +45,8 @@ export interface AgentLoopContext {
|
|
|
45
45
|
* says no (AC-1).
|
|
46
46
|
*/
|
|
47
47
|
contextManager?: ContextManager;
|
|
48
|
+
/** Request-time view of history for the provider only (D-20); absent = send as-is. */
|
|
49
|
+
projectMessages?: (messages: readonly Message[]) => readonly Message[];
|
|
48
50
|
timeouts: {
|
|
49
51
|
llmCallTimeout: number;
|
|
50
52
|
toolTimeout: number;
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { validateHistory } from './compaction.js';
|
|
9
9
|
import { acceptSteering } from './accept-steering.js';
|
|
10
10
|
import { estimatePromptTokens } from '../llm/output-limits.js';
|
|
11
|
+
import { toToolResultMessageContent } from './tool-result-content.js';
|
|
11
12
|
// ---------------------------------------------------------------------------
|
|
12
13
|
// Compaction checkpoint (context-auto-compaction §3.3)
|
|
13
14
|
// ---------------------------------------------------------------------------
|
|
@@ -306,7 +307,10 @@ export async function runAgentLoop(ctx) {
|
|
|
306
307
|
'Please configure the API key in Settings.');
|
|
307
308
|
}
|
|
308
309
|
const toolDefs = ctx.toolRegistry.toToolDefinitions();
|
|
309
|
-
const
|
|
310
|
+
const stored = ctx.messageManager.getAll();
|
|
311
|
+
const messages = ctx.projectMessages
|
|
312
|
+
? ctx.projectMessages(stored)
|
|
313
|
+
: stored;
|
|
310
314
|
// ----- Stream LLM response -----
|
|
311
315
|
let assistantMessage;
|
|
312
316
|
let usage = { inputTokens: 0, outputTokens: 0 };
|
|
@@ -425,14 +429,12 @@ export async function runAgentLoop(ctx) {
|
|
|
425
429
|
isError: execResult.isError,
|
|
426
430
|
duration: execResult.duration,
|
|
427
431
|
});
|
|
428
|
-
// Build and push tool result message.
|
|
429
|
-
|
|
430
|
-
.map((c) => (c.type === 'text' ? c.text : `[image: ${c.mediaType}]`))
|
|
431
|
-
.join('\n');
|
|
432
|
+
// Build and push tool result message. Images in a successful result are kept
|
|
433
|
+
// (agent-image-reading); text-only and error results flatten exactly as before.
|
|
432
434
|
ctx.messageManager.push({
|
|
433
435
|
role: 'tool_result',
|
|
434
436
|
toolCallId: toolCall.toolCallId,
|
|
435
|
-
content:
|
|
437
|
+
content: toToolResultMessageContent(execResult.result, execResult.isError),
|
|
436
438
|
isError: execResult.isError,
|
|
437
439
|
});
|
|
438
440
|
}
|
package/dist/engine/agent.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* tool registry/executor, and idle watchdog into a single cohesive API
|
|
6
6
|
* that provides a full agentic LLM execution engine.
|
|
7
7
|
*/
|
|
8
|
-
import type { Message, ThinkingLevel, UserMessage } from '../llm/types.js';
|
|
8
|
+
import type { ContentPart, Message, ThinkingLevel, UserMessage } from '../llm/types.js';
|
|
9
9
|
import type { ProviderRegistry } from '../llm/providers/index.js';
|
|
10
10
|
import type { AgentTool } from '../tools/types.js';
|
|
11
11
|
import type { AgentEventListener } from '../types.js';
|
|
@@ -38,6 +38,13 @@ export interface AgentConfig {
|
|
|
38
38
|
* the `Agent`'s whole lifetime while the policy behind it changes mid-session.
|
|
39
39
|
*/
|
|
40
40
|
contextManager?: ContextManager;
|
|
41
|
+
/**
|
|
42
|
+
* Optional request-time projection of history (desktop-attachments-and-tool-voice D-20).
|
|
43
|
+
* Applied ONLY to the copy handed to the provider; the message manager and
|
|
44
|
+
* checkpoints are never touched. Absent = pre-feature behaviour. A projection with
|
|
45
|
+
* nothing to change must return the same array reference.
|
|
46
|
+
*/
|
|
47
|
+
projectMessages?: (messages: readonly Message[]) => readonly Message[];
|
|
41
48
|
/** Timeout configuration. */
|
|
42
49
|
timeouts?: {
|
|
43
50
|
/** Single LLM call timeout (ms). Default: 300_000 (5 min). */
|
|
@@ -94,6 +101,7 @@ export declare class Agent {
|
|
|
94
101
|
private readonly getApiKeyFn;
|
|
95
102
|
private readonly sandbox?;
|
|
96
103
|
private readonly contextManager?;
|
|
104
|
+
private readonly projectMessages?;
|
|
97
105
|
private maxTokens;
|
|
98
106
|
private readonly llmCallTimeout;
|
|
99
107
|
private readonly idleTimeout;
|
|
@@ -129,7 +137,7 @@ export declare class Agent {
|
|
|
129
137
|
*/
|
|
130
138
|
subscribe(listener: AgentEventListener): () => void;
|
|
131
139
|
/** Queue high-priority text; an optional ID is echoed only after history acceptance. */
|
|
132
|
-
steer(message: string, id?: string): void;
|
|
140
|
+
steer(message: string, id?: string, parts?: ContentPart[]): void;
|
|
133
141
|
/** Withdraw a queued steering message by its receipt ID; false if the engine already took it. */
|
|
134
142
|
removeQueuedSteering(id: string): boolean;
|
|
135
143
|
/** Queue a low-priority follow-up message (consumed after end_turn). */
|
package/dist/engine/agent.js
CHANGED
|
@@ -38,6 +38,7 @@ export class Agent {
|
|
|
38
38
|
getApiKeyFn;
|
|
39
39
|
sandbox;
|
|
40
40
|
contextManager;
|
|
41
|
+
projectMessages;
|
|
41
42
|
// --- LLM generation parameters ---
|
|
42
43
|
maxTokens;
|
|
43
44
|
// --- Timeouts ---
|
|
@@ -59,6 +60,7 @@ export class Agent {
|
|
|
59
60
|
this.getApiKeyFn = config.getApiKey;
|
|
60
61
|
this.sandbox = config.sandbox;
|
|
61
62
|
this.contextManager = config.contextManager;
|
|
63
|
+
this.projectMessages = config.projectMessages;
|
|
62
64
|
this.maxTokens = config.maxTokens;
|
|
63
65
|
// Timeouts
|
|
64
66
|
this.llmCallTimeout = config.timeouts?.llmCallTimeout ?? DEFAULT_LLM_CALL_TIMEOUT;
|
|
@@ -157,8 +159,8 @@ export class Agent {
|
|
|
157
159
|
// Message queues
|
|
158
160
|
// =========================================================================
|
|
159
161
|
/** Queue high-priority text; an optional ID is echoed only after history acceptance. */
|
|
160
|
-
steer(message, id) {
|
|
161
|
-
this.messageQueueManager.pushSteering(message, id);
|
|
162
|
+
steer(message, id, parts) {
|
|
163
|
+
this.messageQueueManager.pushSteering(message, id, parts);
|
|
162
164
|
}
|
|
163
165
|
/** Withdraw a queued steering message by its receipt ID; false if the engine already took it. */
|
|
164
166
|
removeQueuedSteering(id) {
|
|
@@ -339,6 +341,7 @@ export class Agent {
|
|
|
339
341
|
// that is genuinely absent rather than a property holding `undefined` —
|
|
340
342
|
// which is what makes the byte-identity claim in AC-1 provable.
|
|
341
343
|
...(this.contextManager ? { contextManager: this.contextManager } : {}),
|
|
344
|
+
...(this.projectMessages ? { projectMessages: this.projectMessages } : {}),
|
|
342
345
|
signal: this.abortController.signal,
|
|
343
346
|
timeouts: {
|
|
344
347
|
llmCallTimeout: this.llmCallTimeout,
|
|
@@ -7,16 +7,22 @@
|
|
|
7
7
|
* Follow-up messages have low priority: they are consumed only when the
|
|
8
8
|
* Agent loop would otherwise exit (end_turn with no pending work).
|
|
9
9
|
*/
|
|
10
|
-
|
|
10
|
+
import type { ContentPart } from '../llm/types.js';
|
|
11
|
+
/**
|
|
12
|
+
* Queued text with an optional host-supplied opaque receipt identifier.
|
|
13
|
+
* `parts` (desktop-attachments-and-tool-voice D-10) carries the multimodal form of the
|
|
14
|
+
* same message; when present it is what enters history, `text` stays the plain view.
|
|
15
|
+
*/
|
|
11
16
|
export interface SteeringMessage {
|
|
12
17
|
readonly text: string;
|
|
13
18
|
readonly id?: string;
|
|
19
|
+
readonly parts?: ContentPart[];
|
|
14
20
|
}
|
|
15
21
|
export declare class MessageQueueManager {
|
|
16
22
|
private readonly steeringQueue;
|
|
17
23
|
private readonly followUpQueue;
|
|
18
24
|
/** Enqueue a high-priority steering message. */
|
|
19
|
-
pushSteering(message: string, id?: string): void;
|
|
25
|
+
pushSteering(message: string, id?: string, parts?: ContentPart[]): void;
|
|
20
26
|
/** Drain and return all pending steering messages (empties the queue). */
|
|
21
27
|
drainSteering(): string[];
|
|
22
28
|
/** Drain all pending envelopes in FIFO order (empties the same queue). */
|
package/dist/engine/steering.js
CHANGED
|
@@ -14,8 +14,12 @@ export class MessageQueueManager {
|
|
|
14
14
|
// Steering
|
|
15
15
|
// -----------------------------------------------------------------------
|
|
16
16
|
/** Enqueue a high-priority steering message. */
|
|
17
|
-
pushSteering(message, id) {
|
|
18
|
-
this.steeringQueue.push({
|
|
17
|
+
pushSteering(message, id, parts) {
|
|
18
|
+
this.steeringQueue.push({
|
|
19
|
+
text: message,
|
|
20
|
+
...(id !== undefined ? { id } : {}),
|
|
21
|
+
...(parts !== undefined ? { parts } : {}),
|
|
22
|
+
});
|
|
19
23
|
}
|
|
20
24
|
/** Drain and return all pending steering messages (empties the queue). */
|
|
21
25
|
drainSteering() {
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool result -> history message content (agent-image-reading P1).
|
|
3
|
+
*
|
|
4
|
+
* INTERNAL: deliberately not exported from `index.ts`. A new runtime export would have to be
|
|
5
|
+
* mirrored in the barrel, `public-api.test.ts` and `API.md`; this helper is an implementation
|
|
6
|
+
* detail of the agent loop.
|
|
7
|
+
*
|
|
8
|
+
* Until now the loop flattened every image block of a tool result to the literal text
|
|
9
|
+
* `[image: image/png]`, so a tool could never show the model a picture. A successful result
|
|
10
|
+
* that carries an image now keeps it as a `ContentPart[]`; everything else is unchanged.
|
|
11
|
+
*/
|
|
12
|
+
import type { ContentPart } from '../llm/types.js';
|
|
13
|
+
import type { ToolResult } from '../tools/types.js';
|
|
14
|
+
/**
|
|
15
|
+
* Content of the `tool_result` message for one tool execution.
|
|
16
|
+
*
|
|
17
|
+
* - An error result, or one without an image block -> the same `join('\n')` string as before
|
|
18
|
+
* (an image never belongs to an error, and plain-text history stays byte-identical).
|
|
19
|
+
* - Otherwise the blocks in their original order as `ContentPart[]`. Empty text blocks are
|
|
20
|
+
* dropped (Anthropic rejects an empty text block); if nothing is left the result is `''`.
|
|
21
|
+
*/
|
|
22
|
+
export declare function toToolResultMessageContent(result: ToolResult, isError: boolean): string | ContentPart[];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool result -> history message content (agent-image-reading P1).
|
|
3
|
+
*
|
|
4
|
+
* INTERNAL: deliberately not exported from `index.ts`. A new runtime export would have to be
|
|
5
|
+
* mirrored in the barrel, `public-api.test.ts` and `API.md`; this helper is an implementation
|
|
6
|
+
* detail of the agent loop.
|
|
7
|
+
*
|
|
8
|
+
* Until now the loop flattened every image block of a tool result to the literal text
|
|
9
|
+
* `[image: image/png]`, so a tool could never show the model a picture. A successful result
|
|
10
|
+
* that carries an image now keeps it as a `ContentPart[]`; everything else is unchanged.
|
|
11
|
+
*/
|
|
12
|
+
/** The pre-existing flattening, kept byte-for-byte for text-only and error results. */
|
|
13
|
+
function flattenToText(result) {
|
|
14
|
+
return result.content
|
|
15
|
+
.map((c) => (c.type === 'text' ? c.text : `[image: ${c.mediaType}]`))
|
|
16
|
+
.join('\n');
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Content of the `tool_result` message for one tool execution.
|
|
20
|
+
*
|
|
21
|
+
* - An error result, or one without an image block -> the same `join('\n')` string as before
|
|
22
|
+
* (an image never belongs to an error, and plain-text history stays byte-identical).
|
|
23
|
+
* - Otherwise the blocks in their original order as `ContentPart[]`. Empty text blocks are
|
|
24
|
+
* dropped (Anthropic rejects an empty text block); if nothing is left the result is `''`.
|
|
25
|
+
*/
|
|
26
|
+
export function toToolResultMessageContent(result, isError) {
|
|
27
|
+
if (isError || !result.content.some((c) => c.type === 'image'))
|
|
28
|
+
return flattenToText(result);
|
|
29
|
+
const parts = [];
|
|
30
|
+
for (const block of result.content) {
|
|
31
|
+
if (block.type === 'image') {
|
|
32
|
+
parts.push({ type: 'image', mediaType: block.mediaType, data: block.data });
|
|
33
|
+
}
|
|
34
|
+
else if (block.text !== '') {
|
|
35
|
+
parts.push({ type: 'text', text: block.text });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return parts.length > 0 ? parts : '';
|
|
39
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export { THINKING_BUDGET } from './llm/types.js';
|
|
|
10
10
|
export type { LLMProvider, LLMRequest, LLMErrorType, } from './llm/provider.js';
|
|
11
11
|
export { LLMError, classifyHttpError, wrapFetchError, } from './llm/provider.js';
|
|
12
12
|
export { DEFAULT_MAX_OUTPUT_TOKENS, MIN_MAX_OUTPUT_TOKENS, SAFE_FALLBACK_MAX_OUTPUT_TOKENS, ABSOLUTE_MAX_OUTPUT_TOKENS, THINKING_HEADROOM_TOKENS, CONTEXT_SAFETY_MARGIN_TOKENS, resolveOutputTokens, staticCeilingFor, learnModelCeiling, getLearnedCeiling, clearLearnedCeilings, estimatePromptTokens, CHARS_PER_TOKEN, } from './llm/output-limits.js';
|
|
13
|
+
export { IMAGE_TOKEN_ESTIMATE } from './llm/image-tokens.js';
|
|
13
14
|
export type { OutputLimitInput, OutputLimitResolution, CeilingSource, } from './llm/output-limits.js';
|
|
14
15
|
export { classifyOutputLimitFailure, sendWithOutputLimitRecovery, learnTokenField, getLearnedTokenField, clearLearnedTokenFields, } from './llm/output-limit-recovery.js';
|
|
15
16
|
export { RETRY_LIMITS, DEFAULT_RETRY_POLICY, isRetryableError, computeBackoffDelay, parseRetryAfterMs, withRetry, } from './llm/retry.js';
|
package/dist/index.js
CHANGED
|
@@ -16,6 +16,8 @@ export { DEFAULT_MAX_OUTPUT_TOKENS, MIN_MAX_OUTPUT_TOKENS, SAFE_FALLBACK_MAX_OUT
|
|
|
16
16
|
// (context-auto-compaction P2-3): two chars-per-token constants that must agree
|
|
17
17
|
// and nothing checking that they do is how a budget and an estimate drift.
|
|
18
18
|
CHARS_PER_TOKEN, } from './llm/output-limits.js';
|
|
19
|
+
// Single source of the per-image token cost (desktop-attachments-and-tool-voice D-21).
|
|
20
|
+
export { IMAGE_TOKEN_ESTIMATE } from './llm/image-tokens.js';
|
|
19
21
|
export { classifyOutputLimitFailure, sendWithOutputLimitRecovery, learnTokenField, getLearnedTokenField, clearLearnedTokenFields, } from './llm/output-limit-recovery.js';
|
|
20
22
|
// ---------------------------------------------------------------------------
|
|
21
23
|
// Retry & exponential backoff — the authority for "a provider call failed, now
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conservative token cost of ONE image part, shared by every estimator and by the
|
|
3
|
+
* desktop UI (which receives it through the host's session meta).
|
|
4
|
+
*
|
|
5
|
+
* Derived from the 1568 px long-edge cap the desktop applies before sending
|
|
6
|
+
* (`ATTACHMENT_LIMITS.maxImageEdgePx`): ceil(1568 * 882 / 750) is about 1.8k, and 1600
|
|
7
|
+
* is the typical screenshot. CHANGE BOTH TOGETHER. Before this constant the engine
|
|
8
|
+
* charged ~256 tokens per image, which delayed compaction and under-reported
|
|
9
|
+
* context occupancy.
|
|
10
|
+
*/
|
|
11
|
+
export declare const IMAGE_TOKEN_ESTIMATE = 1600;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conservative token cost of ONE image part, shared by every estimator and by the
|
|
3
|
+
* desktop UI (which receives it through the host's session meta).
|
|
4
|
+
*
|
|
5
|
+
* Derived from the 1568 px long-edge cap the desktop applies before sending
|
|
6
|
+
* (`ATTACHMENT_LIMITS.maxImageEdgePx`): ceil(1568 * 882 / 750) is about 1.8k, and 1600
|
|
7
|
+
* is the typical screenshot. CHANGE BOTH TOGETHER. Before this constant the engine
|
|
8
|
+
* charged ~256 tokens per image, which delayed compaction and under-reported
|
|
9
|
+
* context occupancy.
|
|
10
|
+
*/
|
|
11
|
+
export const IMAGE_TOKEN_ESTIMATE = 1600;
|
|
@@ -24,6 +24,13 @@ export declare class ModelRegistry {
|
|
|
24
24
|
getModels(providerId: string): ModelInfo[];
|
|
25
25
|
/** Look up a specific model by provider + model id. */
|
|
26
26
|
getModel(providerId: string, modelId: string): ModelInfo | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* Catalog lookup that tolerates dated snapshots and vendor prefixes (`catalogModelId`), the
|
|
29
|
+
* same normalisation `getContextWindow` uses. `getModel` stays exact on purpose.
|
|
30
|
+
*/
|
|
31
|
+
findCatalogModel(providerId: string, modelId: string): ModelInfo | undefined;
|
|
32
|
+
/** The endpoint-scoped discovery entry for a model, if discovery has run and found it. */
|
|
33
|
+
getDiscoveredModel(providerId: string, modelId: string, baseUrl?: string): ModelInfo | undefined;
|
|
27
34
|
/** Resolve context separately from price, scoped to the configured endpoint. */
|
|
28
35
|
getContextWindow(providerId: string, modelId: string, baseUrl?: string): ContextWindowInfo;
|
|
29
36
|
private cacheKey;
|
|
@@ -41,6 +41,22 @@ export class ModelRegistry {
|
|
|
41
41
|
const models = this.builtinModels.get(providerId);
|
|
42
42
|
return models?.find((m) => m.id === modelId);
|
|
43
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Catalog lookup that tolerates dated snapshots and vendor prefixes (`catalogModelId`), the
|
|
46
|
+
* same normalisation `getContextWindow` uses. `getModel` stays exact on purpose.
|
|
47
|
+
*/
|
|
48
|
+
findCatalogModel(providerId, modelId) {
|
|
49
|
+
const exact = this.getModel(providerId, modelId);
|
|
50
|
+
if (exact)
|
|
51
|
+
return exact;
|
|
52
|
+
const id = catalogModelId(modelId);
|
|
53
|
+
return this.getModels(providerId).find((m) => catalogModelId(m.id) === id);
|
|
54
|
+
}
|
|
55
|
+
/** The endpoint-scoped discovery entry for a model, if discovery has run and found it. */
|
|
56
|
+
getDiscoveredModel(providerId, modelId, baseUrl) {
|
|
57
|
+
return this.discoveryCache.get(this.cacheKey(providerId, baseUrl))?.models
|
|
58
|
+
.find((m) => m.id.replace(/^models\//, '') === modelId.replace(/^models\//, ''));
|
|
59
|
+
}
|
|
44
60
|
/** Resolve context separately from price, scoped to the configured endpoint. */
|
|
45
61
|
getContextWindow(providerId, modelId, baseUrl) {
|
|
46
62
|
const discovered = this.discoveryCache.get(this.cacheKey(providerId, baseUrl))?.models
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
* `afterEach`, or a learned 8192 leaks into the next test file and produces a
|
|
20
20
|
* failure whose cause is not in the failing file.
|
|
21
21
|
*/
|
|
22
|
+
import { IMAGE_TOKEN_ESTIMATE } from './image-tokens.js';
|
|
22
23
|
// ---------------------------------------------------------------------------
|
|
23
24
|
// Constants — nothing else in this package may spell these numbers
|
|
24
25
|
// ---------------------------------------------------------------------------
|
|
@@ -246,7 +247,7 @@ function partLength(content) {
|
|
|
246
247
|
// Base64 image payloads are counted at a flat rate rather than by length:
|
|
247
248
|
// their character count says nothing useful about their token cost.
|
|
248
249
|
else if (part?.type === 'image')
|
|
249
|
-
total += CHARS_PER_TOKEN *
|
|
250
|
+
total += CHARS_PER_TOKEN * IMAGE_TOKEN_ESTIMATE;
|
|
250
251
|
}
|
|
251
252
|
return total;
|
|
252
253
|
}
|
|
@@ -14,6 +14,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
14
14
|
import { reportedContextWindow } from '../context-window.js';
|
|
15
15
|
import { createModelDiscoverySignal } from '../model-discovery.js';
|
|
16
16
|
import { LLMError, classifyHttpError, wrapFetchError } from '../provider.js';
|
|
17
|
+
import { findToolName, imageHandoffLabel, splitToolResultContent, withHandoffStub, } from './tool-result-images.js';
|
|
17
18
|
import { DEFAULT_MAX_OUTPUT_TOKENS, learnModelCeiling, resolveOutputTokens, } from '../output-limits.js';
|
|
18
19
|
import { sendWithOutputLimitRecovery } from '../output-limit-recovery.js';
|
|
19
20
|
import { parseSSEStream } from '../stream-utils.js';
|
|
@@ -313,7 +314,18 @@ function buildRequestBody(request) {
|
|
|
313
314
|
// ---------------------------------------------------------------------------
|
|
314
315
|
function convertMessages(messages) {
|
|
315
316
|
const result = [];
|
|
317
|
+
// A `functionResponse` carries text only, so a tool result's pictures follow in a `user` turn
|
|
318
|
+
// after the whole run of consecutive tool results (same hand-off as the OpenAI adapter).
|
|
319
|
+
let handoffs = [];
|
|
320
|
+
const flushHandoffs = () => {
|
|
321
|
+
if (handoffs.length === 0)
|
|
322
|
+
return;
|
|
323
|
+
result.push(...handoffs);
|
|
324
|
+
handoffs = [];
|
|
325
|
+
};
|
|
316
326
|
for (const msg of messages) {
|
|
327
|
+
if (msg.role !== 'tool_result')
|
|
328
|
+
flushHandoffs();
|
|
317
329
|
switch (msg.role) {
|
|
318
330
|
case 'user':
|
|
319
331
|
result.push({
|
|
@@ -330,9 +342,13 @@ function convertMessages(messages) {
|
|
|
330
342
|
});
|
|
331
343
|
break;
|
|
332
344
|
case 'tool_result': {
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
|
|
345
|
+
const { text: splitText, images } = splitToolResultContent(msg.content);
|
|
346
|
+
// Without pictures the flattening stays exactly as it was (`join('')` for an array).
|
|
347
|
+
const textContent = images.length > 0
|
|
348
|
+
? withHandoffStub(splitText)
|
|
349
|
+
: typeof msg.content === 'string'
|
|
350
|
+
? msg.content
|
|
351
|
+
: msg.content.map((p) => p.type === 'text' ? p.text : '').join('');
|
|
336
352
|
// Gemini requires the function *name* here, not the call ID.
|
|
337
353
|
// Look backwards through the conversation for the matching
|
|
338
354
|
// tool_call block so we can resolve the actual name.
|
|
@@ -350,10 +366,20 @@ function convertMessages(messages) {
|
|
|
350
366
|
},
|
|
351
367
|
],
|
|
352
368
|
});
|
|
369
|
+
if (images.length > 0) {
|
|
370
|
+
handoffs.push({
|
|
371
|
+
role: 'user',
|
|
372
|
+
parts: [
|
|
373
|
+
{ text: imageHandoffLabel(msg.toolCallId, findToolName(messages, msg.toolCallId)) },
|
|
374
|
+
...convertContentParts(images),
|
|
375
|
+
],
|
|
376
|
+
});
|
|
377
|
+
}
|
|
353
378
|
break;
|
|
354
379
|
}
|
|
355
380
|
}
|
|
356
381
|
}
|
|
382
|
+
flushHandoffs();
|
|
357
383
|
return result;
|
|
358
384
|
}
|
|
359
385
|
function convertContentParts(parts) {
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* - The `[DONE]` sentinel terminates the SSE stream.
|
|
12
12
|
*/
|
|
13
13
|
import { LLMError, classifyHttpError, wrapFetchError } from '../provider.js';
|
|
14
|
+
import { findToolName, imageHandoffLabel, splitToolResultContent, withHandoffStub, } from './tool-result-images.js';
|
|
14
15
|
import { DEFAULT_MAX_OUTPUT_TOKENS, estimatePromptTokens, normalizeModelId, resolveOutputTokens, staticCeilingFor, } from '../output-limits.js';
|
|
15
16
|
import { getLearnedTokenField, sendWithOutputLimitRecovery } from '../output-limit-recovery.js';
|
|
16
17
|
import { parseSSEStream } from '../stream-utils.js';
|
|
@@ -404,11 +405,23 @@ function buildRequestBody(request) {
|
|
|
404
405
|
// ---------------------------------------------------------------------------
|
|
405
406
|
function convertMessages(messages, systemPrompt) {
|
|
406
407
|
const result = [];
|
|
408
|
+
// The `tool` role cannot carry pictures, so a tool result's images are handed off in a `user`
|
|
409
|
+
// message. OpenAI requires every `tool` message answering one assistant turn to follow it
|
|
410
|
+
// back to back, so the hand-offs wait here until that run of tool results ends.
|
|
411
|
+
let handoffs = [];
|
|
412
|
+
const flushHandoffs = () => {
|
|
413
|
+
if (handoffs.length === 0)
|
|
414
|
+
return;
|
|
415
|
+
result.push(...handoffs);
|
|
416
|
+
handoffs = [];
|
|
417
|
+
};
|
|
407
418
|
// System prompt as the first message
|
|
408
419
|
if (systemPrompt) {
|
|
409
420
|
result.push({ role: 'system', content: systemPrompt });
|
|
410
421
|
}
|
|
411
422
|
for (const msg of messages) {
|
|
423
|
+
if (msg.role !== 'tool_result')
|
|
424
|
+
flushHandoffs();
|
|
412
425
|
switch (msg.role) {
|
|
413
426
|
case 'user':
|
|
414
427
|
result.push({
|
|
@@ -421,17 +434,25 @@ function convertMessages(messages, systemPrompt) {
|
|
|
421
434
|
case 'assistant':
|
|
422
435
|
result.push(convertAssistantMessage(msg));
|
|
423
436
|
break;
|
|
424
|
-
case 'tool_result':
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
tool_call_id: msg.toolCallId,
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
437
|
+
case 'tool_result': {
|
|
438
|
+
const { text, images } = splitToolResultContent(msg.content);
|
|
439
|
+
if (images.length === 0) {
|
|
440
|
+
result.push({ role: 'tool', tool_call_id: msg.toolCallId, content: text });
|
|
441
|
+
break;
|
|
442
|
+
}
|
|
443
|
+
result.push({ role: 'tool', tool_call_id: msg.toolCallId, content: withHandoffStub(text) });
|
|
444
|
+
handoffs.push({
|
|
445
|
+
role: 'user',
|
|
446
|
+
content: [
|
|
447
|
+
{ type: 'text', text: imageHandoffLabel(msg.toolCallId, findToolName(messages, msg.toolCallId)) },
|
|
448
|
+
...convertContentParts(images),
|
|
449
|
+
],
|
|
431
450
|
});
|
|
432
451
|
break;
|
|
452
|
+
}
|
|
433
453
|
}
|
|
434
454
|
}
|
|
455
|
+
flushHandoffs();
|
|
435
456
|
return result;
|
|
436
457
|
}
|
|
437
458
|
function convertContentParts(parts) {
|
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
import type { ContentPart, ImageContentPart, Message } from '../types.js';
|
|
13
|
+
/** Appended to the tool message text so the model knows the picture is not missing. */
|
|
14
|
+
export declare const IMAGE_HANDOFF_STUB = "(the image follows in the next message)";
|
|
15
|
+
/**
|
|
16
|
+
* Split a tool result into the text the tool message carries and the images that must be
|
|
17
|
+
* handed off. Text blocks are joined with `\n`, the same rule the agent loop uses to flatten
|
|
18
|
+
* a text-only result; a plain string result has no images.
|
|
19
|
+
*/
|
|
20
|
+
export declare function splitToolResultContent(content: string | ContentPart[]): {
|
|
21
|
+
text: string;
|
|
22
|
+
images: ImageContentPart[];
|
|
23
|
+
};
|
|
24
|
+
/** Tool message text for a result whose pictures are handed off: the text, then the stub. */
|
|
25
|
+
export declare function withHandoffStub(text: string): string;
|
|
26
|
+
/** First text block of the follow-up user message: ties the pictures to their tool call. */
|
|
27
|
+
export declare function imageHandoffLabel(toolCallId: string, toolName: string | undefined): string;
|
|
28
|
+
/** Name of the tool a result answers, or `undefined` when the call is not in the history. */
|
|
29
|
+
export declare function findToolName(messages: readonly Message[], toolCallId: string): string | undefined;
|
|
@@ -0,0 +1,52 @@
|
|
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aragon-agent/core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.64",
|
|
4
4
|
"description": "AragonAgent core engine — LLM provider adapters, streaming, tool registry/execution, steering, idle watchdog, and an optional isolated-vm sandbox.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "AragonAgent contributors",
|