@noetaris/harness-anthropic
v0.13.0
Published
Anthropic Claude adapter for @noetaris/harness
Readme
@noetaris/harness-anthropic
Anthropic Claude adapter for @noetaris/harness.
Overview
@noetaris/harness-anthropic provides a Claude class that implements the LLM and ObserverAware interfaces from @noetaris/harness. It handles translation between the harness message format and the Anthropic SDK format, and emits telemetry events (token usage, model ID) through an attached Observer.
Installation
pnpm add @noetaris/harness-anthropicPeer dependencies:
pnpm add @noetaris/harness @noetaris/harness-typesRequires Node.js ≥ 22, @noetaris/harness 0.7.0 or later (the provider request runs inside TelemetryContext.within), and @noetaris/harness-types 0.12.0 or later.
Usage
import { createHarness, createAgent, field, runtime } from '@noetaris/harness'
import type { LLM, Message } from '@noetaris/harness-types'
import { Claude } from '@noetaris/harness-anthropic'
// The model ID is the required first argument; options are optional.
const llm = new Claude('claude-sonnet-4-6') // apiKey defaults to the ANTHROPIC_API_KEY env var
const h = createHarness<{ llm: LLM }>()({
messages: field<Message[]>({ default: () => [], reduce: (a, b) => [...a, ...b] }),
})
.provide('llm', runtime()) // supplied at agent.run()
.loop((loop) => {
loop.start().step('reply', {
run: async (state, ctx) => {
const res = await ctx.llm.invoke(state.messages, {
system: 'You are a helpful assistant.',
signal: ctx.signal, // let run.stop() cut the call
})
return { messages: [{ role: 'assistant', content: res.text }] }
},
route: () => 'done',
}).on('done').end()
})
const agent = createAgent('my-agent', h, {})
const outcome = await agent.run({ messages: [{ role: 'user', content: 'Hello' }] }, { llm })API
Claude
new Claude(model: string, options?: ClaudeOptions)Implements LLM and ObserverAware. ClaudeOptions accepts apiKey, maxRetries (see Retries) and the
generation parameters temperature, maxTokens (default 16384; thinking tokens count
toward it), topP, thinking and effort (below), captureIO (below),
autoCache and cacheTtl (see Prompt caching).
thinking and effort are sent as-is. A model that does not accept a value returns a 400 error.
| thinking | Models |
|---|---|
| { type: 'enabled', budgetTokens } | Claude 4.5; Claude 4.6 (deprecated) |
| { type: 'adaptive', display? } | Claude 4.6 and later. display is 'summarized' or 'omitted' |
| { type: 'disabled' } | Claude 4.5 to Opus 4.8, Opus 5, Sonnet 5, Haiku 5.5 |
| { type: 'between_tools' } | Sonnet 5.5 only (no up-front thinking) |
In the tool loop, the model's thinking is kept and sent back, so it does not lose its reasoning:
- The
thinkingandredacted_thinkingblocks that come before a tool call are stored on that call asproviderState.anthropic. They are plain JSON, so they survive a session store. - Keep each tool call as it is (with this field) when you put it in the conversation. Copying
response.toolCallsdoes that. - On the next call, the blocks are sent back before their tool call, and the first call's blocks before the text. Badly shaped blocks and other providers' keys are skipped.
- Thinking after the last tool call, or in a reply with no tool calls, is not kept. Its text is still in
reasoning.
effort is sent as output_config.effort ('low', 'medium', 'high', 'xhigh' or 'max').
Opus 4.7 and later and every Claude 5 model refuse temperature and topP with a 400 error.
invoke(messages, options?)—optionsis{ tools?, signal?, system? }(InvokeOptions). Translates harnessMessage[]andTool[]to Anthropic SDK format, callsclient.messages.create(), and maps the response back to anLLMResponse(including a requiredusage: { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, cacheWriteTokensByTtl?, contextWindowSize? }field;inputTokensis the total, see Prompt caching). The text ofthinkingblocks isreasoning, apart fromtext; it is absent withdisplay: 'omitted'.usage.reasoningTokensis never set: Anthropic counts thinking insideoutput_tokensand reports no separate count.withTelemetry(telemetry)— returns a per-call-scoped view of the adapter (anLLM). The harness calls it once per step, and once per branch, and installs the result asctx.llm, so telemetry travels with each call — concurrent fork branches that share one instance are attributed to their own branch, with no shared field to race on. Callers outsideagent.run()can instead passtelemetryoninvoke's options. Eachinvokeemits an"llm.request"event ({ modelId, providerName: 'anthropic', callId }) before the call and an"llm.response"event ({ tokens: { input, output, cacheRead, cacheWrite, cacheWriteByTtl? }, modelId, stopReason, providerName, contextWindowSize?, callId }) after it. If the call throws after"llm.request", an"llm.error"event ({ modelId, providerName, callId, error }, with the thrown value) is emitted instead of"llm.response", and the error then propagates unchanged. Each"llm.request"is followed by exactly one of the two, with the samecallId, so an observer can pair them.- Request scope — inside
agent.run(), the provider request (client.messages.create()) runs insidetc.within('llm.request', { callId }), the scope of the"llm.request"event. With the OTel observer and its GenAI extension (@noetaris/harness-otel-genai) thechatspan is the active span there, so auto-instrumented HTTP calls nest under it. The one-time context-window lookup runs before the request, outside that scope. A provider error emits"llm.error"instead of"llm.response"and propagates unchanged. captureIO(defaultfalse) — withtrue,"llm.request"also carriesmessages,toolsandsystem(the harness values passed toinvoke, not the translated provider payload;toolsandsystemonly when you passed them) and"llm.response"carriesoutput, theLLMResponsereturned to you. They may contain sensitive data. The GenAI extension records them only when itscaptureInputs/captureOutputsoption is on as well — see Content capture.
Image input
Image input needs @noetaris/harness-types 0.5.0 or later.
A user message can carry images next to text. Pass blocks instead of a string:
import { readFileSync } from 'node:fs'
import { Claude } from '@noetaris/harness-anthropic'
const llm = new Claude('claude-sonnet-4-6')
const response = await llm.invoke([
{
role: 'user',
content: [
{ type: 'image', data: readFileSync('photo.png').toString('base64'), mediaType: 'image/png' },
{ type: 'text', text: 'What is in this picture?' },
],
},
])- Accepted types:
image/jpeg,image/png,image/gif,image/webp. The match is exact and case-sensitive. - Anything else throws before any request is sent, and no
llm.requestevent is emitted:Error: Unsupported image media type "image/bmp" for Anthropic. Supported: image/jpeg, image/png, image/gif, image/webp. datais raw base64. The adapter passes it through unchanged, so do not add adata:prefix. Only base64 data is supported.- Order is kept as you give it. Anthropic's vision guide says Claude works best when images come before text.
- String content is sent as before. An array becomes one Anthropic content block per block, in the same order.
- Tool results: when a
toolmessage follows a user message, the adapter puts itstool_resultblock before the other blocks of that turn. - The adapter does not check that the model can read images. The provider decides.
- Images kept in session state are stored again on every run. See Large media in session state.
System prompt
Pass system to invoke. The adapter sends it as Anthropic's system parameter:
await llm.invoke(messages, { system: 'You are a careful code reviewer.' })
await llm.invoke(messages, {
system: [
{ type: 'text', text: styleGuide, cachePoint: true },
{ type: 'text', text: 'Review the diff below.' },
],
})- A string is sent as a string. Text blocks are sent as Anthropic text blocks, in order; a block with
cachePoint: truegetscache_control(see Prompt caching). - No
systemoption: the request has nosystemparameter. An empty string or empty array is sent as given. - The meaning of the option is in the
typesREADME.
Prompt caching
Anthropic caches only where the request says so. Two ways to say it:
cachePoint on a block. A text or image block with cachePoint: true, in the system option or in a user message, is sent with cache_control: { type: 'ephemeral' }. Anthropic caches the request up to and including that block (system first, then messages). The cache lives 5 minutes unless cacheTtl.points says '1h' (see Cache TTL below).
await llm.invoke([
{ role: 'user', content: [
{ type: 'text', text: contract, cachePoint: true },
{ type: 'text', text: 'List the termination clauses.' },
] },
])- At most 4 points per request, system and messages together. With more,
invokethrows before any request is sent and no"llm.request"event is emitted:Error: Too many cache points for Anthropic: 5. At most 4 are allowed per request (system and messages together). - Tool results (
role: 'tool') cannot be marked.
autoCache. new Claude(model, { autoCache: true }) sends a top-level cache_control: { type: 'ephemeral' } on every request (with ttl: '1h' when cacheTtl.auto is '1h'). Anthropic then caches up to the last cacheable block, so a chat caches its whole conversation each turn without marking anything. It uses one of Anthropic's 4 cache slots, so with autoCache on you can mark at most 3 blocks with cachePoint. With more, invoke throws before any request is sent and no "llm.request" event is emitted:
Error: Too many cache points for Anthropic: 4 and autoCache. At most 4 are allowed per request, and autoCache uses one of them.
(Anthropic itself rejects autoCache plus 4 marked blocks with HTTP 400, "A maximum of 4 blocks with cache_control may be provided. Found 5."; checked live on 2026-10-13.)
Cache TTL. A cache entry lives 5 minutes by default. cacheTtl sets it to 1 hour, separately for the cachePoint markers (points) and for the autoCache marker (auto):
const llm = new Claude('claude-sonnet-4-6', {
autoCache: true,
cacheTtl: { points: '1h', auto: '5m' },
})'5m'(the default) sendscache_control: { type: 'ephemeral' }, as before.'1h'sendscache_control: { type: 'ephemeral', ttl: '1h' }.- Price. A 5-minute write costs 1.25× the input price, a 1-hour write 2×. A read costs 0.1× (less on some models; see Anthropic's pricing). A cache hit refreshes the TTL at no cost.
- Recommended:
{ points: '1h', auto: '5m' }. Put acachePointat the end of the stable prefix (the system prompt, long documents; tools come before them and are cached with them): it is written once and survives idle gaps of up to an hour. The rolling tail thatautoCacherewrites every turn stays at the cheaper 5 minutes. autois ignored whenautoCacheis off.- Ordering. Anthropic needs a longer TTL before a shorter one, and the
autoCachemarker is always last. So:autoCachewithpoints: '5m'andauto: '1h'throws in the constructor:Error: Invalid cacheTtl for Anthropic: auto is '1h' but points is '5m'. A longer TTL must come before a shorter one, and the autoCache marker is always last. Set points to '1h', or auto to '5m'.- With
autoCacheon and different TTLs, acachePointon the request's last block (the blockautoCachemarks) throws ininvoke, before any request is sent and with no"llm.request"event:Error: Cache point on the last block conflicts with autoCache for Anthropic: the cache point's TTL is '1h' and autoCache's is '5m', and Anthropic rejects a different TTL on the block autoCache marks. Move the cache point off the last block, or give cacheTtl.points and cacheTtl.auto the same value.The last block is read from the request as sent: a tool result is merged into the user turn before it and placed first, so[user [doc ◀ cachePoint], tool]still ends with the marked block.
- 20-block lookback. A cache marker finds an earlier entry only within the 20 blocks before it. When one turn adds more than 20 blocks (for example many tool results), add a
cachePointpart-way through the turn, or the next call misses the cache.
Usage. usage.cacheReadTokens and usage.cacheWriteTokens are always present (0 when nothing was read or written). Both are parts of inputTokens. usage.cacheWriteTokensByTtl splits cacheWriteTokens into { '5m': n, '1h': m }; both keys are present whenever Anthropic reports the split (cache_creation), and the field is absent when it does not. The "llm.response" event carries the same numbers as tokens.cacheRead / tokens.cacheWrite / tokens.cacheWriteByTtl. The price formula is in the types README.
Behaviour change.
inputTokensis now the total input: Anthropic'sinput_tokens(the uncached part) pluscache_read_input_tokenspluscache_creation_input_tokens. Calls that use no cache report the same number as before. Calls that read or write the cache now report a larger number than before, and it can be compared withcontextWindowSize.
Cancelling a call
Pass an AbortSignal as signal. The adapter hands it to the Anthropic SDK, which closes the HTTP request when it aborts:
await llm.invoke(messages, { signal: AbortSignal.timeout(30_000) })
// inside a step: let run.stop() cut the call
await ctx.llm.invoke(state.messages, { signal: ctx.signal })invokerejects withsignal.reason(anAbortErrororTimeoutErrorDOMExceptionfor the default reasons), not with the SDK'sAPIUserAbortError.- Already aborted when
invokeis called: it rejects at once, with no event and no request. - Aborted after
"llm.request":"llm.error"is emitted witherror: signal.reason, theninvokerejects with it. - The one-time context-window lookup on the first call is not cancelled; if the signal aborts during it,
invokerejects right after it, with no event. - Aborting frees the caller and closes the connection. It does not guarantee that Anthropic stops billing for the request.
The full rules are in the types README.
Retries
The Anthropic SDK retries a failed request by itself. It retries connection errors, 408, 409, 429 and 5xx, twice by default. One invoke then emits one "llm.request" / "llm.response" pair, but the provider may get up to three requests.
Set maxRetries to change this. The adapter passes it to the SDK client:
const llm = new Claude('claude-sonnet-4-6', { maxRetries: 0 }) // one request per invokemaxRetries: 0turns the SDK's retries off. Use it when your code owns the retry policy, or when asignaldeadline should not be spent on retries.- No
maxRetries: the SDK default applies (2 retries). - The adapter has no retry of its own.
MockClaude
A deterministic test double for use in tests and demos without a real API key.
new MockClaude(responses?, { captureIO, latencyMs }):
captureIO: true—"llm.request"carries themessages,toolsandsystempassed toinvokeas given (the mock does no translation) and"llm.response"carries the returned response asoutput.latencyMs— waits that long before answering. The wait listens to the call'ssignal, so a test can cut a slow call withAbortSignal.timeout()orctx.signal.- Abort behaves as in the adapter: already aborted → rejects with
signal.reasonand emits nothing; aborted while waiting →"llm.error"withsignal.reason, then rejects with it. "llm.response"tokensare theusageof the returned response (reasoning/cacheRead/cacheWrite/cacheWriteByTtlonly when that usage has them).lastMessagesandlastOptionshold the messages and the options (tools,signal,system; nottelemetry) of the last call. Both are set when the call starts, so they are there even when it fails:
const llm = new MockClaude(response, { latencyMs: 5_000 })
// ... run a step that calls ctx.llm.invoke(messages, { signal: ctx.signal })
expect(llm.lastOptions.signal).toBeDefined()Like the adapter, it answers inside tc.within('llm.request', { callId }). When its queue is empty it emits "llm.error" with the empty-queue error, then throws it.
Related Packages
@noetaris/harness— core execution engine@noetaris/harness-types— shared LLM type contract@noetaris/harness-openai— OpenAI adapter@noetaris/harness-google— Google Gemini adapter@noetaris/harness-otel— OpenTelemetry observer bridge@noetaris/harness-otel-genai— GenAI semantic-conventions extension (chatspans, token metrics)
License
MIT
