Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

test(agent): assert the prompt-cache breakpoint on the wire (#90)

Matthew Kissinger23f674c14300
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0620676f..30e7a970 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,51 @@
Changes to `@kiln/engine`. Source and installable packages are distributed through
GitHub. The package is not published on the npm registry.
+## The prompt-cache breakpoint is asserted on the wire — 2026-09-12
+
+- The two deferred rows in the queue were both deferred *with a reason*. Checking the
+ reasons rather than inheriting them changed both answers.
+- **The `ai` 7 family is blocked upstream, and money was never the constraint.** The
+ recorded reason was that only `test:live` exercises those paths and it spends money.
+ What actually blocks it: `@strands-agents/[email protected]` is the latest release, declares
+ peer `@ai-sdk/provider: ^3.0.0`, and types its `VercelModel` on `LanguageModelV3`,
+ while `@openrouter/ai-sdk-provider@3` requires `ai@^7`, which depends on
+ `@ai-sdk/provider@4`. No budget moves that.
+- And `typecheck` would not have caught it. `@ai-sdk/provider@4` still exports
+ `LanguageModelV3` beside V4, so the import keeps compiling; the break is a v4 model
+ handed to a v3 wrapper, at runtime, on the one path no offline suite drives. There is
+ a gate for it now: `scripts/peer-ranges.test.mjs` walks the installed tree and fails
+ on a peer range the version beside it does not meet.
+- **It found a mismatch that already exists.** `@strands-agents/sdk` declares peer
+ `@anthropic-ai/sdk: ^0.109.1` — on a 0.x version that means `>=0.109.1 <0.110.0` —
+ and the last dependency refresh took 0.125.0. Fifteen minors past the declared
+ range, moved by a routine in-range update, noticed by nothing. Kept, and listed with
+ its reasoning in the gate's `ACCEPTED` table, so the next one fails while this one is
+ a decision on the record rather than a silence.
+- **The native cache breakpoint is now asserted against the bytes.** The OpenRouter
+ half already was: it drives `doStream` with `fetch` replaced and reads the outgoing
+ JSON. The native half asserted that `toCachedSystemPrompt` returns
+ `[TextBlock, CachePointBlock]` — the input to the transport, never its output. So the
+ claim the design rests on, that a cache point becomes `cache_control` on the wire,
+ was carried by a comment, on two dependencies that move inside their caret ranges on
+ every refresh. Losing it bills full price for every prefix that should have been a
+ cache read, with every offline gate green.
+- Both native transports are captured now, offline: the Anthropic client takes a
+ `fetch` that records and throws, Bedrock a `requestHandler` that does the same. Both
+ tests are differential — a plain string goes out with no breakpoint — so the
+ breakpoint has one possible origin. Establishing that took an injected defect, which
+ disproved the first draft's premise: Bedrock does *not* auto-inject a system cache
+ point here, because that needs a `cacheConfig` and Kiln passes none. Patching the
+ installed adapters to drop `cache_control` and the converse `cachePoint` fails
+ exactly the new tests while every pre-existing test stays green — including the one
+ named "the adapter emits `cache_control`", which never checked that it did.
+- **7.12 / SEP-2640 stays deferred, for a better reason.** PR 2640 is open and still
+ labelled `draft`; a page summary reported it Final for the second time and was wrong
+ again. But the row turns on something downstream: `@modelcontextprotocol/sdk`
+ publishes 1.30.0 as latest, the version already installed, so there is no TypeScript
+ surface for `skill://` resources to build against whatever the SEP does next. Check
+ the SDK's version, not the pull request.
+
## A preset's shadow filter now selects a filter — 2026-09-12
- Going to compare shadow filters by eye turned up the reason there was nothing to
diff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
index e1aa0f42..22af687a 100644
--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md
+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
@@ -1642,10 +1642,102 @@ is what separated "the rig is wrong" from "the backend cannot do this".
- **7.12 / SEP-2640.** Still `In Review` on the Skills Over MCP working group's own
board, with the reference implementation also in review. Nothing to build against.
Re-checked 2026-09-11; the first summary read claimed it had gone Final, and that
- was wrong -- the charter is the authority, not a page summary.
+ was wrong -- the charter is the authority, not a page summary. Re-checked again
+ 2026-09-12 and superseded by Phase 14: the row now turns on the TypeScript SDK's
+ version, not on the SEP's status.
- **The `ai` 7 / `@ai-sdk/provider` 4 / `@openrouter/ai-sdk-provider` 3 family.**
Deferred by decision. Only `test:live` exercises those paths, it spends money, and
the deliberate prompt-cache transport asymmetry is exactly what a provider major
breaks silently. 13.2 deliberately takes the in-range updates and leaves these.
+ **Superseded by Phase 14**, which checked this reason rather than inheriting it:
+ the family is blocked upstream and the money was never the binding constraint.
- **11.4.** Answered: the CLI already joins a running service, and auto-spawn would
make a one-shot command pay a GPU startup it cannot amortize.
+
+
+## Phase 14 -- The two deferred rows, re-grounded
+
+Opened 2026-09-12, after Phase 13 closed. Nothing here was queued work. Both rows
+left open were deferred *with a reason*, and this phase checked the reasons instead
+of inheriting them. One held for a different cause than the one recorded, one was
+wrong, and the wrong one was sitting on top of a mismatch that already exists in
+the installed tree.
+
+| ID | Task | State |
+| --- | --- | --- |
+| 14.1 | Re-ground 7.12 / SEP-2640 against an authoritative source | **Done 2026-09-12.** Deferred still, for a stronger reason. See below |
+| 14.2 | Establish what actually blocks the `ai` 7 family, and gate it | **Done 2026-09-12.** `@strands-agents/[email protected]` is latest, declares peer `@ai-sdk/provider: ^3.0.0`, and its `VercelModel` is typed on `LanguageModelV3` in 21 places. `@openrouter/[email protected]` requires `ai: ^7.0.0`; `[email protected]` depends on `@ai-sdk/[email protected]`. The family cannot be taken until Strands ships a release accepting the v4 spec -- no budget changes that. `scripts/peer-ranges.test.mjs` now fails on a peer range the version beside it does not meet, verified by patching the installed `@openrouter/ai-sdk-provider` manifest to peer `ai: ^7.0.0` and watching it report `installed 6.0.282` |
+| 14.3 | Assert the prompt-cache breakpoint on the wire, offline | **Done 2026-09-12.** Both native transports captured in `src/agent/providers.test.ts`, both differential. See below |
+
+### 14.1 -- the decisive fact is not the SEP's status
+
+Checked against the GitHub API rather than a rendered page: PR 2640 is `OPEN`,
+neither merged nor closed, labelled `SEP`, `draft` ("SEP proposal with a sponsor")
+and `extension`, last updated 2026-09-11T22:34Z. A page summary again reported it
+as accepted and "now Final, with reference implementations and conformance tests in
+place." That is the **second** time the same summary has been wrong about this row,
+so the 2026-09-11 note is now load-bearing rather than incidental: read the labels,
+not the prose.
+
+What actually settles the row sits downstream of the SEP. `@modelcontextprotocol/sdk`
+publishes **1.30.0** as latest -- the exact version installed here, at protocol
+2025-11-25. There is no TypeScript surface for `skill://` resources to build
+against, so ratification tomorrow would still leave nothing to implement. The thing
+to re-check is the SDK's version, not the pull request's.
+
+### 14.2 -- why a peer range needed a gate of its own
+
+The repository's recurring defect is a value that must agree across files with
+nothing enforcing it. A peer range is that shape one level out: the agreement is
+between manifests this repository does not own, `bun install` warns and installs
+anyway, and the code that breaks is a provider adapter reached only through the
+agent loop.
+
+`typecheck` looks like it would catch this and does not.
+`@ai-sdk/[email protected]` still exports `LanguageModelV3` beside V2 and V4, so
+`import type { LanguageModelV3 }` keeps compiling after the bump; the break is a v4
+model handed to a v3 wrapper, at runtime, on a path only `test:live` drives.
+
+**The mismatch that already exists.** The peer walk found one, and it is not the
+deferred family: `@strands-agents/[email protected]` declares peer
+`@anthropic-ai/sdk: ^0.109.1`, which on a 0.x version resolves to
+`>=0.109.1 <0.110.0`, and 13.2 took **0.125.0**. Fifteen minors past the range its
+author declares, moved by a routine in-range refresh, noticed by nothing. Kept
+rather than reverted -- the surface Kiln uses is `messages.stream` plus
+system-prompt formatting -- and listed in the gate's `ACCEPTED` table with that
+reasoning, so a *second* mismatch fails while this one is a decision on the record.
+The staleness arm is gated too: an accepted entry that stops mismatching must be
+dropped, verified by widening the range in the installed manifest and watching the
+test say so.
+
+### 14.3 -- what "only `test:live` exercises those paths" was hiding
+
+Half true, and the wrong half had been assumed.
+
+The OpenRouter side already asserted the bytes: it drives `doStream` with
+`globalThis.fetch` replaced and reads `cache_control` and `provider.sort` out of the
+outgoing JSON. The native side asserted that `toCachedSystemPrompt` returns
+`[TextBlock, CachePointBlock]` and that those carry the discriminators the adapters
+branch on -- the **input** to the transport, never its output. So the claim the whole
+design rests on, that a cache point becomes `cache_control` on the wire, was carried
+by a comment. Both native dependencies move inside their caret ranges on every
+refresh, and losing this silently bills full price for every prefix that should have
+been a cache read while every offline gate stays green.
+
+Both native transports are now captured offline: the Anthropic client takes a
+`fetch` that records and throws, the Bedrock client a `requestHandler` that does the
+same, and neither test reaches the network. Both are differential -- a plain string
+goes out with no breakpoint at all -- so the breakpoint has exactly one possible
+origin.
+
+Establishing that took an injected defect. The first draft asserted that Bedrock
+auto-injects a system cache point for `anthropic`/`claude` model ids and that Kiln's
+block array is therefore redundant there. It does not:
+`_shouldEnableCaching()` returns false when no `cacheConfig` was passed, and Kiln
+passes none to either native provider. `toCachedSystemPrompt` is the sole mechanism
+on all three transports.
+
+Verified the way the rest of this queue was -- by patching the installed Strands
+adapters to drop `cache_control` and the converse `cachePoint`. Each injection fails
+exactly the new test while **every pre-existing test stays green**, including the one
+named "the adapter emits `cache_control`", which never checked that it did.
diff --git a/scripts/peer-ranges.test.mjs b/scripts/peer-ranges.test.mjs
new file mode 100644
index 00000000..d0b69c44
--- /dev/null
+++ b/scripts/peer-ranges.test.mjs
@@ -0,0 +1,151 @@
+/**
+ * Peer ranges the installed tree does not satisfy.
+ *
+ * WHY THIS EXISTS: the repository's recurring defect is a value that must agree
+ * across files with nothing enforcing it, and a peer range is that shape one
+ * level out -- the agreement is between manifests this repository does not own.
+ * `bun install` warns and installs anyway, `typecheck` only sees what the types
+ * export, and the code that actually breaks is a provider adapter. Kiln's agent
+ * path is exactly that: `@strands-agents/sdk` wraps `@anthropic-ai/sdk`,
+ * `@aws-sdk/client-bedrock-runtime` and a Vercel `LanguageModelV3`, so a peer
+ * range it stops satisfying is a runtime failure in the loop, and the only suite
+ * that drives the loop for real is `test:live` -- opt-in, billed, not in CI.
+ *
+ * Two live cases, both verified rather than hypothetical:
+ *
+ * - One mismatch exists today and is accepted below with its reason.
+ * - The deferred `ai` 7 family would add a second. `@ai-sdk/[email protected]`
+ * still exports `LanguageModelV3` alongside V4, so taking it typechecks
+ * clean; the break is a v4 model handed to a wrapper expecting v3, at
+ * runtime. This is the gate that names it at install time instead.
+ */
+import { test, expect, describe } from 'bun:test';
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// `fileURLToPath`, not `.pathname`: on Windows the latter yields `/C:/...`, which
+// `join` then treats as a root-relative path. The Windows job blocks merges.
+const repo = fileURLToPath(new URL('../', import.meta.url));
+
+/** Read an installed manifest, or undefined when the package is not in the tree. */
+function installedManifest(name) {
+ const path = join(repo, 'node_modules', name, 'package.json');
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : undefined;
+}
+
+/**
+ * Every peer range a package declares that the version beside it does not meet.
+ *
+ * Only packages this repository names are walked, and only peers that are
+ * actually installed are judged -- an absent optional peer is not a mismatch,
+ * and a transitive dependency's peers are its own resolver's problem. A peer
+ * that is installed is judged whether or not it is marked optional: optional
+ * describes whether it must be present, not whether the version may be wrong.
+ */
+export function peerMismatches(declared, readManifest = installedManifest) {
+ const mismatches = [];
+ for (const name of Object.keys(declared).sort()) {
+ const manifest = readManifest(name);
+ for (const [peer, range] of Object.entries(manifest?.peerDependencies ?? {})) {
+ const resolved = readManifest(peer);
+ if (!resolved) continue;
+ if (Bun.semver.satisfies(resolved.version, range)) continue;
+ mismatches.push({ package: name, wants: peer, range, installed: resolved.version });
+ }
+ }
+ return mismatches;
+}
+
+/**
+ * Mismatches this repository has looked at and decided to run anyway, each with
+ * the evidence that the pairing works. A new entry is a deliberate decision, not
+ * a lockfile refresh: that is the whole point of listing them.
+ */
+const ACCEPTED = [
+ {
+ // Strands lags the Anthropic SDK's 0.x minors by a wide margin -- ^0.109.1
+ // resolves to >=0.109.1 <0.110.0 -- and 13.2 took 0.125.0 without anything
+ // noticing. Kept, because the surface Kiln depends on is `messages.stream`
+ // plus system-prompt formatting, and the cache breakpoint that rides on it
+ // is now asserted against the outgoing request body offline, in
+ // src/agent/providers.test.ts. If that pairing ever breaks, those tests fail
+ // in CI rather than the next live run failing in front of a user.
+ package: '@strands-agents/sdk',
+ wants: '@anthropic-ai/sdk',
+ },
+];
+
+describe('peer ranges', () => {
+ test('the installed tree has no unaccepted peer mismatch', () => {
+ const root = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf8'));
+ const declared = {
+ ...root.dependencies,
+ ...root.devDependencies,
+ ...root.peerDependencies,
+ };
+ const found = peerMismatches(declared);
+ const unaccepted = found.filter(
+ (m) => !ACCEPTED.some((a) => a.package === m.package && a.wants === m.wants),
+ );
+ expect(
+ unaccepted.map((m) => `${m.package} wants ${m.wants}@${m.range}, installed ${m.installed}`),
+ ).toEqual([]);
+ // ...and an accepted entry that has stopped happening is stale bookkeeping.
+ for (const accepted of ACCEPTED) {
+ expect(
+ found.some((m) => m.package === accepted.package && m.wants === accepted.wants),
+ `${accepted.package} no longer mismatches ${accepted.wants}; drop it from ACCEPTED`,
+ ).toBe(true);
+ }
+ });
+
+ test('it names the Strands pin that blocks the deferred ai 7 family', () => {
+ // The real published versions, so this case stops passing the day Strands
+ // ships a release that accepts the v4 provider spec.
+ const tree = {
+ '@openrouter/ai-sdk-provider': { version: '3.0.0', peerDependencies: { ai: '^7.0.0' } },
+ ai: { version: '7.0.99' },
+ '@ai-sdk/provider': { version: '4.0.14' },
+ '@strands-agents/sdk': {
+ version: '1.17.0',
+ peerDependencies: { '@ai-sdk/provider': '^3.0.0' },
+ },
+ };
+ const found = peerMismatches(tree, (name) => tree[name]);
+ expect(found).toEqual([
+ {
+ package: '@strands-agents/sdk',
+ wants: '@ai-sdk/provider',
+ range: '^3.0.0',
+ installed: '4.0.14',
+ },
+ ]);
+ });
+
+ test('a tree that agrees reports nothing', () => {
+ // A rule that always fires is as useless as one that never does. These are
+ // the versions actually installed here, and the family below is the one the
+ // case above rejects, one major back.
+ const tree = {
+ '@openrouter/ai-sdk-provider': { version: '2.10.0', peerDependencies: { ai: '^6.0.0' } },
+ ai: { version: '6.0.282' },
+ '@ai-sdk/provider': { version: '3.0.16' },
+ '@strands-agents/sdk': {
+ version: '1.17.0',
+ peerDependencies: { '@ai-sdk/provider': '^3.0.0' },
+ },
+ };
+ expect(peerMismatches(tree, (name) => tree[name])).toEqual([]);
+ });
+
+ test('an absent peer is not a mismatch, but an installed optional one is judged', () => {
+ const absent = {
+ host: { version: '1.0.0', peerDependencies: { plugin: '^2.0.0' } },
+ };
+ expect(peerMismatches(absent, (name) => absent[name])).toEqual([]);
+
+ const present = { ...absent, plugin: { version: '3.1.0' } };
+ expect(peerMismatches(present, (name) => present[name])).toHaveLength(1);
+ });
+});
diff --git a/src/agent/providers.test.ts b/src/agent/providers.test.ts
index a3691174..e96d7f95 100644
--- a/src/agent/providers.test.ts
+++ b/src/agent/providers.test.ts
@@ -8,7 +8,9 @@
* keys so native construction never touches the network).
*/
import { test, expect, describe, beforeAll, afterAll } from 'bun:test';
-import { CachePointBlock, TextBlock } from '@strands-agents/sdk';
+import { CachePointBlock, Message, TextBlock, type SystemPrompt } from '@strands-agents/sdk';
+import { AnthropicModel } from '@strands-agents/sdk/models/anthropic';
+import { BedrockModel } from '@strands-agents/sdk/models/bedrock';
import {
resolveKilnAgentModel,
makeKilnModel,
@@ -504,3 +506,140 @@ describe('OpenRouter-Anthropic prompt caching (cache_control)', () => {
expect(toCachedSystemPrompt('SYSTEM', model)).toBe('SYSTEM');
});
});
+
+/**
+ * The cache breakpoint, asserted against the bytes that leave the process.
+ *
+ * The OpenRouter half above already does this: it drives `doStream` with
+ * `globalThis.fetch` replaced and reads the outgoing JSON. The native half did
+ * not. It asserted that `toCachedSystemPrompt` returns `[TextBlock,
+ * CachePointBlock]` and that those carry the discriminators the adapters branch
+ * on -- which is the INPUT to the transport, not its output. So the claim the
+ * whole design rests on, that a cache point becomes `cache_control` on the wire,
+ * was carried by a comment and by `test:live`: opt-in, billed, and absent from
+ * CI. `@anthropic-ai/sdk` and `@aws-sdk/client-bedrock-runtime` both move inside
+ * their caret ranges on every dependency refresh, and losing this silently bills
+ * full price for every prefix that should have been a cache read while every
+ * offline gate stays green.
+ *
+ * Neither test reaches the network: the Anthropic client takes a `fetch` that
+ * records and throws, the Bedrock client a `requestHandler` that does the same.
+ */
+describe('the cache breakpoint reaches the wire (captured transports, no network)', () => {
+ const TEXT = 'You generate exportable 3D game assets as Kiln code.';
+
+ /**
+ * Run a real `stream()` against a transport that records one request and fails.
+ *
+ * The recorded body is decoded rather than coerced: Bedrock hands its request
+ * handler a `Uint8Array`, and `@aws-sdk/core` shims it to warn when a consumer
+ * calls a string method on it -- a warning today and, the shim says, a throw
+ * later. Anthropic's `fetch` gets a string, so both shapes arrive here.
+ */
+ async function captureRequest(
+ model: {
+ stream(messages: Message[], options: { systemPrompt: SystemPrompt }): AsyncIterable<unknown>;
+ },
+ systemPrompt: SystemPrompt,
+ read: () => string | Uint8Array | undefined,
+ ): Promise<Record<string, unknown>> {
+ const messages = [new Message({ role: 'user', content: [new TextBlock('hi')] })];
+ let failure: unknown;
+ try {
+ for await (const _event of model.stream(messages, { systemPrompt })) {
+ // The transport throws on the first request, so no event ever arrives.
+ }
+ } catch (error) {
+ failure = error;
+ }
+ const sent = read();
+ // Rethrow rather than report "no request": if construction or formatting threw
+ // before the transport ran, that error is the finding, not this assertion.
+ if (sent === undefined) throw failure ?? new Error('the transport was never called');
+ const text = typeof sent === 'string' ? sent : new TextDecoder().decode(sent);
+ return JSON.parse(text) as Record<string, unknown>;
+ }
+
+ function anthropicModel(): {
+ model: AnthropicModel;
+ read: () => string | undefined;
+ } {
+ let body: string | undefined;
+ const model = new AnthropicModel({
+ modelId: 'claude-opus-4-8',
+ apiKey: 'test-key',
+ maxTokens: 1024,
+ clientConfig: {
+ maxRetries: 0,
+ fetch: (async (_url: unknown, init: { body: string }) => {
+ body = init.body;
+ throw new Error('captured by the test transport');
+ }) as unknown as typeof fetch,
+ },
+ });
+ return { model, read: () => body };
+ }
+
+ test('a plain string system prompt goes out uncached — nothing else adds the breakpoint', async () => {
+ // Kiln passes no `cacheConfig`, so the adapter's own caching is off and a
+ // string is forwarded verbatim. This is what makes the next test
+ // differential: `cache_control` below can only have come from Kiln's blocks.
+ const { model, read } = anthropicModel();
+ const body = await captureRequest(model, TEXT, read);
+ expect(body['system']).toBe(TEXT);
+ });
+
+ test('toCachedSystemPrompt becomes cache_control on the system text block', async () => {
+ const { model, read } = anthropicModel();
+ const shaped = toCachedSystemPrompt(TEXT, model);
+ expect(Array.isArray(shaped)).toBe(true);
+ const body = await captureRequest(model, shaped, read);
+ expect(body['system']).toEqual([
+ { type: 'text', text: TEXT, cache_control: { type: 'ephemeral' } },
+ ]);
+ });
+
+ function bedrockModel(modelId: string): {
+ model: BedrockModel;
+ read: () => Uint8Array | string | undefined;
+ } {
+ let sent: Uint8Array | string | undefined;
+ const model = new BedrockModel({
+ modelId,
+ region: 'us-west-2',
+ maxTokens: 1024,
+ clientConfig: {
+ maxAttempts: 1,
+ credentials: { accessKeyId: 'test-key-id', secretAccessKey: 'test-secret' },
+ requestHandler: {
+ handle: (request: { body: Uint8Array | string }) => {
+ sent = request.body;
+ throw new Error('captured by the test transport');
+ },
+ },
+ },
+ });
+ return { model, read: () => sent };
+ }
+
+ test("Bedrock converse: a plain string carries no cachePoint, Kiln's blocks add one", async () => {
+ // Differential for the same reason as the Anthropic pair, and it took an
+ // injected defect to establish it: the adapter CAN auto-inject a system cache
+ // point for a model id containing `anthropic` or `claude`, but only when it
+ // was given a `cacheConfig`, and Kiln passes none to either native provider.
+ // So on all three transports `toCachedSystemPrompt` is the sole mechanism,
+ // and the entry below has exactly one possible origin.
+ const plain = bedrockModel('global.anthropic.claude-opus-4-8');
+ expect(await captureRequest(plain.model, TEXT, plain.read)).toMatchObject({
+ system: [{ text: TEXT }],
+ });
+
+ const cached = bedrockModel('global.anthropic.claude-opus-4-8');
+ const body = await captureRequest(
+ cached.model,
+ toCachedSystemPrompt(TEXT, cached.model),
+ cached.read,
+ );
+ expect(body['system']).toEqual([{ text: TEXT }, { cachePoint: { type: 'default' } }]);
+ });
+});