npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-anthropic

Peer dependencies:

pnpm add @noetaris/harness @noetaris/harness-types

Requires 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 thinking and redacted_thinking blocks that come before a tool call are stored on that call as providerState.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.toolCalls does 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?) — options is { tools?, signal?, system? } (InvokeOptions). Translates harness Message[] and Tool[] to Anthropic SDK format, calls client.messages.create(), and maps the response back to an LLMResponse (including a required usage: { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, cacheWriteTokensByTtl?, contextWindowSize? } field; inputTokens is the total, see Prompt caching). The text of thinking blocks is reasoning, apart from text; it is absent with display: 'omitted'. usage.reasoningTokens is never set: Anthropic counts thinking inside output_tokens and reports no separate count.
  • withTelemetry(telemetry) — returns a per-call-scoped view of the adapter (an LLM). The harness calls it once per step, and once per branch, and installs the result as ctx.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 outside agent.run() can instead pass telemetry on invoke's options. Each invoke emits 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 same callId, so an observer can pair them.
  • Request scope — inside agent.run(), the provider request (client.messages.create()) runs inside tc.within('llm.request', { callId }), the scope of the "llm.request" event. With the OTel observer and its GenAI extension (@noetaris/harness-otel-genai) the chat span 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 (default false) — with true, "llm.request" also carries messages, tools and system (the harness values passed to invoke, not the translated provider payload; tools and system only when you passed them) and "llm.response" carries output, the LLMResponse returned to you. They may contain sensitive data. The GenAI extension records them only when its captureInputs / captureOutputs option 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.request event is emitted: Error: Unsupported image media type "image/bmp" for Anthropic. Supported: image/jpeg, image/png, image/gif, image/webp.
  • data is raw base64. The adapter passes it through unchanged, so do not add a data: 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 tool message follows a user message, the adapter puts its tool_result block 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: true gets cache_control (see Prompt caching).
  • No system option: the request has no system parameter. An empty string or empty array is sent as given.
  • The meaning of the option is in the types README.

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, invoke throws 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) sends cache_control: { type: 'ephemeral' }, as before. '1h' sends cache_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 a cachePoint at 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 that autoCache rewrites every turn stays at the cheaper 5 minutes.
  • auto is ignored when autoCache is off.
  • Ordering. Anthropic needs a longer TTL before a shorter one, and the autoCache marker is always last. So:
    • autoCache with points: '5m' and auto: '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 autoCache on and different TTLs, a cachePoint on the request's last block (the block autoCache marks) throws in invoke, 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 cachePoint part-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. inputTokens is now the total input: Anthropic's input_tokens (the uncached part) plus cache_read_input_tokens plus cache_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 with contextWindowSize.

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 })
  • invoke rejects with signal.reason (an AbortError or TimeoutError DOMException for the default reasons), not with the SDK's APIUserAbortError.
  • Already aborted when invoke is called: it rejects at once, with no event and no request.
  • Aborted after "llm.request": "llm.error" is emitted with error: signal.reason, then invoke rejects with it.
  • The one-time context-window lookup on the first call is not cancelled; if the signal aborts during it, invoke rejects 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 invoke
  • maxRetries: 0 turns the SDK's retries off. Use it when your code owns the retry policy, or when a signal deadline 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 the messages, tools and system passed to invoke as given (the mock does no translation) and "llm.response" carries the returned response as output.
  • latencyMs — waits that long before answering. The wait listens to the call's signal, so a test can cut a slow call with AbortSignal.timeout() or ctx.signal.
  • Abort behaves as in the adapter: already aborted → rejects with signal.reason and emits nothing; aborted while waiting → "llm.error" with signal.reason, then rejects with it.
  • "llm.response" tokens are the usage of the returned response (reasoning / cacheRead / cacheWrite / cacheWriteByTtl only when that usage has them).
  • lastMessages and lastOptions hold the messages and the options (tools, signal, system; not telemetry) 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

License

MIT