| 1 |
import { makeId } from '@agent/lib/util'; |
| 2 |
|
| 3 |
// Providers reject a tool/function name with characters outside this set, and |
| 4 |
// ability ids are namespaced with a slash (e.g. woocommerce/products-query). |
| 5 |
export const toolName = (id) => id.replace(/[^a-zA-Z0-9_.-]/g, '_'); |
| 6 |
|
| 7 |
// blockSchemas reaches the backend via workflowData; in the transcript it's static |
| 8 |
// metadata re-read every turn. Serialize-time so persisted events come out clean too. |
| 9 |
const trimResult = (result) => { |
| 10 |
if (!result || typeof result !== 'object') return result ?? null; |
| 11 |
const { blockSchemas: _, ...rest } = result; |
| 12 |
return rest; |
| 13 |
}; |
| 14 |
|
| 15 |
// Values go stale between runs; ids don't. Keep error or stripFailedToolRuns |
| 16 |
// can't spot a failure. |
| 17 |
const summarizeResult = (result) => { |
| 18 |
if (!result || typeof result !== 'object') return result ?? null; |
| 19 |
return Object.fromEntries( |
| 20 |
Object.entries(result).filter( |
| 21 |
([key]) => key === 'error' || /^id$|_id$|Id$/.test(key), |
| 22 |
), |
| 23 |
); |
| 24 |
}; |
| 25 |
|
| 26 |
// The provider rejects a tool result unless it's paired with an assistant |
| 27 |
// tool-call sharing its id, so emit both. |
| 28 |
export const buildToolMessages = ( |
| 29 |
{ id, inputs, result }, |
| 30 |
{ summarize = false } = {}, |
| 31 |
) => { |
| 32 |
const toolCallId = makeId(); |
| 33 |
const name = toolName(id); |
| 34 |
return [ |
| 35 |
{ |
| 36 |
role: 'assistant', |
| 37 |
content: [ |
| 38 |
{ type: 'tool-call', toolCallId, toolName: name, input: inputs ?? {} }, |
| 39 |
], |
| 40 |
}, |
| 41 |
{ |
| 42 |
role: 'tool', |
| 43 |
content: [ |
| 44 |
{ |
| 45 |
type: 'tool-result', |
| 46 |
toolCallId, |
| 47 |
toolName: name, |
| 48 |
output: { |
| 49 |
type: 'json', |
| 50 |
value: summarize ? summarizeResult(result) : trimResult(result), |
| 51 |
}, |
| 52 |
}, |
| 53 |
], |
| 54 |
}, |
| 55 |
]; |
| 56 |
}; |
| 57 |
|