Skip to content

[Bug] strands-agents (TypeScript): proactive compression ignores the model's context window #157

Closed

Description

@campoy

What are you really trying to do?

Run a Strands agent with proactive compression
(new SlidingWindowConversationManager({ proactiveCompression: true })) as a TemporalAgent, and have
it compress at the same point as the same agent outside Temporal.

Describe the bug

TemporalAgent replaces the agent's model with a TemporalModel, whose getConfig() returns {}
because the real model lives on the Worker (typescript/strands-agents/src/temporal-model.ts).
Strands' conversation manager runs in Workflow code and reads contextWindowLimit from that
getConfig(). With no limit it falls back to 200,000 tokens and logs contextWindowLimit is not set on the model, using default of 200000.

So every TemporalAgent compresses at 70% of 200,000 tokens, whatever its model. With a model whose
window is larger (for example gpt-4.1, 1,047,576 tokens, or the plugin's default Bedrock model,
1,000,000) the agent drops turns that the native agent keeps. With a smaller window (gpt-4o,
128,000) it keeps turns that the native agent drops and sends a larger request. The run completes
and nothing fails. Strands' agent and model spans also lose the model id, which comes from the same
getConfig().

Minimal Reproduction

Two files, repro.cjs and workflows.cjs (below). A Worker-side fake Model
has { modelId: 'fake-model', contextWindowLimit: 1000 } and reports 800 input tokens for its first
reply, 80% of its window. The script runs two turns on a native Agent and on a TemporalAgent,
both with proactive compression, and compares the second model call and getConfig().

repro.cjs:

'use strict';
// Strands' proactive compression on a TemporalAgent uses the model's context window, as natively.
// The model has a 1,000-token window and its first reply reports 800 input tokens (80%, over the
// default 70% threshold), so the agent should drop turn 1 before the second model call.
// Exits 0 when the plugin matches the native agent, 1 otherwise.
//   STRANDS_TS_ENV=<dir whose node_modules has @strands-agents/sdk, @temporalio/strands-agents,
//   @temporalio/worker and @temporalio/testing> node repro.cjs
const assert = require('node:assert/strict');
const path = require('node:path');
const { createRequire } = require('node:module');

const req = createRequire(path.join(process.env.STRANDS_TS_ENV, 'package.json'));
const { Agent, Model, SlidingWindowConversationManager } = req('@strands-agents/sdk');
const { StrandsPlugin } = req('@temporalio/strands-agents');
const { Worker, DefaultLogger, Runtime } = req('@temporalio/worker');
const { TestWorkflowEnvironment } = req('@temporalio/testing');

const calls = [];
class FakeModel extends Model {
  getConfig() {
    return { modelId: 'fake-model', contextWindowLimit: 1000 };
  }
  updateConfig() {}
  async *stream(messages) {
    const turns = messages.filter((m) => m.role === 'user').map((m) => m.content[0].text);
    calls.push(turns);
    const inputTokens = turns.at(-1) === 'turn 1' ? 800 : 10;
    yield { type: 'modelMessageStartEvent', role: 'assistant' };
    yield { type: 'modelContentBlockStartEvent' };
    yield { type: 'modelContentBlockDeltaEvent', delta: { type: 'textDelta', text: 'ok' } };
    yield { type: 'modelContentBlockStopEvent' };
    yield { type: 'modelMessageStopEvent', stopReason: 'endTurn' };
    yield { type: 'modelMetadataEvent', usage: { inputTokens, outputTokens: 1, totalTokens: inputTokens + 1 } };
  }
}

async function main() {
  const conversationManager = () => new SlidingWindowConversationManager({ proactiveCompression: true });
  const native = new Agent({ model: new FakeModel(), printer: false, conversationManager: conversationManager() });
  await native.invoke('turn 1');
  await native.invoke('turn 2');
  const nativeResult = { config: native.model.getConfig(), secondCall: calls.splice(0)[1] };
  console.log('native', JSON.stringify(nativeResult));

  Runtime.install({ logger: new DefaultLogger('ERROR') });
  const cli = process.env.TEMPORAL_CLI; // optional: an installed Temporal CLI instead of a download
  const env = await TestWorkflowEnvironment.createLocal(
    cli ? { server: { executable: { type: 'existing-path', path: cli } } } : undefined
  );
  let pluginResult;
  try {
    const worker = await Worker.create({
      connection: env.nativeConnection,
      taskQueue: 'repro',
      workflowsPath: require.resolve('./workflows.cjs'),
      bundlerOptions: {
        webpackConfigHook(config) {
          config.resolve.modules = [...(config.resolve.modules ?? []), path.join(process.env.STRANDS_TS_ENV, 'node_modules')];
          return config;
        },
      },
      plugins: [new StrandsPlugin({ models: { fake: () => new FakeModel() } })],
    });
    const config = await worker.runUntil(env.client.workflow.execute('twoTurns', { taskQueue: 'repro', workflowId: 'repro' }));
    pluginResult = { config, secondCall: calls.splice(0)[1] };
  } finally {
    await env.teardown();
  }
  console.log('plugin', JSON.stringify(pluginResult));
  assert.deepEqual(pluginResult, nativeResult);
  console.log('PASS: the TemporalAgent matches the native agent');
}

main().catch((err) => {
  console.error(err.message);
  console.log('FAIL: the TemporalAgent differs from the native agent');
  process.exitCode = 1;
});

workflows.cjs:

'use strict';
const { SlidingWindowConversationManager } = require('@strands-agents/sdk');
const { TemporalAgent } = require('@temporalio/strands-agents');

async function twoTurns() {
  const agent = new TemporalAgent({
    model: 'fake',
    printer: false,
    conversationManager: new SlidingWindowConversationManager({ proactiveCompression: true }),
  });
  await agent.invoke('turn 1');
  await agent.invoke('turn 2');
  return agent.model.getConfig();
}

module.exports = { twoTurns };

Run:

STRANDS_TS_ENV=<dir with @strands-agents/sdk, @temporalio/strands-agents, @temporalio/worker, @temporalio/testing> node repro.cjs

Output with @temporalio/strands-agents 1.24.0 (and the same on main):

native {"config":{"modelId":"fake-model","contextWindowLimit":1000},"secondCall":["turn 2"]}
plugin {"config":{},"secondCall":["turn 1","turn 2"]}
FAIL: the TemporalAgent differs from the native agent

Expected: the plugin line equals the native line.

Environment/Versions

  • OS and processor: Linux container on Apple Silicon (not OS-specific)
  • Temporal Version: @temporalio/strands-agents 1.24.0 with @strands-agents/sdk 1.6.0, and
    typescript/strands-agents at ai-integrations main (5e91c26) with its locked
    @strands-agents/sdk 1.19.0; @temporalio/worker 1.24.0; Node 24.22.0; Temporal CLI 1.9.1
  • Are you using Docker or Kubernetes or building Temporal from source? A local dev server
    (TestWorkflowEnvironment.createLocal)

Additional context

Proposed fix, with a test and a version gate: before Strands initializes a TemporalAgent, read the
Worker model's modelId and contextWindowLimit through a small Activity (only those two fields, so
provider settings such as API keys stay out of history), and return them from
TemporalModel.getConfig(). Gate it with patched() so agents that open runs initialized before the
upgrade keep the empty config. This is a breaking change for anyone who scaled compressionThreshold
by window / 200,000 to work around the missing limit: they need to remove that scaling. I'm opening
a PR with the patch and tests. The Python Strands integration has the
same gap and should be fixed separately.

Activity

  1. added
    bug
    on Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions