Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/coding-agent/docs/environment-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Step reads the variables below. Configuration shared across launches belongs in
| `STEP_AUTOPILOT` | Retired tier selector; resets to Ask. Select a new tier instead |
| `STEP_API_KEY` | StepFun API credential |
| `STEP_BASE_URL` | Override the StepFun API endpoint |
| `STEP_CLIENT` | The product every Step request names in `x-step-client`: `stepcode-cli` (the default), `stepcode-desktop`, `stepcode-web`; a host that sets it keeps its value |
| `STEP_CLIENT` | The product every Step request names in `x-step-client` and in the provider `User-Agent` as `<client>/<version>`: `stepcode-cli` (the default), `stepcode-desktop`, `stepcode-web`; a host that sets it keeps its value |
| `STEP_PROVIDER`, `STEP_MODEL` | Default provider and model selection |
| `VISUAL`, `EDITOR` | External editor fallback when `externalEditor` is unset |
| `HTTP_PROXY`, `HTTPS_PROXY` | Proxy outbound HTTP requests |
Expand Down
12 changes: 12 additions & 0 deletions packages/coding-agent/docs/step-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ version embedded by the release build, or `STEPCODE_VERSION_OVERRIDE` when set.
Source runs report the fallback development version. The server reads the two
headers together, so each product's minimum version is configured separately.

Every model request appends the same pair to the provider `User-Agent`:

```text
stepcode (darwin 25.1.0; arm64) stepcode-cli/1.4.2
```

The first token stays the runtime identity; `stepcode-cli/1.4.2` is the client
product and release, so a provider-side log can tell a stale desktop build from
a current CLI without reading Step's own headers. The model collection sets the
identity once at construction, so every request path — session turns,
compaction, and other `completeSimple()` callers — reports it.

Set `STEP_PROVIDER`, `STEP_MODEL`, `STEP_API_KEY`, or the provider endpoint
variables to override the defaults. The Step launcher also disables upstream
release and install checks so the product does not contact those services.
Expand Down
26 changes: 24 additions & 2 deletions packages/coding-agent/src/core/model-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ import {
type ProviderRequestOptions,
type SimpleStreamOptions,
type StreamOptions,
type UserAgentClient,
} from "@step-harness/providers";
import * as builtinProviderCatalog from "@step-harness/providers/providers/all";
import { getAgentDir, STEP_ENTRYPOINT } from "../config.ts";
import { resolveStepClientIdentity } from "../step/client-identity.ts";
import { operationSignal, raceWithAbortSignal } from "../utils/abort.ts";
import { AuthStorage as DefaultAuthStorage } from "./auth-storage.ts";
import { ModelConfig } from "./model-config.ts";
Expand Down Expand Up @@ -82,6 +84,12 @@ export interface CreateModelRuntimeOptions {
* Defaults to false under the Step entrypoint (StepFun-only), true otherwise.
*/
includeDefaultBuiltins?: boolean;
/**
* Product identity appended to the provider `User-Agent` as `name/version`.
* Defaults to the resolved Step client identity (`STEP_CLIENT` plus the build
* version), so a host only overrides it to report something else.
*/
userAgent?: UserAgentClient;
}

export interface ModelRuntimeAuthOverrides extends AuthOperationOptions {
Expand Down Expand Up @@ -139,6 +147,7 @@ export class ModelRuntime implements Models {
private readonly extensionProviders = new Map<string, ProviderConfigInput>();
private readonly compositionErrors = new Map<string, string>();
private readonly modelsPath: string | undefined;
private readonly userAgent: UserAgentClient;
private config: ModelConfig;
private snapshot: ModelRuntimeSnapshot = {
all: [],
Expand All @@ -159,13 +168,17 @@ export class ModelRuntime implements Models {
modelsPath: string | undefined,
modelsStore: ModelsStore,
providers: readonly Provider[],
userAgent: UserAgentClient,
) {
this.credentials = credentials;
this.config = config;
this.modelsPath = modelsPath;
this.userAgent = userAgent;
this.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));
for (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);
this.models = createModels({ credentials, modelsStore });
// Every model request this runtime dispatches names the product that sent
// it, so provider logs can attribute traffic to a client release.
this.models = createModels({ credentials, modelsStore, userAgent });
this.rebuildProviders();
}

Expand All @@ -181,7 +194,14 @@ export class ModelRuntime implements Models {
: new InMemoryCodingAgentModelsStore());
const includeDefaultBuiltins = options.includeDefaultBuiltins ?? !STEP_ENTRYPOINT;
const providers = includeDefaultBuiltins ? builtinProviderCatalog.builtinProviders() : [];
const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers);
const runtime = new ModelRuntime(
credentials,
config,
modelsPath,
modelsStore,
providers,
options.userAgent ?? resolveStepClientIdentity(),
);
runtime.resetBuiltinProviders();
runtime.rebuildProviders();
const refreshFromNetwork = options.allowModelNetwork === true;
Expand Down Expand Up @@ -570,6 +590,7 @@ export class ModelRuntime implements Models {
resolution.env || providerOptions.env
? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }
: undefined;
const userAgent = providerOptions.userAgent ?? this.userAgent;
return {
provider,
model: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,
Expand All @@ -578,6 +599,7 @@ export class ModelRuntime implements Models {
apiKey: providerOptions.apiKey ?? resolution.auth.apiKey,
headers,
env,
...(userAgent === undefined ? {} : { userAgent }),
} as Omit<TOptions, "transformHeaders"> & ProviderRequestOptions,
};
}
Expand Down
5 changes: 5 additions & 0 deletions packages/coding-agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,11 @@ export {
logoutStepCredentials,
migrateLegacyStepCredential,
} from "./step/auth.ts";
export {
resolveStepClientIdentity,
resolveStepClientName,
type StepClientIdentity,
} from "./step/client-identity.ts";
export {
isStepConfigCommand,
normalizeStepSessionSelectorArgs,
Expand Down
30 changes: 30 additions & 0 deletions packages/coding-agent/src/step/client-identity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { UserAgentClient } from "@step-harness/providers";
import { STEP_CLIENT_DEFAULT } from "./environment.ts";
import { STEPCODE_VERSION } from "./version.ts";

/** Which product a Step request came from, and which release of it. */
export interface StepClientIdentity extends UserAgentClient {
readonly name: string;
readonly version: string;
}

/**
* Resolve the product name Step reports to its own server.
*
* `STEP_CLIENT` lets an embedding host name itself (`stepcode-desktop`,
* `stepcode-web`); the CLI keeps the default. Every attribution surface reads
* this function, so the `x-step-client` header and the provider `User-Agent`
* cannot drift apart.
*/
export function resolveStepClientName(env: Record<string, string | undefined> = process.env): string {
return env.STEP_CLIENT?.trim() || STEP_CLIENT_DEFAULT;
}

/**
* Resolve the client identity sent on provider requests: the product name from
* {@link resolveStepClientName} and the Step release version exposed everywhere
* else (build tag, `STEPCODE_VERSION_OVERRIDE`, or the development fallback).
*/
export function resolveStepClientIdentity(env: Record<string, string | undefined> = process.env): StepClientIdentity {
return { name: resolveStepClientName(env), version: STEPCODE_VERSION.value };
}
17 changes: 9 additions & 8 deletions packages/coding-agent/src/step/trace-headers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createHash } from "node:crypto";
import process from "node:process";
import { STEP_CLIENT_DEFAULT } from "./environment.ts";
import { STEPCODE_VERSION } from "./version.ts";
import { resolveStepClientIdentity } from "./client-identity.ts";

/** Values copied from the request context into Step's attribution headers. */
export interface StepTraceContext {
Expand Down Expand Up @@ -54,10 +53,11 @@ const STEP_TRACE_PRODUCT_PROVIDERS = new Set(["stepfunModelProxy", "neocodex"]);
* Add Step attribution headers in place.
*
* `x-step-client` and `x-step-client-version` are sent on every request
* (`STEP_CLIENT_DEFAULT`, or the caller's `clientType` when it names the
* product; the Step product version, or the caller's `clientVersion`). The
* server reads the pair to decide which client releases may use Step-specific
* capacity.
* ({@link resolveStepClientIdentity} — `STEP_CLIENT` or the CLI default, and the
* Step product version — unless the caller's `clientType` / `clientVersion`
* replaces a half). The server reads the pair to decide which client releases
* may use Step-specific capacity; the same identity is appended to the provider
* `User-Agent` as `name/version`.
* The high-sensitivity fields
* (session/workspace/goal/...) are sent only when the request URL matches
* `options.allowedBaseUrls` AND the field appears in
Expand All @@ -71,8 +71,9 @@ export function applyStepTraceHeaders(
trace: StepTraceContext,
options: StepTraceHeaderOptions = {},
): void {
setHeader(headers, "x-step-client", options.clientType ?? STEP_CLIENT_DEFAULT);
setHeader(headers, "x-step-client-version", options.clientVersion ?? STEPCODE_VERSION.value);
const identity = resolveStepClientIdentity();
setHeader(headers, "x-step-client", options.clientType ?? identity.name);
setHeader(headers, "x-step-client-version", options.clientVersion ?? identity.version);

const traceAllowed =
options.requestUrl === undefined ||
Expand Down
24 changes: 23 additions & 1 deletion packages/coding-agent/test/sdk-openrouter-attribution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type Api,
type AssistantMessage,
createAssistantMessageEventStream,
getPiUserAgent,
type Model,
type ProviderHeaders,
type SimpleStreamOptions,
Expand All @@ -15,6 +16,7 @@ import { AuthStorage } from "../src/core/auth-storage.ts";
import { createAgentSession } from "../src/core/sdk.ts";
import { SessionManager } from "../src/core/session-manager.ts";
import { SettingsManager } from "../src/core/settings-manager.ts";
import { resolveStepClientIdentity } from "../src/step/client-identity.ts";

import { createInMemoryModelRegistry, getModelRuntime } from "./model-runtime-test-utils.ts";

Expand Down Expand Up @@ -83,6 +85,18 @@ describe("createAgentSession provider headers", () => {
sessionId?: string;
} = {},
): Promise<ProviderHeaders | undefined> {
const capturedOptions = await captureOptions(model, options);
return capturedOptions?.headers;
}

async function captureOptions(
model: Model<Api>,
options: {
providerHeaders?: Record<string, string>;
requestHeaders?: Record<string, string>;
sessionId?: string;
} = {},
): Promise<SimpleStreamOptions | undefined> {
const settingsManager = SettingsManager.create(cwd, agentDir);

const authStorage = AuthStorage.inMemory({
Expand Down Expand Up @@ -125,13 +139,21 @@ describe("createAgentSession provider headers", () => {
},
);
await stream.result();
return capturedOptions?.headers;
return capturedOptions;
} finally {
session.dispose();
modelRegistry.unregisterProvider(model.provider);
}
}

it("names the Step client and release in the provider User-Agent", async () => {
const captured = await captureOptions(createModel("custom", "https://provider.example/v1"));
const identity = resolveStepClientIdentity();

expect(captured?.userAgent).toEqual(identity);
expect(getPiUserAgent(captured?.userAgent)).toMatch(/^stepcode \([^)]*\) stepcode-cli\/\S+$/u);
});

it("adds StepCode attribution headers for OpenRouter models without changing the provider", async () => {
const headers = await captureHeaders(createModel("openrouter", "https://openrouter.ai/api/v1"));

Expand Down
24 changes: 24 additions & 0 deletions packages/coding-agent/test/step-client-identity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { getPiUserAgent } from "@step-harness/providers";
import { describe, expect, it } from "vitest";
import { resolveStepClientIdentity, resolveStepClientName } from "../src/step/client-identity.ts";
import { STEPCODE_VERSION } from "../src/step/version.ts";

describe("Step client identity", () => {
it("defaults to the CLI product and the release version", () => {
expect(resolveStepClientIdentity({})).toEqual({ name: "stepcode-cli", version: STEPCODE_VERSION.value });
});

it("reports the product the host names, ignoring blank overrides", () => {
expect(resolveStepClientName({ STEP_CLIENT: "stepcode-desktop" })).toBe("stepcode-desktop");
expect(resolveStepClientName({ STEP_CLIENT: " stepcode-web " })).toBe("stepcode-web");
expect(resolveStepClientName({ STEP_CLIENT: " " })).toBe("stepcode-cli");
expect(resolveStepClientName({})).toBe("stepcode-cli");
});

it("appends the identity to the runtime User-Agent", () => {
const identity = resolveStepClientIdentity({});
const userAgent = getPiUserAgent(identity);
expect(userAgent).toMatch(/^stepcode \([^)]*\) stepcode-cli\/\S+$/u);
expect(userAgent.endsWith(` stepcode-cli/${STEPCODE_VERSION.value}`)).toBe(true);
});
});
14 changes: 14 additions & 0 deletions packages/providers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,20 @@ Both overloads resolve credentials, refresh expired OAuth when necessary, and ma

`getAuth()`, `checkAuth()`, `getAvailable()`, login, and logout accept optional caller cancellation through their existing options or interaction objects and remain unbounded when no signal is supplied. Provider `login`, `ApiKeyAuth.check`, `ApiKeyAuth.resolve`, and `OAuthAuth.refresh` implementations always receive a concrete signal and must honor it for blocking work.

### Identifying the Client

Every request sends the `stepcode (platform release; arch)` runtime token in `User-Agent`. A composition root also names the product that sends the request, so provider logs can attribute traffic to a client release instead of only a runtime:

```typescript
const models = createModels({
userAgent: { name: "stepcode-cli", version: "1.4.2" },
});
// User-Agent: stepcode (darwin 25.1.0; arm64) stepcode-cli/1.4.2
models.streamSimple(model, context, { userAgent: { name: "my-host", version: "0.3.0" } });
```

`createModels({ userAgent })` covers every request the collection dispatches; a per-request `userAgent` overrides it. Each half must be an RFC 9110 product token; an invalid half drops the client token and leaves the runtime token untouched. `getPiUserAgent(client?)` renders the same value for callers that own the header themselves.

### Transforming Request Headers

`Models.stream()`, `complete()`, `streamSimple()`, and `completeSimple()` accept a Models-only `transformHeaders` option. It runs once after provider auth, `model.headers`, and explicit `options.headers` have been merged, but before provider dispatch:
Expand Down
14 changes: 11 additions & 3 deletions packages/providers/src/api/anthropic-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import { classifyProviderError, ProviderStreamError } from "../utils/error-kind.
import { AssistantMessageEventStream } from "../utils/event-stream.ts";
import { headersToRecord } from "../utils/headers.ts";
import { parseJsonWithRepair, parseStreamingJson } from "../utils/json-parse.ts";
import { getPiUserAgent } from "../utils/pi-user-agent.ts";
import { getPiUserAgent, type UserAgentClient } from "../utils/pi-user-agent.ts";
import { providerRetryAfterMs, retryProviderRequest } from "../utils/provider-retry.ts";
import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts";

Expand Down Expand Up @@ -228,8 +228,11 @@ function mergeHeaders(...headerSources: (ProviderHeaders | undefined)[]): Provid
return merged;
}

function mergeClientHeaders(...headerSources: (ProviderHeaders | undefined)[]): ProviderHeaders {
return mergeHeaders({ "User-Agent": getPiUserAgent() }, ...headerSources);
function mergeClientHeaders(
userAgent: UserAgentClient | undefined,
...headerSources: (ProviderHeaders | undefined)[]
): ProviderHeaders {
return mergeHeaders({ "User-Agent": getPiUserAgent(userAgent) }, ...headerSources);
}

function hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {
Expand Down Expand Up @@ -509,6 +512,7 @@ export const stream: StreamFunction<"anthropic-messages", AnthropicOptions> = (
options?.fetch,
copilotDynamicHeaders,
cacheSessionId,
options?.userAgent,
);
}
let params = buildParams(model, context, options);
Expand Down Expand Up @@ -838,6 +842,7 @@ function createClient(
fetch?: typeof globalThis.fetch,
dynamicHeaders?: Record<string, string>,
sessionId?: string,
userAgent?: UserAgentClient,
): Anthropic {
// Adaptive thinking models have interleaved thinking built in, so skip the beta header.
const needsInterleavedBeta = interleavedThinking && model.compat?.forceAdaptiveThinking !== true;
Expand All @@ -861,6 +866,7 @@ function createClient(
dangerouslyAllowBrowser: true,
fetch,
defaultHeaders: mergeClientHeaders(
userAgent,
{
accept: "application/json",
"anthropic-dangerous-direct-browser-access": "true",
Expand All @@ -885,6 +891,7 @@ function createClient(
dangerouslyAllowBrowser: true,
fetch,
defaultHeaders: mergeClientHeaders(
userAgent,
{
accept: "application/json",
"anthropic-dangerous-direct-browser-access": "true",
Expand All @@ -902,6 +909,7 @@ function createClient(
const sessionAffinityHeaders: ProviderHeaders =
sessionId && getAnthropicCompat(model).sendSessionAffinityHeaders ? { "x-session-affinity": sessionId } : {};
const defaultHeaders = mergeClientHeaders(
userAgent,
{
accept: "application/json",
"anthropic-dangerous-direct-browser-access": "true",
Expand Down
16 changes: 13 additions & 3 deletions packages/providers/src/api/openai-completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import { AssistantMessageEventStream } from "../utils/event-stream.ts";
import { shortHash } from "../utils/hash.ts";
import { headersToRecord } from "../utils/headers.ts";
import { parseStreamingJson } from "../utils/json-parse.ts";
import { getPiUserAgent } from "../utils/pi-user-agent.ts";
import { getPiUserAgent, type UserAgentClient } from "../utils/pi-user-agent.ts";
import { providerRetryAfterMs, retryProviderRequest } from "../utils/provider-retry.ts";
import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts";
import {
Expand Down Expand Up @@ -336,7 +336,16 @@ export const stream: StreamFunction<"openai-completions", OpenAICompletionsOptio
);
const cacheRetention = options?.cacheRetention ?? "short";
const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
const client = createClient(model, context, apiKey, options?.headers, options?.fetch, cacheSessionId, compat);
const client = createClient(
model,
context,
apiKey,
options?.headers,
options?.fetch,
cacheSessionId,
compat,
options?.userAgent,
);
let params = buildParams(model, context, options, compat, cacheRetention, grammarToolInputProperties);
const nextParams = await options?.onPayload?.(params, model);
if (nextParams !== undefined) {
Expand Down Expand Up @@ -745,8 +754,9 @@ function createClient(
fetch?: typeof globalThis.fetch,
sessionId?: string,
compat: ResolvedOpenAICompletionsCompat = getCompat(model),
userAgent?: UserAgentClient,
) {
const headers: ProviderHeaders = { "User-Agent": getPiUserAgent(), ...model.headers };
const headers: ProviderHeaders = { "User-Agent": getPiUserAgent(userAgent), ...model.headers };
if (model.provider === "github-copilot") {
const hasImages = hasCopilotVisionInput(context.messages);
const copilotHeaders = buildCopilotDynamicHeaders({
Expand Down
Loading