Fixed delegate agent history... again
All checks were successful
Publish Library / Build NPM Project (push) Successful in 48s
Publish Library / Tag Version (push) Successful in 13s

This commit is contained in:
2026-08-04 13:58:47 -04:00
parent 566d84fd7a
commit 077f75cdd9
4 changed files with 201 additions and 266 deletions

View File

@@ -24,49 +24,29 @@ export class Anthropic extends LLMProvider {
return client;
}
private toStandard(history: any[]): LLMMessage[] {
const timestamp = Date.now();
const messages: LLMMessage[] = [];
for(let h of history) {
if(typeof h.content == 'string') {
messages.push(<any>{timestamp, ...h});
} else {
const textContent = h.content?.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n');
if(textContent) messages.push({role: h.role, content: textContent, timestamp: timestamp, duration: h.duration, tps: h.tps});
h.content.forEach((c: any) => {
if(c.type == 'tool_use') {
messages.push({role: 'tool', id: c.id, name: c.name, args: c.input, timestamp: h.timestamp, content: undefined, duration: h.duration, tps: h.tps});
} else if(c.type == 'tool_result') {
const m: any = messages.findLast(m => (<any>m).id == c.tool_use_id);
if(m) m[c.is_error ? 'error' : 'content'] = c.content;
}
});
}
}
return messages;
}
private fromStandard(history: LLMMessage[]): any[] {
for(let i = 0; i < history.length; i++) {
if(history[i].role == 'tool') {
const h: any = history[i];
history.splice(i, 1,
/** Convert standard history -> Anthropic wire format */
private toWire(history: LLMMessage[]): any[] {
const wire: any[] = [];
for(const h of history) {
if(h.role === 'tool') {
wire.push(
{role: 'assistant', content: [{type: 'tool_use', id: h.id, name: h.name, input: h.args}]},
{role: 'user', content: [{type: 'tool_result', tool_use_id: h.id, is_error: !!h.error, content: h.error || h.content}]}
)
i++;
{role: 'user', content: [{type: 'tool_result', tool_use_id: h.id, is_error: !!h.error, content: h.error || h.content || ''}]}
);
} else {
wire.push({role: h.role, content: h.content});
}
}
return history;
return wire;
}
ask(message: string, options: LLMRequest = {}): AbortablePromise<string | any> {
const controller = new AbortController();
return Object.assign(new Promise<any>(async (res) => {
let history = this.fromStandard([
...(options.history || []).filter(h => h.role !== 'system'),
{role: 'user', content: message, timestamp: Date.now()}
]);
return Object.assign(new Promise<any>(async (res, rej) => {
if(!options.history) options.history = [];
const history = options.history;
if(message) history.push({role: 'user', content: message, timestamp: Date.now()});
const tools = options.tools || this.ai.options.llm?.tools || [];
const requestParams: any = {
model: options.model || this.model,
@@ -80,105 +60,97 @@ export class Anthropic extends LLMProvider {
type: 'object',
properties: t.args ? objectMap(t.args, (key, value) => ({...value, required: undefined})) : {},
required: t.args ? Object.entries(t.args).filter(t => t[1].required).map(t => t[0]) : []
},
fn: undefined
}
})),
messages: history,
stream: !!options.stream,
};
// Add structured output support
if(options.schema) {
requestParams.output_config = {
format: {
type: 'json_schema',
schema: convertSchema(options.schema)
}
};
requestParams.output_config = {format: {type: 'json_schema', schema: convertSchema(options.schema)}};
}
let resp: any, terminal = false, duration = 0, tps = 0;
do {
requestParams.messages = history.map(({timestamp, ...m}) => m);
const callStart = Date.now();
resp = await this.tokenPool.run(token => this.getClient(token).messages.create(requestParams)).catch(err => {
err.message += `\n\nMessages:\n${JSON.stringify(history, null, 2)}`;
throw err;
});
try {
let terminal = false;
do {
requestParams.messages = this.toWire(history.filter(h => h.role !== 'system'));
let usage: any;
if(options.stream) {
resp.content = [];
for await (const chunk of resp) {
if(controller.signal.aborted) break;
if(chunk.type === 'content_block_start') {
if(chunk.content_block.type === 'text') {
resp.content.push({type: 'text', text: ''});
} else if(chunk.content_block.type === 'tool_use') {
resp.content.push({type: 'tool_use', id: chunk.content_block.id, name: chunk.content_block.name, input: <any>''});
const callStart = Date.now();
const resp: any = await this.tokenPool.run(token => this.getClient(token).messages.create(requestParams)).catch(err => {
err.message += `\n\nMessages:\n${JSON.stringify(requestParams.messages, null, 2)}`;
throw err;
});
let usage: any, content: any[] = [];
if(options.stream) {
for await (const chunk of resp) {
if(controller.signal.aborted) break;
if(chunk.type === 'content_block_start') {
if(chunk.content_block.type === 'text') content.push({type: 'text', text: ''});
else if(chunk.content_block.type === 'tool_use') content.push({type: 'tool_use', id: chunk.content_block.id, name: chunk.content_block.name, input: ''});
} else if(chunk.type === 'content_block_delta') {
if(chunk.delta.type === 'text_delta') {
content.at(-1).text += chunk.delta.text;
options.stream({text: chunk.delta.text});
} else if(chunk.delta.type === 'input_json_delta') {
content.at(-1).input += chunk.delta.partial_json;
}
} else if(chunk.type === 'content_block_stop') {
const last = content.at(-1);
if(last?.type === 'tool_use') last.input = last.input ? JSONAttemptParse(last.input, {}) : {};
} else if(chunk.type === 'message_delta') {
if(chunk.usage) usage = chunk.usage;
} else if(chunk.type === 'message_stop') {
break;
}
} else if(chunk.type === 'content_block_delta') {
if(chunk.delta.type === 'text_delta') {
const text = chunk.delta.text;
resp.content.at(-1).text += text;
options.stream({text});
} else if(chunk.delta.type === 'input_json_delta') {
resp.content.at(-1).input += chunk.delta.partial_json;
}
} else if(chunk.type === 'content_block_stop') {
const last = resp.content.at(-1);
if(last?.input != null) last.input = last.input ? JSONAttemptParse(last.input, {}) : {};
} else if(chunk.type === 'message_delta') {
if(chunk.usage) usage = chunk.usage;
} else if(chunk.type === 'message_stop') {
break;
}
} else {
usage = resp.usage;
content = resp.content;
}
} else {
usage = resp.usage;
}
duration = Date.now() - callStart;
tps = usage?.output_tokens && duration > 0 ? usage.output_tokens / (duration / 1000) : 0;
const duration = Date.now() - callStart;
const tps = usage?.output_tokens && duration > 0 ? usage.output_tokens / (duration / 1000) : 0;
const toolCalls = resp.content.filter((c: any) => c.type === 'tool_use');
if(toolCalls.length && !controller.signal.aborted) {
history.push({role: 'assistant', content: resp.content, timestamp: Date.now(), duration, tps});
const results = await Promise.all(toolCalls.map(async (toolCall: any) => {
const tool = tools.find(findByProp('name', toolCall.name));
if(options.stream) options.stream({tool: toolCall.name});
if(!tool) return {tool_use_id: toolCall.id, is_error: true, content: 'Tool not found'};
try {
const toolStream = options.stream && ((chunk: any) => {
if(chunk.done) { terminal = true; return; }
options.stream!(chunk);
});
const result = await tool.fn(toolCall.input, toolStream, this.ai, toolCall.id);
return {type: 'tool_result', tool_use_id: toolCall.id, content: typeof result == 'object' ? JSONSanitize(result) : result};
} catch (err: any) {
return {type: 'tool_result', tool_use_id: toolCall.id, is_error: true, content: err?.message || err?.toString() || 'Unknown'};
}
}));
history.push({role: 'user', content: results, timestamp: Date.now()});
requestParams.messages = history;
}
} while (!terminal && !controller.signal.aborted && resp.content.some((c: any) => c.type === 'tool_use'));
const toolCalls = content.filter((c: any) => c.type === 'tool_use');
if(toolCalls.length && !controller.signal.aborted) {
const text = content.filter((c: any) => c.type === 'text').map((c: any) => c.text).join('\n\n').trim();
if(text) history.push({role: 'assistant', content: text, timestamp: Date.now(), duration, tps});
if(!terminal) {
const textContent = resp.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n');
history.push({role: 'assistant', content: textContent.trim(), timestamp: Date.now(), duration, tps});
const entries = toolCalls.map((tc: any) => {
const entry: any = {role: 'tool', id: tc.id, name: tc.name, args: tc.input, content: undefined, timestamp: Date.now()};
history.push(entry);
return {tc, entry};
});
await Promise.all(entries.map(async ({tc, entry}: any) => {
const tool = tools.find(findByProp('name', tc.name));
if(options.stream) options.stream({tool: tc.name});
if(!tool) { entry.error = 'Tool not found'; return; }
try {
const toolStream = options.stream && ((chunk: any) => {
if(chunk.done) { terminal = true; return; }
options.stream!(chunk);
});
const result = await tool.fn(entry.args, toolStream, this.ai, tc.id);
entry.content = typeof result === 'object' ? JSONSanitize(result) : result;
} catch(err: any) {
entry.error = err?.message || err?.toString() || 'Unknown';
}
}));
} else {
terminal = true;
const text = content.filter((c: any) => c.type === 'text').map((c: any) => c.text).join('\n\n').trim();
if(text) history.push({role: 'assistant', content: text, timestamp: Date.now(), duration, tps});
}
} while(!terminal && !controller.signal.aborted);
if(options.stream) options.stream({done: true});
const turnStart = history.map(h => h.role).lastIndexOf('user');
const finalContent = history.slice(turnStart + 1).reduce((str, h) => h.role === 'assistant' ? str + (h.content || '') : str, '').trim();
res(options.schema ? JSONAttemptParse(finalContent, finalContent) : finalContent);
} catch(err) {
rej(err);
}
history = this.toStandard(history);
if(options.history) options.history.splice(0, options.history.length, ...history);
if(options.stream) options.stream({done: true});
const turnStart = history.map(h => h.role).lastIndexOf('user');
const finalContent = history.slice(turnStart + 1).reduce((str, h) => {
if(h.role === 'assistant') return str + (h.content || '');
return str;
}, '').trim();
res(options.schema ? JSONAttemptParse(finalContent, finalContent) : finalContent);
}), {abort: () => controller.abort()});
}
}