From 070f17c3ae46fdc5e8943f4d5ba4aa3470e35344 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:50:01 +0800 Subject: [PATCH 1/5] feat(step): queue Step model requests when the server asks to wait Requests to Step's API hosts now carry X-StepCode-Queue-ID. When the server answers 429 with X-StepCode-Queue-State: waiting, the request holds its place: the client polls the region's queue endpoint, resends the original bytes under the same id once ready, and releases the place on stop. Servers that do not queue ignore the header, so nothing else changes. - core: modelFetch hook, request teardowns settled on dispose, and the ephemeral model_queue session event - providers: StreamIdleHold pauses the idle watchdog while waiting; isStepProvider / isStepPlatformUrl as the single Step identity source - step: queue client, model_queue setting (STEPCODE_MODEL_QUEUE env, default on), x-step-client defaults to stepcode-cli - cli: TUI queue status, -p stderr line, json/rpc live events --- apps/cli/src/main.ts | 13 +- apps/cli/src/ui/interactive-mode.ts | 26 + apps/cli/src/ui/runtime/context.ts | 5 + apps/cli/src/ui/runtime/session-events.ts | 8 + .../src/ui/view/chrome/status-indicator.ts | 100 ++- apps/cli/src/ui/view/dialogs/usage-panel.ts | 3 +- apps/cli/src/ui/view/index.ts | 2 + apps/cli/test/queue-signal-exit.test.ts | 244 ++++++ .../session-events-working-tracker.test.ts | 79 +- docs/step-configuration.md | 17 + .../docs/environment-variables.md | 2 + packages/coding-agent/docs/json.md | 2 +- packages/coding-agent/docs/rpc.md | 1 + packages/coding-agent/docs/sdk.md | 54 ++ .../coding-agent/docs/step-integration.md | 81 ++ .../src/core/agent-session-runtime.ts | 4 + .../src/core/agent-session-services.ts | 8 + .../coding-agent/src/core/agent-session.ts | 43 + packages/coding-agent/src/core/index.ts | 9 + packages/coding-agent/src/core/model-fetch.ts | 73 ++ .../src/core/request-teardowns.ts | 38 + packages/coding-agent/src/core/sdk.ts | 28 +- .../src/core/session-event-durability.ts | 8 + packages/coding-agent/src/features/step.ts | 4 +- packages/coding-agent/src/index.ts | 20 +- packages/coding-agent/src/main.ts | 4 + packages/coding-agent/src/modes/print-mode.ts | 11 + packages/coding-agent/src/step/environment.ts | 12 +- packages/coding-agent/src/step/model-queue.ts | 444 ++++++++++ packages/coding-agent/src/step/sdk.ts | 13 + .../coding-agent/src/step/settings-manager.ts | 30 + .../src/step/telemetry-contract.ts | 15 +- .../coding-agent/src/step/trace-headers.ts | 7 +- .../agent-session-runtime-concurrency.test.ts | 10 +- .../test/json-event-projection.test.ts | 10 + .../test/main-model-fetch.test.ts | 121 +++ .../test/model-fetch-hook.test.ts | 214 +++++ packages/coding-agent/test/print-mode.test.ts | 72 ++ .../test/request-teardowns.test.ts | 46 ++ .../test/runtime-request-teardowns.test.ts | 127 +++ .../test/step-endpoint-class.test.ts | 28 + .../test/step-environment.test.ts | 6 +- .../coding-agent/test/step-extension.test.ts | 4 +- .../test/step-model-queue-session.test.ts | 235 ++++++ .../test/step-model-queue.test.ts | 772 ++++++++++++++++++ .../test/step-trace-headers.test.ts | 6 +- .../test/subagent-child-env.test.ts | 20 + packages/providers/src/step-provider/index.ts | 50 ++ .../providers/src/utils/stream-watchdog.ts | 47 +- packages/providers/test/step-identity.test.ts | 51 ++ .../providers/test/stream-watchdog.test.ts | 45 +- 51 files changed, 3232 insertions(+), 40 deletions(-) create mode 100644 apps/cli/test/queue-signal-exit.test.ts create mode 100644 packages/coding-agent/src/core/model-fetch.ts create mode 100644 packages/coding-agent/src/core/request-teardowns.ts create mode 100644 packages/coding-agent/src/step/model-queue.ts create mode 100644 packages/coding-agent/test/main-model-fetch.test.ts create mode 100644 packages/coding-agent/test/model-fetch-hook.test.ts create mode 100644 packages/coding-agent/test/request-teardowns.test.ts create mode 100644 packages/coding-agent/test/runtime-request-teardowns.test.ts create mode 100644 packages/coding-agent/test/step-endpoint-class.test.ts create mode 100644 packages/coding-agent/test/step-model-queue-session.test.ts create mode 100644 packages/coding-agent/test/step-model-queue.test.ts create mode 100644 packages/providers/test/step-identity.test.ts diff --git a/apps/cli/src/main.ts b/apps/cli/src/main.ts index 0aa378f89..9c77837a0 100644 --- a/apps/cli/src/main.ts +++ b/apps/cli/src/main.ts @@ -17,6 +17,7 @@ import { configureHttpDispatcher, createStepCode, createStepCodeProviderInlineExtension, + createStepModelQueueFactory, createStepProviderConfig, createStepSessionManagerFactory, createStepSettingsManager, @@ -35,6 +36,7 @@ import { installProcessStderrDevLogCapture, isStepConfigCommand, isStepInteractiveLoginStartup, + isStepProvider, isStepServicesDisabled, loginMcpServer, logoutMcpServer, @@ -74,6 +76,7 @@ import { type StepSettingsManager, scanUsageOverview, setStderrDevLogStorageRootDirectory, + stepModelQueueStatusText, stopThemeWatcher, syncStepLoginProfileEndpoint, trackStepTelemetry, @@ -270,7 +273,7 @@ const stepMainOptions: MainOptions = { interactiveModeOptions: { showChangelog: false, tuiStyle: "step" as const, - defaultModelForProvider: (providerId) => (providerId === STEP_PROVIDER_ID ? STEP_DEFAULT_MODEL : undefined), + defaultModelForProvider: (providerId) => (isStepProvider(providerId) ? STEP_DEFAULT_MODEL : undefined), allowedAuthProviders: [STEP_PROVIDER_ID], stepLogin: (host) => runStepLogin({ @@ -320,6 +323,11 @@ const stepMainOptions: MainOptions = { }, }, ...(modelRequestObserver ? { modelRequestObserver } : {}), + // Every mode (interactive, print/json, rpc and the subagent children it + // starts) runs through here; the switch decides per request. + modelFetch: createStepModelQueueFactory({ + settings: () => currentStepSettingsManager?.getStepSettings(), + }), systemPromptProduct: { name: "StepCode", role: "an interactive terminal coding agent developed by StepFun", @@ -741,7 +749,7 @@ try { STEP_DEFAULT_PROVIDER; if ( interactiveStartup && - selectedProvider === STEP_PROVIDER_ID && + isStepProvider(selectedProvider) && !hasExplicitStepCredential && !hasConfiguredStepCodeCredential(stepCodeConfig) ) { @@ -924,6 +932,7 @@ async function dispatchStepAppMode(prep: Extract this.ui, + presentation: () => this.presentation, + active: () => this.activeStatusIndicator, + swap: (next) => { + const previous = this.activeStatusIndicator; + this.activeStatusIndicator = next; + this.statusContainer.clear(); + if (next) this.statusContainer.addChild(next); + return previous; + }, + }); + this.modelQueueSlot.update(queueId, state); + } + + clearModelQueue(): void { + this.modelQueueSlot?.leave(); + } + clearStatusIndicator(kind?: StatusIndicator["kind"]): void { + this.modelQueueSlot?.forget(kind); if (kind && this.activeStatusIndicator?.kind !== kind) { return; } diff --git a/apps/cli/src/ui/runtime/context.ts b/apps/cli/src/ui/runtime/context.ts index bfb2458a5..5c9f9a623 100644 --- a/apps/cli/src/ui/runtime/context.ts +++ b/apps/cli/src/ui/runtime/context.ts @@ -28,6 +28,7 @@ import type { ExtensionUIDialogOptions, InteractiveModeOptions, MarkdownTransformer, + ModelQueueState, SessionEntry, } from "@step-harness/coding-agent"; import type { Container, EditorComponent, MarkdownTheme, TUI, TuiAltScreen, TuiMainScreen } from "@step-harness/pi-tui"; @@ -128,6 +129,10 @@ export interface RuntimeContext { showWorkingStatusIndicator(): void; showTurnDoneIndicator(durationSeconds: number): void; clearStatusIndicator(kind?: StatusIndicator["kind"]): void; + /** Show (or, with `null`, drop) one model request's place in line; see `ModelQueueStatusSlot`. */ + updateModelQueue(queueId: string, state: ModelQueueState | null): void; + /** Drop every queue row and restore what they covered. */ + clearModelQueue(): void; showError(errorMessage: string): void; renderSessionEntries(entries: SessionEntry[], options?: { updateFooter?: boolean; populateHistory?: boolean }): void; addCompactionCostNotice(notice: { diff --git a/apps/cli/src/ui/runtime/session-events.ts b/apps/cli/src/ui/runtime/session-events.ts index c83c05561..2cd6a3c22 100644 --- a/apps/cli/src/ui/runtime/session-events.ts +++ b/apps/cli/src/ui/runtime/session-events.ts @@ -349,6 +349,8 @@ export async function handleSessionEvent(ctx: RuntimeContext, event: AgentSessio case "agent_end": ctx.ui.terminal.setProgress(false); + // A run that ends while a request waits (a stop) leaves no queue row behind. + ctx.clearModelQueue(); ctx.clearStatusIndicator("working"); // Turn-done marker: only for normally-ended turns (aborted/error // turns already show an error line in the transcript); stays @@ -460,6 +462,12 @@ export async function handleSessionEvent(ctx: RuntimeContext, event: AgentSessio break; } + case "model_queue": { + ctx.updateModelQueue(event.queueId, event.queue); + ctx.redraw.requestRender(); + break; + } + case "auto_retry_start": { // Set up escape to abort retry ctx.retryEscapeHandler = ctx.defaultEditor.onEscape; diff --git a/apps/cli/src/ui/view/chrome/status-indicator.ts b/apps/cli/src/ui/view/chrome/status-indicator.ts index bb8f626e6..631efeb74 100644 --- a/apps/cli/src/ui/view/chrome/status-indicator.ts +++ b/apps/cli/src/ui/view/chrome/status-indicator.ts @@ -1,5 +1,5 @@ import type { WorkingIndicatorOptions } from "@step-harness/coding-agent"; -import { keyText, theme } from "@step-harness/coding-agent"; +import { keyText, type ModelQueueState, stepModelQueueStatusText, theme } from "@step-harness/coding-agent"; import { type Component, Loader, type TUI, truncateToWidth, visibleWidth } from "@step-harness/pi-tui"; import type { AssistantMessage, AssistantMessageEvent } from "@step-harness/providers"; import { CountdownTimer } from "../dialogs/countdown-timer.ts"; @@ -8,7 +8,7 @@ import { estimateTokens, formatElapsedTime, formatTokens } from "./footer.ts"; /** Refresh cadence for the compact Step working indicator. */ export const STEP_WORKING_INDICATOR_INTERVAL_MS = 200; -export type StatusIndicatorKind = "working" | "retry" | "compaction" | "branchSummary"; +export type StatusIndicatorKind = "working" | "retry" | "compaction" | "branchSummary" | "queue"; export interface WorkingOutputSnapshot { elapsedSeconds: number; @@ -355,6 +355,102 @@ export class RetryStatusIndicator extends StatusIndicator { } } +/** + * Stands in for the working row while the running model request waits in the + * Step Plan queue: the request has not reached the model yet. Shows the place + * in line, never a wait estimate. + */ +export class ModelQueueStatusIndicator extends StatusIndicator { + constructor(ui: TUI, state: ModelQueueState, presentation: "native" | "step" = "native") { + super( + "queue", + ui, + (spinner) => theme.fg("warning", spinner), + (text) => theme.fg("muted", text), + ModelQueueStatusIndicator.label(state), + undefined, + presentation, + ); + } + + update(state: ModelQueueState): void { + this.setMessage(ModelQueueStatusIndicator.label(state)); + } + + private static label(state: ModelQueueState): string { + return `${stepModelQueueStatusText(state)} (${keyText("app.interrupt")} to cancel)`; + } +} + +/** Where a {@link ModelQueueStatusSlot} shows its row: the host's single status position. */ +export interface ModelQueueStatusHost { + ui(): TUI; + presentation(): "native" | "step"; + /** The indicator in the status position now. */ + active(): StatusIndicator | undefined; + /** Put `next` (or nothing) in the status position and hand back what was there, neither disposed nor stopped. */ + swap(next: StatusIndicator | undefined): StatusIndicator | undefined; +} + +/** + * The queue row of every model request that waits in line, by queue id. While + * any waits, the row shows the newest one; the indicator it covered (working, + * retry, compaction) is paused, not disposed, and comes back when the last + * request leaves. One request leaving never clears another's place. + */ +export class ModelQueueStatusSlot { + private readonly host: ModelQueueStatusHost; + private readonly waiting = new Map(); + private indicator: ModelQueueStatusIndicator | undefined; + private covered: StatusIndicator | undefined; + + constructor(host: ModelQueueStatusHost) { + this.host = host; + } + + update(queueId: string, state: ModelQueueState | null): void { + this.waiting.delete(queueId); + if (state) this.waiting.set(queueId, state); + const newest = [...this.waiting.values()].at(-1); + if (!newest) { + this.leave(); + return; + } + if (this.indicator && this.host.active() === this.indicator) { + this.indicator.update(newest); + return; + } + // First report, or another row took the position meanwhile: cover what is there now. + this.indicator = new ModelQueueStatusIndicator(this.host.ui(), newest, this.host.presentation()); + const previous = this.host.swap(this.indicator); + this.covered?.dispose(); + this.covered = previous; + previous?.stop(); + } + + /** Every request left the line (or the run ended): restore the covered row. */ + leave(): void { + this.waiting.clear(); + const indicator = this.indicator; + const covered = this.covered; + this.indicator = undefined; + this.covered = undefined; + if (indicator && this.host.active() === indicator) { + this.host.swap(covered); + covered?.start(); + } else covered?.dispose(); + indicator?.dispose(); + } + + /** The host cleared rows of `kind` (all rows when undefined): a covered one of that kind is not restored. */ + forget(kind: StatusIndicatorKind | undefined): void { + if (this.covered && (kind === undefined || this.covered.kind === kind)) { + this.covered.dispose(); + this.covered = undefined; + } + } +} + export type CompactionStatusReason = "manual" | "threshold" | "overflow"; export class CompactionStatusIndicator extends StatusIndicator { diff --git a/apps/cli/src/ui/view/dialogs/usage-panel.ts b/apps/cli/src/ui/view/dialogs/usage-panel.ts index 68d396827..534ce9da1 100644 --- a/apps/cli/src/ui/view/dialogs/usage-panel.ts +++ b/apps/cli/src/ui/view/dialogs/usage-panel.ts @@ -1,6 +1,7 @@ import { type AccountUsageState, type ExtensionCommandContext, + isStepProvider, stripAnsi, theme, type UsagePresentation, @@ -237,7 +238,7 @@ export function usagePresentationRows(model: UsagePresentation, width = 100, det ); if (model.session.invalid || model.session.missing) rows.push(`Usage coverage: ${model.session.invalid} invalid, ${model.session.missing} missing records`); - if (s.provider !== "step") rows.push(`Step account quota · current model uses ${s.provider}`); + if (!isStepProvider(s.provider)) rows.push(`Step account quota · current model uses ${s.provider}`); rows.push("", "R refresh account"); } rows.push("1/2 or ←/→ switch tab · ↑/↓ scroll · Esc close"); diff --git a/apps/cli/src/ui/view/index.ts b/apps/cli/src/ui/view/index.ts index a0e14cee4..eeb9827bb 100644 --- a/apps/cli/src/ui/view/index.ts +++ b/apps/cli/src/ui/view/index.ts @@ -7,6 +7,8 @@ export { FooterComponent } from "./chrome/footer.ts"; export { BranchSummaryStatusIndicator, CompactionStatusIndicator, + ModelQueueStatusIndicator, + ModelQueueStatusSlot, RetryStatusIndicator, StatusIndicator, TurnDoneIndicator, diff --git a/apps/cli/test/queue-signal-exit.test.ts b/apps/cli/test/queue-signal-exit.test.ts new file mode 100644 index 000000000..a5d1fe4d2 --- /dev/null +++ b/apps/cli/test/queue-signal-exit.test.ts @@ -0,0 +1,244 @@ +import { execFileSync, spawn } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { createServer as createHttpServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import { createServer as createHttpsServer } from "node:https"; +import { connect } from "node:net"; +import type { Duplex } from "node:stream"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +/** + * A stop while a request waits in Step's model request queue must reach the + * server: the built CLI in `-p` mode gets SIGINT mid-queue and has to send the + * cancel (with the request's id) before it exits, within its bound. + * + * Step's queue lives at fixed hosts, so the test plays `api.stepfun.com` behind + * a local CONNECT proxy (`HTTPS_PROXY`) with a throwaway certificate the child + * accepts (`NODE_TLS_REJECT_UNAUTHORIZED=0`). Nothing leaves the machine. + */ + +const roots: string[] = []; +const closers: Array<() => Promise> = []; +afterEach(async () => { + for (const close of closers.splice(0)) await close(); + for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }); +}); + +function listen(server: Server): Promise { + return new Promise((done) => + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") throw new Error("server did not start"); + done(address.port); + }), + ); +} + +function closeServer(server: Server, sockets: Set): () => Promise { + return () => + new Promise((done) => { + for (const socket of sockets) socket.destroy(); + server.close(() => done()); + }); +} + +async function body(request: IncomingMessage): Promise { + let text = ""; + for await (const chunk of request) text += chunk; + return text; +} + +describe.skipIf(process.platform === "win32")("-p in the model request queue", () => { + it( + "sends the queue cancel before exiting on SIGINT", + async () => { + const root = await mkdtemp(join(tmpdir(), "step-cli-queue-signal-")); + roots.push(root); + const home = join(root, "home"); + const cwd = join(root, "project"); + const agentDir = join(root, "configuration", "agent"); + await Promise.all([mkdir(home), mkdir(cwd), mkdir(agentDir, { recursive: true })]); + execFileSync("openssl", [ + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-days", + "1", + "-subj", + "/CN=api.stepfun.com", + "-keyout", + join(root, "key.pem"), + "-out", + join(root, "cert.pem"), + ], { stdio: "ignore" }); + + const trace: string[] = []; + let cancel: { readonly id: unknown; readonly contentType: unknown; readonly body: string } | undefined; + let pollId: unknown; + let onFirstPoll: (() => void) | undefined; + const firstPoll = new Promise((done) => { + onFirstPoll = done; + }); + const step = createHttpsServer( + { key: await readFile(join(root, "key.pem")), cert: await readFile(join(root, "cert.pem")) }, + async (request: IncomingMessage, response: ServerResponse) => { + const text = await body(request); + const url = new URL(request.url ?? "/", "https://api.stepfun.com"); + trace.push(`${request.method} ${url.pathname}`); + if (url.pathname === "/step_plan/v1/chat/completions") { + response.writeHead(429, { + "content-type": "application/json", + "X-StepCode-Queue-State": "waiting", + "X-StepCode-Queue-Position": "3", + "Retry-After-Ms": "100", + }); + response.end('{"error":{"type":"queued","code":"queued"}}'); + return; + } + if (url.pathname === "/stepcode/v1/queue") { + pollId = request.headers["x-stepcode-queue-id"]; + response.writeHead(200, { "content-type": "application/json" }); + response.end('{"state":"waiting","position":2,"retry_after_ms":5000,"reason":""}'); + onFirstPoll?.(); + return; + } + if (url.pathname === "/stepcode/v1/queue/cancel") { + cancel = { + id: request.headers["x-stepcode-queue-id"], + contentType: request.headers["content-type"], + body: text, + }; + response.writeHead(200, { "content-type": "application/json" }); + response.end("{}"); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end('{"data":[]}'); + }, + ); + const stepSockets = new Set(); + step.on("connection", (socket) => { + stepSockets.add(socket); + socket.on("close", () => stepSockets.delete(socket)); + }); + const stepPort = await listen(step); + closers.push(closeServer(step, stepSockets)); + + // Every CONNECT, whatever host it names, is tunnelled to the stand-in. + const proxy = createHttpServer(); + const proxySockets = new Set(); + proxy.on("connection", (socket) => { + proxySockets.add(socket); + socket.on("close", () => proxySockets.delete(socket)); + }); + proxy.on("connect", (_request, client: Duplex, head) => { + const upstream = connect(stepPort, "127.0.0.1", () => { + client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + upstream.write(head); + upstream.pipe(client); + client.pipe(upstream); + }); + proxySockets.add(upstream); + upstream.on("error", () => client.destroy()); + client.on("error", () => upstream.destroy()); + }); + const proxyPort = await listen(proxy); + closers.push(closeServer(proxy, proxySockets)); + + const catalog = JSON.stringify({ + providers: { + stepgate: { + baseUrl: "https://api.stepfun.com/step_plan/v1", + api: "openai-completions", + models: [ + { + id: "queue-model", + name: "Queue model", + contextWindow: 32000, + maxTokens: 1000, + reasoning: false, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }, + ], + }, + }, + }); + await Promise.all([ + writeFile(join(root, "configuration", "models.json"), catalog), + writeFile(join(agentDir, "models.json"), catalog), + ]); + const cli = resolve(import.meta.dirname, "../dist/main.js"); + const args = [ + cli, + "--provider", + "stepgate", + "--model", + "queue-model", + "--api-key", + "test-key", + "--no-extensions", + "--no-skills", + "--no-prompt-templates", + "--no-themes", + "--no-context-files", + "--no-approve", + "--no-update-check", + "--no-session", + "-p", + "Reply done.", + ]; + const child = spawn(process.execPath, args, { + cwd, + env: { + PATH: process.env.PATH, + HOME: home, + USERPROFILE: home, + STEP_CODING_AGENT_DIR: agentDir, + STEP_NO_LOCAL_LLM: "1", + AWS_EC2_METADATA_DISABLED: "true", + STEPCODE_MODEL_QUEUE: "1", + HTTPS_PROXY: `http://127.0.0.1:${proxyPort}`, + NODE_TLS_REJECT_UNAUTHORIZED: "0", + }, + stdio: ["ignore", "pipe", "pipe"], + }); + let output = ""; + child.stdout.on("data", (chunk) => { + output += chunk; + }); + child.stderr.on("data", (chunk) => { + output += chunk; + }); + const exited = new Promise((done, reject) => { + child.once("error", reject); + child.once("close", (code) => done(code)); + }); + const guard = setTimeout(() => child.kill("SIGKILL"), 90_000); + try { + await Promise.race([firstPoll, exited.then(() => Promise.reject(new Error(`exited early:\n${output}`)))]); + expect(trace.slice(0, 2)).toEqual(["POST /step_plan/v1/chat/completions", "GET /stepcode/v1/queue"]); + const stoppedAt = Date.now(); + child.kill("SIGINT"); + const code = await exited; + const elapsed = Date.now() - stoppedAt; + expect(code, output.slice(-4000)).toBe(130); + expect(trace).toContain("POST /stepcode/v1/queue/cancel"); + // The cancel names the place in its queue id header, the same one the poll + // asked about, and has no body. + expect(pollId).toMatch(/^[0-9a-f-]{36}$/u); + expect(cancel).toEqual({ id: pollId, contentType: undefined, body: "" }); + // The stop is bounded: the cancel's own limit plus the dispose bound, with slack for a loaded runner. + expect(elapsed).toBeLessThan(5_000); + expect(output).toContain("Queued: position 3"); + } finally { + clearTimeout(guard); + if (child.exitCode === null) child.kill("SIGKILL"); + } + }, + 120_000, + ); +}); diff --git a/apps/cli/test/session-events-working-tracker.test.ts b/apps/cli/test/session-events-working-tracker.test.ts index 55ff2ccdc..c2432861e 100644 --- a/apps/cli/test/session-events-working-tracker.test.ts +++ b/apps/cli/test/session-events-working-tracker.test.ts @@ -1,9 +1,17 @@ import { describe, expect, test, vi } from "vitest"; import type { AssistantMessage } from "@step-harness/providers"; -import { WorkingOutputTracker } from "../src/ui/view/chrome/status-indicator.ts"; +import type { TUI } from "@step-harness/pi-tui"; +import { + CompactionStatusIndicator, + ModelQueueStatusIndicator, + ModelQueueStatusSlot, + type StatusIndicator, + WorkingOutputTracker, +} from "../src/ui/view/chrome/status-indicator.ts"; import type { RuntimeContext } from "../src/ui/runtime/context.ts"; import { handleSessionEvent } from "../src/ui/runtime/session-events.ts"; -import { INCOMPLETE_TURN_RECOVERY_CUSTOM_TYPE } from "@step-harness/coding-agent"; +import { INCOMPLETE_TURN_RECOVERY_CUSTOM_TYPE, stepModelQueueStatusText } from "@step-harness/coding-agent"; +import { initTheme } from "../../../packages/coding-agent/src/theme/theme.ts"; test("announces only a recovery that actually starts and uses its attempt metadata", async () => { const showStatus = vi.fn(); @@ -64,6 +72,7 @@ test.each(["agent_end", "auto_clm_end", "compaction_end"] as const)( settingsManager: { getShowTerminalProgress: () => false }, ui: { terminal: { setProgress } }, clearStatusIndicator: vi.fn(), + clearModelQueue: vi.fn(), pendingTools: new Map(), redraw: { requestRender: vi.fn() }, flushCompactionQueue: vi.fn(), @@ -219,3 +228,69 @@ describe("session-events agent_start working-tracker reset", () => { } }); }); + +function queueSlotHost() { + const state: { active: StatusIndicator | undefined } = { active: undefined }; + const host = { + ui: () => ({ requestRender: vi.fn() }) as unknown as TUI, + presentation: () => "step" as const, + active: () => state.active, + swap: (next: StatusIndicator | undefined) => { + const previous = state.active; + state.active = next; + return previous; + }, + }; + return { state, host }; +} + +test("the queue row covers the current row and gives the same one back when the request leaves", () => { + initTheme("dark"); + const { state, host } = queueSlotHost(); + const slot = new ModelQueueStatusSlot(host); + const compaction = new CompactionStatusIndicator(host.ui(), "threshold", "step"); + state.active = compaction; + + slot.update("r1", { position: 3 }); + expect(state.active).toBeInstanceOf(ModelQueueStatusIndicator); + slot.update("r1", { position: 1 }); + expect(state.active?.render(80).join("\n")).toContain(stepModelQueueStatusText({ position: 1 })); + + slot.update("r1", null); + // Not a working row: the compaction row it covered. + expect(state.active).toBe(compaction); + compaction.dispose(); +}); + +test("one request leaving the line keeps another's queue row", () => { + initTheme("dark"); + const { state, host } = queueSlotHost(); + const slot = new ModelQueueStatusSlot(host); + slot.update("a", { position: 2 }); + slot.update("b", { position: 5 }); + slot.update("a", null); + expect(state.active?.render(80).join("\n")).toContain(stepModelQueueStatusText({ position: 5 })); + slot.update("b", null); + expect(state.active).toBeUndefined(); +}); + +test("model_queue events reach the queue slot, and agent_end clears it", async () => { + const updateModelQueue = vi.fn(); + const clearModelQueue = vi.fn(); + const ctx = { + isInitialized: true, + footer: { invalidate: vi.fn() }, + ui: { terminal: { setProgress: vi.fn() } }, + settingsManager: { getShowTerminalProgress: () => false }, + updateModelQueue, + clearModelQueue, + clearStatusIndicator: vi.fn(), + pendingTools: new Map(), + turnEndedAbnormally: true, + redraw: { requestRender: vi.fn() }, + } as unknown as RuntimeContext; + await handleSessionEvent(ctx, { type: "model_queue", queueId: "r1", queue: { position: 2 } }); + expect(updateModelQueue).toHaveBeenCalledWith("r1", { position: 2 }); + await handleSessionEvent(ctx, { type: "agent_end", messages: [], willRetry: false }); + expect(clearModelQueue).toHaveBeenCalledOnce(); +}); diff --git a/docs/step-configuration.md b/docs/step-configuration.md index 15b457b49..04c6e9178 100644 --- a/docs/step-configuration.md +++ b/docs/step-configuration.md @@ -183,6 +183,23 @@ confirms the child's actual route after it starts, rejecting CLI fuzzy matches o falls back to a different model. A background lane keeps the route it was launched with when a reply respawns its child. +### Model request queue + +When Step's model pool is busy, the server can keep a model request sent to +Step's API in a first-come line instead of rejecting it. The client side is on +by default: + +```toml +model_queue = true +``` + +Every model request sent to `api.stepfun.com` or `api.stepfun.ai` takes part, +whichever provider sends it. `STEPCODE_MODEL_QUEUE=1` / `0` overrides the setting; a trusted project's +`.stepcode/config.toml` overrides the global one; with neither, the queue is on, +for every host alike. See +[Step integration](../packages/coding-agent/docs/step-integration.md#model-request-queue) +for the protocol. + ### Plan file storage Native Markdown plans default to diff --git a/packages/coding-agent/docs/environment-variables.md b/packages/coding-agent/docs/environment-variables.md index cc218afe7..937a8328e 100644 --- a/packages/coding-agent/docs/environment-variables.md +++ b/packages/coding-agent/docs/environment-variables.md @@ -14,7 +14,9 @@ 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_PROVIDER`, `STEP_MODEL` | Default provider and model selection | +| `STEPCODE_MODEL_QUEUE` | Model request queue: `1` on, `0` off, over `model_queue`; on by default. See [Step integration](step-integration.md#model-request-queue) | | `VISUAL`, `EDITOR` | External editor fallback when `externalEditor` is unset | | `HTTP_PROXY`, `HTTPS_PROXY` | Proxy outbound HTTP requests | diff --git a/packages/coding-agent/docs/json.md b/packages/coding-agent/docs/json.md index 2ce20f282..fa269be1c 100644 --- a/packages/coding-agent/docs/json.md +++ b/packages/coding-agent/docs/json.md @@ -36,7 +36,7 @@ type JsonAgentSessionEvent = | { type: "agent_end"; willRetry: boolean; messageCount: number }; ``` -`queue_update` emits the full pending steering and follow-up queues whenever they change. `compaction_start` and `compaction_end` cover both manual and automatic compaction. +`queue_update` emits the full pending steering and follow-up queues whenever they change. `model_queue` is a live frame (written only with `--include-live-events`): a model request waits in the model request queue (`{ queueId, queue: { position? } }`), then `queue: null` (with `closedReason` when the server closed its place) when it leaves the line. Text mode (`-p`) writes each change to stderr instead. `compaction_start` and `compaction_end` cover both manual and automatic compaction. Other events are the session loop's own [`AgentSessionEvent`](https://github.com/stepfun-ai/step-harness/blob/main/packages/coding-agent/src/core/agent-session.ts), diff --git a/packages/coding-agent/docs/rpc.md b/packages/coding-agent/docs/rpc.md index 0195c256b..4810dd758 100644 --- a/packages/coding-agent/docs/rpc.md +++ b/packages/coding-agent/docs/rpc.md @@ -913,6 +913,7 @@ Events are streamed to stdout as JSON lines during agent operation. Events do no | `queue_update` | Pending steering/follow-up queue changed | | `compaction_start` | Compaction begins | | `compaction_end` | Compaction completes | +| `model_queue` | **Opt-in frame** (`--include-live-events`): a model request waits in the model request queue (`queue.position`), or left it (`queue: null`, with `closedReason` when the server closed its place); carries the call's `queueId`. Subagent parents start their children with this flag, so they receive it | | `auto_retry_start` | Auto-retry begins (after transient error) | | `auto_retry_end` | Auto-retry completes (success or final failure) | | `summarization_retry_scheduled` | Retry scheduled for a transient compaction or branch-summary summarization error | diff --git a/packages/coding-agent/docs/sdk.md b/packages/coding-agent/docs/sdk.md index b81d01446..6423b37af 100644 --- a/packages/coding-agent/docs/sdk.md +++ b/packages/coding-agent/docs/sdk.md @@ -575,6 +575,60 @@ A failed or timed-out network refresh does not undo a successful credential oper > See [examples/sdk/09-api-keys-and-oauth.ts](../examples/sdk/09-api-keys-and-oauth.ts) +### Model Request Fetch + +`modelFetch` lets a host wrap the HTTP fetch of every model request the session +sends. Nothing installs one by default. The factory runs once per model request +and returns the fetch to use, or `undefined` to leave that request unchanged: + +```typescript +import { createAgentSession, type ModelFetchFactory } from "@step-harness/coding-agent"; + +const modelFetch: ModelFetchFactory = ({ model, signal, fetch, holdIdleWatchdog }) => async (input, init) => { + // Example: wait until the host lets this request go, without tripping the stream idle bound. + const release = holdIdleWatchdog(); + try { + await waitForTurn(model, signal); + } finally { + release(); + } + return fetch(input, init); +}; + +const { session } = await createAgentSession({ modelFetch }); +``` + +- `fetch` is the fetch the request would use without the wrapper. +- `signal` cancels the logical request: a user stop or the stream idle + watchdog. The provider SDK passes its own per-attempt signal on + `init.signal`, which also carries the SDK's request timeout and may already be + aborted after a long wait; a wrapper that holds a request listens to `signal` + while waiting. +- `holdIdleWatchdog()` suspends the stream idle bound + (`retry.provider.streamIdleTimeoutMs`) until the returned function is called. + Release it before sending to the provider, so a request that then gets no + answer still ends as a stall. Releasing the last hold starts a full idle + window. The release function is idempotent. +- `reportQueue(queueId, state, exit?)` tells the session that the request + waits in a server-side line (`state`, optionally with `position`) or left it + (`null`, with `exit.closedReason` when the server closed the place). The + session publishes each report as a `model_queue` event: a live frame the TUI + presents and `--mode json` / `--mode rpc` write with `--include-live-events`. +- `registerTeardown(task)` registers work the request still owes after its + caller stopped waiting (for example releasing a server-side reservation). + Disposing the session (runtime dispose, session replacement) awaits the + registered work for at most 2s, so a host that exits right after dispose + still sends it; with nothing registered, dispose does not wait. +- The wrapper sees only HTTP transports; WebSocket transports bypass it. + One-off calls made directly on `ModelRuntime` (outside the session's agent + loop) do not pass through it. + +`createAgentSessionServices({ modelFetch })` sets a default for every session +created from those services; a session's own `modelFetch` replaces it. +`createStepAgentSession()` and `createStepAgentSessionServices()` install the +model request queue this way unless you pass your own `modelFetch`; see +[Step integration](step-integration.md#model-request-queue). + ### System Prompt Use a `ResourceLoader` to override the system prompt: diff --git a/packages/coding-agent/docs/step-integration.md b/packages/coding-agent/docs/step-integration.md index 15631be37..e9786d047 100644 --- a/packages/coding-agent/docs/step-integration.md +++ b/packages/coding-agent/docs/step-integration.md @@ -50,6 +50,10 @@ separate blue variants. `step-violet-light/step-violet` remains available for automatic violet light/dark switching. Non-interactive `step --export` uses the same precedence as startup: explicit `--use-theme`, saved settings, then the Step product default. +Every Step request names the product it came from in `x-step-client`: +`stepcode-cli` (this build's default, `STEP_CLIENT`), or whatever a host sets — +`stepcode-desktop` for the desktop app, `stepcode-web` for its web server. + 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. @@ -212,6 +216,83 @@ normal user-message path. The model inspects the project and uses the native write and approval flow; the prompt explicitly preserves an existing `AGENTS.md` instead of replacing it. +## Model request queue + +When Step's model pool is busy, the server keeps a model request sent to Step's +API in a first-come line instead of rejecting it, and the client waits its +turn (`src/step/model-queue.ts`, installed through the generic +[`modelFetch`](sdk.md#model-request-fetch) hook). + +**Switch.** `STEPCODE_MODEL_QUEUE` (`1` / `0`) wins; then `model_queue` (a +trusted project's `.stepcode/config.toml` over `~/.stepcode/config.toml`; a +value that is not a boolean is ignored with a settings warning); with neither, +the queue is on, for every host alike (the CLI, the desktop app, the web app and +subagent children). The switch is read for every request, so a settings reload +applies to the next one. + +**Mount points.** The CLI composition root passes the queue factory to every +mode (interactive, `-p`, `--mode json`, `--mode rpc`, and the subagent children +that run those modes). `createStepAgentSession()` and +`createStepAgentSessionServices()` install it by default for embedded hosts. + +**Which requests.** Every model request sent to one of Step's two API hosts, +whatever the provider (the official `step` provider or a user's own provider +pointed at Step), login profile or route: the request host makes it a StepCode +request. The host also picks the queue: + +| Request host | Status | Cancel | +| --- | --- | --- | +| `api.stepfun.com` | `GET https://api.stepfun.com/stepcode/v1/queue` | `POST https://api.stepfun.com/stepcode/v1/queue/cancel` | +| `api.stepfun.ai` | `GET https://api.stepfun.ai/stepcode/v1/queue` | `POST https://api.stepfun.ai/stepcode/v1/queue/cancel` | + +Both control requests name the place by the `X-StepCode-Queue-ID` header (no +query parameter, no body) and carry the model request's own headers minus those +describing its body, so its credentials authorize them. + +The endpoints are fixed, not configurable. A request to any other host (for +example an endpoint override through `STEP_BASE_URL`) is sent as it is, with no +header and no queue. + +**Protocol.** With the switch on, every such request carries a fresh +`X-StepCode-Queue-ID`; whether it waits is the server's decision: + +- HTTP 429 with `X-StepCode-Queue-State: waiting` means the request holds a + place in line (`X-StepCode-Queue-Position`). The client polls its region's + status endpoint every `Retry-After-Ms` (default 2s) and on `ready` sends the + original bytes again under the same id; a queued answer to the resend keeps + polling. + The stream idle watchdog is held only while polling. +- `closed`, or a status answer of 404 (`not_found`), ends the request with a + synthesized HTTP 410 `queue_closed` error carrying `x-should-retry: false`, so + no retry re-enters the line under a new id. Its message is readable English + followed by the reason code (`queue_full`, `user_limit`, `lease_expired`, + `max_wait_exceeded`, `not_found`; unknown codes get a generic text), and + `error.reason` keeps the code. A 401 or 403 status answer is returned to the + caller as it is. A 429 or 5xx status answer, or a network error, is retried + with backoff from 1s to 8s; after 30s without a good answer the request ends + with the same 410. Any other status answer ends it too. +- A stop after the server queued the call (it answered `429` with + `X-StepCode-Queue-State: waiting`) releases the place with the region's cancel + endpoint (queue id header, no body; 200 on success). A stop before any such + answer sends nothing more; the server's lease ends a place the client never + saw, so a host without the queue never gets a cancel. The stopped call awaits + the cancel for at most 1s, and a queued call is a registered request teardown + until it settles, so disposing the session (every exit path: `-p`/json + signals, rpc shutdown, the TUI, a desktop session closing) waits for it before + the process exits. A request to a control endpoint is never wrapped or + queued, and keeps the queue id it names. +- Any other response, including an ordinary 429, goes back unchanged to the + existing retry policy. + +**Presentation.** Each change of place in line (and entering or leaving it) is +a `model_queue` session event (`{ queueId, queue: { position? } | null, +closedReason? }`), a live frame like `message_update`. The TUI covers the status +row with "Queued: position N" while any request waits and restores the covered +row (working, retry or compaction) when the last one leaves; `-p` writes each +change to stderr; `--mode json` / `--mode rpc` write the event with +`--include-live-events`, which subagent parents always pass. The status shows +the place in line only, never a wait estimate. + ## Shell command execution Foreground `run_command` calls use a 120-second timeout when `timeout_ms` is diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.ts index 4da727a29..08d233e4f 100644 --- a/packages/coding-agent/src/core/agent-session-runtime.ts +++ b/packages/coding-agent/src/core/agent-session-runtime.ts @@ -263,6 +263,7 @@ export class AgentSessionRuntime implements AgentSessionRuntimeHost { this.beforeSessionInvalidate?.(); session.dispose(); if (this._session === session) this.currentSessionDisposed = true; + await session.settleRequestTeardowns(); } private apply(result: CreateAgentSessionRuntimeResult): boolean { @@ -538,6 +539,9 @@ export class AgentSessionRuntime implements AgentSessionRuntimeHost { this.beforeSessionInvalidate?.(); session.dispose(); this.currentSessionDisposed = true; + // Bounded: what the stopped requests still owe (a released reservation) + // gets its chance before the host exits. + await session.settleRequestTeardowns(); } } finally { this.rebindSession = undefined; diff --git a/packages/coding-agent/src/core/agent-session-services.ts b/packages/coding-agent/src/core/agent-session-services.ts index c2397ccfe..c2eb6efec 100644 --- a/packages/coding-agent/src/core/agent-session-services.ts +++ b/packages/coding-agent/src/core/agent-session-services.ts @@ -51,6 +51,8 @@ export interface CreateAgentSessionServicesOptions { extensionFlagValues?: Map; resourceLoaderOptions?: Omit; resourceLoaderReloadOptions?: ResourceLoaderReloadOptions; + /** Default model-fetch wrapper for sessions created from these services. */ + modelFetch?: CreateAgentSessionOptions["modelFetch"]; } /** @@ -76,6 +78,8 @@ export interface CreateAgentSessionFromServicesOptions { customTools?: ToolDefinition[]; /** Optional best-effort observer for provider request lifecycle metrics. */ modelRequestObserver?: ModelRequestObserver; + /** Optional host wrapper around each model request's HTTP fetch; replaces `services.modelFetch`. */ + modelFetch?: CreateAgentSessionOptions["modelFetch"]; /** Optional product identity used by the default system prompt. */ systemPromptProduct?: SystemPromptProduct; } @@ -95,6 +99,8 @@ export interface AgentSessionServices { settingsManager: SettingsManager; resourceLoader: ResourceLoader; diagnostics: AgentSessionRuntimeDiagnostic[]; + /** Default model-fetch wrapper for sessions created from these services. */ + modelFetch?: CreateAgentSessionOptions["modelFetch"]; } function applyExtensionFlagValues( @@ -215,6 +221,7 @@ export async function createAgentSessionServices( settingsManager, resourceLoader, diagnostics, + ...(options.modelFetch ? { modelFetch: options.modelFetch } : {}), }; } @@ -246,6 +253,7 @@ export async function createAgentSessionFromServices( customTools: options.customTools, sessionStartEvent: options.sessionStartEvent, modelRequestObserver: options.modelRequestObserver, + modelFetch: options.modelFetch ?? options.services.modelFetch, systemPromptProduct: options.systemPromptProduct, }); } diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts index e6b114869..92c0049d0 100644 --- a/packages/coding-agent/src/core/agent-session.ts +++ b/packages/coding-agent/src/core/agent-session.ts @@ -139,11 +139,13 @@ import { recordIncompleteTurn, } from "./incomplete-turn-recovery.ts"; import { type BashExecutionMessage, type CustomMessage, convertToLlm } from "./messages.ts"; +import type { ModelQueueChannel, ModelQueueState } from "./model-fetch.ts"; import { ModelRegistry } from "./model-registry.ts"; import type { ModelRuntime } from "./model-runtime.ts"; import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.ts"; import { isRateLimitError, rateLimitDelay } from "./rate-limit.ts"; import type { RequestLedger } from "./request-provenance.ts"; +import type { RequestTeardowns } from "./request-teardowns.ts"; import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.ts"; import type { AgentRunFailure } from "./run-failure.ts"; import { exportSessionToJsonl } from "./session-export.ts"; @@ -222,6 +224,19 @@ export type AgentSessionEvent = | { type: "summarization_retry_finished" } | { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string } | { type: "bash_execution_update"; id?: string; delta: string } + | { + /** + * A model request waits in a server-side line (`queue`), or left it + * (`queue: null`, with `closedReason` when the server closed its place). + * Reported by the host's model-fetch wrapper. A live frame (see + * `session-event-durability.ts`): records skip it, live consumers and + * `--include-live-events` streams (a subagent's parent) receive it. + */ + type: "model_queue"; + queueId: string; + queue: ModelQueueState | null; + closedReason?: string; + } | { /** Request-time lightweight context projection telemetry (step.compaction.contextProjection). */ type: "context_projection"; @@ -326,6 +341,10 @@ export interface AgentSessionConfig { * the message are recorded. */ requestLedger?: RequestLedger; + /** Queue reports from the model-fetch wrappers of this session's requests, published as `model_queue`. */ + modelQueue?: ModelQueueChannel; + /** Work this session's model requests still owe; see {@link AgentSession.settleRequestTeardowns}. */ + requestTeardowns?: RequestTeardowns; } export interface ExtensionBindings { @@ -621,6 +640,16 @@ export class AgentSession { sessionId: () => this.sessionManager.getSessionId(), ...(config.requestLedger ? { ledger: config.requestLedger } : {}), }); + this._modelQueue = config.modelQueue; + this._requestTeardowns = config.requestTeardowns; + this._modelQueue?.connect((queueId, queue, exit) => + this._emit({ + type: "model_queue", + queueId, + queue, + ...(exit?.closedReason === undefined ? {} : { closedReason: exit.closedReason }), + }), + ); // Always subscribe to agent events for internal handling // (session persistence, extensions, auto-compaction, retry logic) @@ -1472,6 +1501,9 @@ export class AgentSession { private _lastAssistantEntryId: string | undefined = undefined; /** What the session writes about how it ran (tool calls, turns, thinking, requests); see `execution-trace.ts`. */ private readonly _trace: SessionExecutionTrace; + /** Queue reports from this session's model-fetch wrappers; disconnected on dispose. */ + private readonly _modelQueue: ModelQueueChannel | undefined; + private readonly _requestTeardowns: RequestTeardowns | undefined; /** Recovery prompt selected at the end of a turn and waiting for its continuation to start. */ private _pendingIncompleteTurnRecovery: CustomMessage | undefined = undefined; @@ -1849,6 +1881,16 @@ export class AgentSession { } } + /** + * Wait, at most `limitMs`, for the work this session's model requests still + * owe after `dispose()` stopped them (for example releasing a server-side + * reservation). Returns at once when there is none. Owners that dispose a + * session (runtime dispose and replacement) await it before going on. + */ + async settleRequestTeardowns(limitMs?: number): Promise { + await this._requestTeardowns?.settle(limitMs); + } + /** * Remove all listeners and disconnect from agent. * Call this when completely done with the session. @@ -1857,6 +1899,7 @@ export class AgentSession { // The filter is this session's, not the agent's: a caller that keeps the // agent must not inherit a rule about a decision nobody owns any more. this.agent.setQueueDeliveryFilter(undefined); + this._modelQueue?.connect(undefined); try { this.abortRetry(); this.abortCompaction(); diff --git a/packages/coding-agent/src/core/index.ts b/packages/coding-agent/src/core/index.ts index 6961e6a46..1e1a4f026 100644 --- a/packages/coding-agent/src/core/index.ts +++ b/packages/coding-agent/src/core/index.ts @@ -85,6 +85,15 @@ export { INCOMPLETE_TURN_RECOVERY_ATTEMPTS, INCOMPLETE_TURN_RECOVERY_CUSTOM_TYPE, } from "./incomplete-turn-recovery.ts"; +export { + type ModelFetch, + type ModelFetchFactory, + type ModelFetchRequest, + ModelQueueChannel, + type ModelQueueExit, + type ModelQueueListener, + type ModelQueueState, +} from "./model-fetch.ts"; export { type ModelRequestCompleted, type ModelRequestObserver, diff --git a/packages/coding-agent/src/core/model-fetch.ts b/packages/coding-agent/src/core/model-fetch.ts new file mode 100644 index 000000000..c18342dd9 --- /dev/null +++ b/packages/coding-agent/src/core/model-fetch.ts @@ -0,0 +1,73 @@ +import type { Api, Model } from "@step-harness/providers/compat"; + +/** The HTTP fetch a provider adapter uses for one model request. */ +export type ModelFetch = typeof globalThis.fetch; + +/** A model request waiting in a server-side line before it runs. */ +export interface ModelQueueState { + /** Place in line, when the server reported one. */ + readonly position?: number; +} + +/** How a request left a server-side line, when the server ended its place. */ +export interface ModelQueueExit { + /** The server's stable code for closing the place (for example `queue_full`). */ + readonly closedReason?: string; +} + +/** Receives a session's queue reports; see {@link ModelFetchRequest.reportQueue}. */ +export type ModelQueueListener = (queueId: string, state: ModelQueueState | null, exit?: ModelQueueExit) => void; + +/** What a {@link ModelFetchFactory} learns about the model request it wraps. */ +export interface ModelFetchRequest { + readonly model: Model; + /** + * Cancellation of the logical request (user stop, stream watchdog). The SDK + * passes its own per-attempt signal on `init.signal`, which also carries the + * SDK's request timeout; a wrapper that holds a request must tell the two apart. + */ + readonly signal: AbortSignal; + /** The fetch the request would use without the wrapper. */ + readonly fetch: ModelFetch; + /** + * Suspend the stream idle watchdog while the request is deliberately held + * before the provider answers. Returns the release function. + */ + readonly holdIdleWatchdog: () => () => void; + /** + * Report that the request waits in a server-side line (`state`), or left it + * (`null`, with `exit.closedReason` when the server closed the place). The + * session publishes each report as a `model_queue` event. `queueId` is the + * wrapper's id for one place in line (an HTTP call it wraps); one model + * request may make several. + */ + readonly reportQueue: ModelQueueListener; + /** + * Register work the request still owes after its caller stopped waiting (see + * `request-teardowns.ts`); disposing the session awaits it, with a bound. + */ + readonly registerTeardown: (task: Promise) => void; +} + +/** + * Host hook that wraps the HTTP fetch of each model request. Returning + * `undefined` leaves the request unchanged. Not installed by default. + */ +export type ModelFetchFactory = (request: ModelFetchRequest) => ModelFetch | undefined; + +/** + * Connects the wrappers of a session's model requests to the session that + * publishes their queue reports. The session connects once it exists; reports + * made before that (or after the session was disposed) are dropped. + */ +export class ModelQueueChannel { + private listener: ModelQueueListener | undefined; + + connect(listener: ModelQueueListener | undefined): void { + this.listener = listener; + } + + report(queueId: string, state: ModelQueueState | null, exit?: ModelQueueExit): void { + this.listener?.(queueId, state, exit); + } +} diff --git a/packages/coding-agent/src/core/request-teardowns.ts b/packages/coding-agent/src/core/request-teardowns.ts new file mode 100644 index 000000000..1fb761f6b --- /dev/null +++ b/packages/coding-agent/src/core/request-teardowns.ts @@ -0,0 +1,38 @@ +/** + * Work a model request still owes after its caller stopped waiting for it: for + * example telling a server to release a reservation the request held. A request + * registers such work while it runs; whoever disposes the session awaits it, + * with a bound, before the process can exit. Nothing is registered by default, + * so a session without such work never waits. + */ + +/** How long a disposing session waits for registered request teardowns. */ +export const DEFAULT_REQUEST_TEARDOWN_LIMIT_MS = 2_000; + +export class RequestTeardowns { + private readonly pending = new Set>(); + + /** Track `task` until it settles; its outcome (or failure) is the registrant's concern. */ + register(task: Promise): void { + const settled = task.then( + () => undefined, + () => undefined, + ); + this.pending.add(settled); + void settled.then(() => this.pending.delete(settled)); + } + + /** Wait for the teardowns registered so far, at most `limitMs`; returns at once when there are none. */ + async settle(limitMs: number = DEFAULT_REQUEST_TEARDOWN_LIMIT_MS): Promise { + if (this.pending.size === 0) return; + let timer: ReturnType | undefined; + const limit = new Promise((resolve) => { + timer = setTimeout(resolve, limitMs); + }); + try { + await Promise.race([Promise.allSettled([...this.pending]), limit]); + } finally { + clearTimeout(timer); + } + } +} diff --git a/packages/coding-agent/src/core/sdk.ts b/packages/coding-agent/src/core/sdk.ts index c5470047a..33f1c1838 100644 --- a/packages/coding-agent/src/core/sdk.ts +++ b/packages/coding-agent/src/core/sdk.ts @@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto"; import { join } from "node:path"; import { Agent, type AgentMessage, setDefaultStreamFn, type ThinkingLevel } from "@step-harness/agent-core"; import type { AssistantMessageEventStream, ModelsSimpleStreamOptions } from "@step-harness/providers"; -import { withStreamIdleWatchdog } from "@step-harness/providers"; +import { StreamIdleHold, withStreamIdleWatchdog } from "@step-harness/providers"; import { type Api, clampThinkingLevel, type Message, type Model, streamSimple } from "@step-harness/providers/compat"; import { getAgentDir } from "../config.ts"; import { resolvePath } from "../utils/paths.ts"; @@ -11,6 +11,7 @@ import { formatNoModelsAvailableMessage } from "./auth-guidance.ts"; import { DEFAULT_THINKING_LEVEL } from "./defaults.ts"; import type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from "./extensions/index.ts"; import { convertToLlm } from "./messages.ts"; +import { type ModelFetchFactory, ModelQueueChannel } from "./model-fetch.ts"; import { type ModelRequestObserver, observeModelRequestFailure, @@ -20,6 +21,7 @@ import { findInitialModel } from "./model-resolver.ts"; import { ModelRuntime } from "./model-runtime.ts"; import { mergeProviderAttributionHeaders } from "./provider-attribution.ts"; import { RequestLedger, type RequestUsageProvenance, rememberRequestUsage } from "./request-provenance.ts"; +import { RequestTeardowns } from "./request-teardowns.ts"; import type { ResourceLoader } from "./resource-loader.ts"; import { DefaultResourceLoader } from "./resource-loader.ts"; import { getDefaultSessionDir, SessionManager } from "./session-manager.ts"; @@ -113,6 +115,8 @@ export interface CreateAgentSessionOptions { sessionStartEvent?: SessionStartEvent; /** Optional best-effort observer for provider request lifecycle metrics. */ modelRequestObserver?: ModelRequestObserver; + /** Optional host wrapper around each model request's HTTP fetch. */ + modelFetch?: ModelFetchFactory; /** Optional product identity used by the default system prompt. */ systemPromptProduct?: SystemPromptProduct; } @@ -338,6 +342,9 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {} const extensionRunnerRef: { current?: ExtensionRunner } = {}; const modelRequestObserver = options.modelRequestObserver; + const modelFetch = options.modelFetch; + const modelQueue = new ModelQueueChannel(); + const requestTeardowns = new RequestTeardowns(); const requestLedger = new RequestLedger(); agent = new Agent({ @@ -386,9 +393,23 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {} // The stream watchdog cancels a stalled request through this controller; a caller // abort still wins and reaches the provider unchanged. const watchdogAbort = new AbortController(); + const requestSignal = options?.signal + ? AbortSignal.any([options.signal, watchdogAbort.signal]) + : watchdogAbort.signal; + const idleHold = new StreamIdleHold(); + const baseFetch = options?.fetch ?? ((input, init) => globalThis.fetch(input, init)); + const fetch = modelFetch?.({ + model, + signal: requestSignal, + fetch: baseFetch, + holdIdleWatchdog: () => idleHold.acquire(), + reportQueue: (queueId, state, exit) => modelQueue.report(queueId, state, exit), + registerTeardown: (task) => requestTeardowns.register(task), + }); const requestOptions: ModelsSimpleStreamOptions = { ...options, - signal: options?.signal ? AbortSignal.any([options.signal, watchdogAbort.signal]) : watchdogAbort.signal, + signal: requestSignal, + ...(fetch ? { fetch } : {}), timeoutMs, websocketConnectTimeoutMs, maxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries, @@ -413,6 +434,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {} try { stream = withStreamIdleWatchdog(modelRuntime.streamSimple(model, context, requestOptions), { idleTimeoutMs: providerRetrySettings.streamIdleTimeoutMs, + hold: idleHold, onTimeout: () => watchdogAbort.abort(new Error("Provider stream idle timeout")), fallback: () => ({ role: "assistant", @@ -540,6 +562,8 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {} sessionStartEvent: options.sessionStartEvent, systemPromptProduct: options.systemPromptProduct, requestLedger, + modelQueue, + requestTeardowns, }); const extensionsResult = resourceLoader.getExtensions(); diff --git a/packages/coding-agent/src/core/session-event-durability.ts b/packages/coding-agent/src/core/session-event-durability.ts index 9ab635cd6..a27726688 100644 --- a/packages/coding-agent/src/core/session-event-durability.ts +++ b/packages/coding-agent/src/core/session-event-durability.ts @@ -39,10 +39,18 @@ export type SessionEventDurability = "durable" | "ephemeral"; * The successor test is what keeps `bash_execution_update` out: it carries a * delta, not a snapshot, and a user-issued `!` command has no message event that * would restate its output. Dropping it would lose the output, not repeat it. + * + * `model_queue` passes it: it is the in-progress state of a model request + * waiting in a server-side line, each report replaces the previous one, and the + * request's own `message_end` (an answer, or the queue's error) is the + * replayable outcome. A record therefore keeps nothing of it, while live + * consumers still get it: the in-process TUI and web host, and the parent of a + * subagent, which starts its child's `--mode rpc` with `--include-live-events`. */ const EPHEMERAL_SESSION_EVENT_TYPES: ReadonlySet = new Set([ "message_update", "tool_execution_update", + "model_queue", ]); export function sessionEventDurability(event: Pick): SessionEventDurability { diff --git a/packages/coding-agent/src/features/step.ts b/packages/coding-agent/src/features/step.ts index e684f6c80..4ca72f6db 100644 --- a/packages/coding-agent/src/features/step.ts +++ b/packages/coding-agent/src/features/step.ts @@ -42,8 +42,8 @@ import { applyStepTraceHeaders } from "../step/trace-headers.ts"; import { isPlanExtensionMounted, planModeToolCallDecision } from "./step-plan.ts"; import { fetchStepModelEfforts, + isStepProvider, registerStepProvider, - STEP_PROVIDER_ID, stepModelsDetailBaseUrl, stepThinkingLevelMap, } from "./step-provider/index.ts"; @@ -81,7 +81,7 @@ async function enrichStepModelEffort( pi: ExtensionAPI, ): Promise { try { - if (!model || model.provider !== STEP_PROVIDER_ID) return; + if (!model || !isStepProvider(model)) return; if (!model.thinkingLevelMap) { const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model); if (auth.ok && auth.apiKey) { diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts index 8ddb66245..afb909270 100644 --- a/packages/coding-agent/src/index.ts +++ b/packages/coding-agent/src/index.ts @@ -257,6 +257,15 @@ export { convertToLlm, createCompactionSummaryMessage, } from "./core/messages.ts"; +export { + type ModelFetch, + type ModelFetchFactory, + type ModelFetchRequest, + ModelQueueChannel, + type ModelQueueExit, + type ModelQueueListener, + type ModelQueueState, +} from "./core/model-fetch.ts"; export { ModelRegistry } from "./core/model-registry.ts"; export { type ModelRequestCompleted, @@ -550,7 +559,7 @@ export { type StepCronRuntimeOptions, stepCronExtensionInline, } from "./features/step-cron.ts"; -export { createStepProviderConfig, STEP_PROVIDER_ID } from "./features/step-provider/index.ts"; +export { createStepProviderConfig, isStepProvider, STEP_PROVIDER_ID } from "./features/step-provider/index.ts"; export { createStepRuntimeContextExtension, type StepRuntimeContextExtensionOptions, @@ -730,6 +739,15 @@ export { export { ambiguousPluginServerNames, resolveStepMcpServer } from "./step/mcp.ts"; export { describeStepMcpImportOutcome, runStepMcpImportPrompt } from "./step/mcp-import-prompt.ts"; export { hasStoredMcpOAuthCredential, loginMcpServer, logoutMcpServer } from "./step/mcp-oauth.ts"; +export { + createStepModelQueueFactory, + resolveStepModelQueueEnabled, + STEP_MODEL_QUEUE_ENV, + type StepModelQueueFactoryOptions, + type StepModelQueueSource, + type StepModelQueueSwitchInput, + stepModelQueueStatusText, +} from "./step/model-queue.ts"; export { resolveStepLoginProfiles } from "./step/onboarding.ts"; export { AUTO_RESUME_PROMPT, diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts index 864475e17..98606906e 100644 --- a/packages/coding-agent/src/main.ts +++ b/packages/coding-agent/src/main.ts @@ -62,6 +62,7 @@ import { AuthStorage, ReadOnlyAuthStorage } from "./core/auth-storage.ts"; import { exportFromFile } from "./core/export-html/index.ts"; import type { InlineExtension, ToolDefinition } from "./core/extensions/types.ts"; import { applyHttpProxySettings, configureHttpDispatcher } from "./core/http-dispatcher.ts"; +import type { ModelFetchFactory } from "./core/model-fetch.ts"; import type { ModelRequestObserver } from "./core/model-request-observer.ts"; import { resolveCliModel, resolveModelScope, type ScopedModel } from "./core/model-resolver.ts"; import { ModelRuntime } from "./core/model-runtime.ts"; @@ -792,6 +793,8 @@ export interface MainOptions { uiHooks?: StartupUiHooks; /** Optional best-effort observer for provider request lifecycle metrics. */ modelRequestObserver?: ModelRequestObserver; + /** Optional host wrapper around each model request's HTTP fetch. */ + modelFetch?: ModelFetchFactory; /** Optional product identity used by the default system prompt. */ systemPromptProduct?: SystemPromptProduct; /** @@ -1307,6 +1310,7 @@ export async function prepareMain(args: string[], options?: MainOptions): Promis noTools: sessionOptions.noTools, customTools: sessionOptions.customTools, modelRequestObserver: options?.modelRequestObserver, + modelFetch: options?.modelFetch, systemPromptProduct: options?.systemPromptProduct, }); const cliThinkingOverride = parsed.thinking !== undefined || cliThinkingFromModel; diff --git a/packages/coding-agent/src/modes/print-mode.ts b/packages/coding-agent/src/modes/print-mode.ts index 53d472691..ba040bfcc 100644 --- a/packages/coding-agent/src/modes/print-mode.ts +++ b/packages/coding-agent/src/modes/print-mode.ts @@ -10,6 +10,7 @@ import type { AgentMessage } from "@step-harness/agent-core"; import { type AssistantMessage, type ImageContent, INCOMPLETE_TURN_MESSAGES } from "@step-harness/providers"; import type { AgentSessionEvent } from "../core/agent-session.ts"; import type { AgentSessionRuntimeHost } from "../core/agent-session-runtime.ts"; +import type { ModelQueueState } from "../core/model-fetch.ts"; import { flushRawStdout, waitForRawStdoutBackpressure, writeRawStdout } from "../core/output-guard.ts"; import { type ExternalPlanHandoff, readExternalPlanHandoff } from "../features/plan-handoff.ts"; import { killTrackedDetachedChildren } from "../utils/shell.ts"; @@ -41,6 +42,12 @@ export interface PrintModeOptions extends CompletionCheckOptions { * `core/session-event-durability.ts`. */ includeLiveEvents?: boolean; + /** + * Text mode: the stderr line for a model request waiting in line (a + * `model_queue` report), supplied by the host that installed the queue. + * Without it, text mode prints no queue lines. + */ + formatModelQueue?: (queue: ModelQueueState) => string; } interface TerminatingBlock { @@ -226,6 +233,10 @@ export async function runPrintMode(runtimeHost: AgentSessionRuntimeHost, options // first would be a second, silently divergent policy. const projected = toJsonEvent(event, { includeLiveEvents }); if (projected) writeRawStdout(`${JSON.stringify(projected)}\n`); + } else if (event.type === "model_queue" && event.queue && options.formatModelQueue) { + // Text mode keeps stdout for the answer; each change of place in line + // is reported once (the wrapper reports changes only) on stderr. + console.error(options.formatModelQueue(event.queue)); } }); unsubscribeBackpressure = diff --git a/packages/coding-agent/src/step/environment.ts b/packages/coding-agent/src/step/environment.ts index 8703bd609..3a6f75a6a 100644 --- a/packages/coding-agent/src/step/environment.ts +++ b/packages/coding-agent/src/step/environment.ts @@ -5,6 +5,13 @@ import { STEP_DEFAULT_MODEL, STEP_DEFAULT_PROVIDER, STEP_DEFAULT_THEME } from ". /** Canonical project directory for StepCode state and resources. */ export const STEPCODE_CONFIG_DIR = ".stepcode"; +/** + * The product StepCode's own CLI names in `x-step-client`. Every Step request + * carries it unless `STEP_CLIENT` names another product (`stepcode-desktop`, + * `stepcode-web`, or an embedding host's own). + */ +export const STEP_CLIENT_DEFAULT = "stepcode-cli"; + /** Directory used by releases before the product rename. */ export const LEGACY_RENAMED_CONFIG_DIR = ".step-harness"; @@ -137,9 +144,8 @@ export function applyStepEnvironment(env: NodeJS.ProcessEnv = process.env, optio env.STEPCODE_DEFAULT_MODEL = env.STEP_MODEL?.trim() || STEP_DEFAULT_MODEL; } // Downstream attribution marker sent as `x-step-client`. Keep it overridable - // so an embedding host can identify itself, but default shipped StepCode - // requests to `stepcode`. - if (!env.STEP_CLIENT?.trim()) env.STEP_CLIENT = "stepcode"; + // so an embedding host can identify itself; the CLI is the default product. + if (!env.STEP_CLIENT?.trim()) env.STEP_CLIENT = STEP_CLIENT_DEFAULT; // Step should not contact Pi's release/install services unless explicitly // opted in by setting STEPCODE_DISABLE_PI_SERVICES to a false value. if (!env.STEPCODE_DISABLE_PI_SERVICES?.trim()) env.STEPCODE_DISABLE_PI_SERVICES = "1"; diff --git a/packages/coding-agent/src/step/model-queue.ts b/packages/coding-agent/src/step/model-queue.ts new file mode 100644 index 000000000..a8c78caca --- /dev/null +++ b/packages/coding-agent/src/step/model-queue.ts @@ -0,0 +1,444 @@ +import { randomUUID } from "node:crypto"; +import type { ModelFetch, ModelFetchFactory, ModelFetchRequest, ModelQueueState } from "../core/model-fetch.ts"; +import type { StepSettings } from "./settings-manager.ts"; + +/** + * Client side of the Step model request queue. + * + * With the queue enabled, every model request sent to Step's mainland or + * overseas API host carries a fresh `X-StepCode-Queue-ID`, whichever provider + * (the official one or a user's own) sent it: the host, not the provider id, + * makes it a StepCode request. Whether a request waits is the server's + * decision: when the pool is busy it answers HTTP 429 with + * `X-StepCode-Queue-State: waiting` instead of running the request. That answer + * is not a rate-limit failure: the request holds a place in line. The wrapper + * then polls the queue of the request's region + * (`GET https://api.stepfun.com/stepcode/v1/queue`, or `api.stepfun.ai` + * overseas, naming the place in `X-StepCode-Queue-ID`), and once the place is + * `ready` sends the original bytes again under the same id. A `closed` place + * ends the call with an error; a stop after the server queued the call releases + * the place with `POST /cancel` (the id in `X-StepCode-Queue-ID`, no + * body). A stop before any queued answer sends nothing more: the server's lease + * ends a place nobody saw. + * + * POST .../chat/completions -> 429 queued (position 3) + * GET (X-StepCode-Queue-ID) -> waiting (position 1) + * GET (X-StepCode-Queue-ID) -> ready + * POST .../chat/completions -> 200 stream (same id, same body) + * + * A request to any other host (an endpoint override) is sent as it is, without + * the header. Any other response, including an ordinary 429, is returned + * unchanged so the existing retry policy handles it. + */ + +const QUEUE_ID_HEADER = "x-stepcode-queue-id"; +const STATE_HEADER = "x-stepcode-queue-state"; +const POSITION_HEADER = "x-stepcode-queue-position"; +const RETRY_AFTER_HEADER = "retry-after-ms"; +/** Request headers that describe the model request's body; the control requests carry their own. */ +const BODY_HEADERS = new Set(["content-length", "content-type", "content-encoding", "transfer-encoding", "accept"]); +/** + * The queue endpoint of each Step API host, by the model request's host name. + * Fixed on purpose: the queue exists only on these public hosts, so it is keyed + * by them and never by configuration. Telemetry's endpoint classification + * (`isStepPlatformUrl`) also follows configured proxies; the two are kept apart + * deliberately, and a request to any other host is never queued. + */ +const QUEUE_ENDPOINTS: Readonly> = { + "api.stepfun.com": "https://api.stepfun.com/stepcode/v1/queue", + "api.stepfun.ai": "https://api.stepfun.ai/stepcode/v1/queue", +}; +/** `1` / `0` force the queue on or off, over every setting. */ +export const STEP_MODEL_QUEUE_ENV = "STEPCODE_MODEL_QUEUE"; + +const DEFAULT_POLL_INTERVAL_MS = 2_000; +const MAX_POLL_INTERVAL_MS = 30_000; +const POLL_TIMEOUT_MS = 10_000; +const FIRST_POLL_BACKOFF_MS = 1_000; +const MAX_POLL_BACKOFF_MS = 8_000; +const DEFAULT_POLL_FAILURE_BUDGET_MS = 30_000; +/** Upper bound of releasing a place on a stop; the stopped call (and a disposing session) waits this long at most. */ +const CANCEL_TIMEOUT_MS = 1_000; +/** Status of the synthesized response that ends a queued call: no SDK or session retry re-enters the queue. */ +const QUEUE_ENDED_STATUS = 410; + +/** Readable text for the server's stable `closed` reason codes; unknown codes read as the generic text. */ +const CLOSED_REASON_TEXT: Readonly> = { + queue_full: "The request queue is full. Try again later.", + user_limit: "You have too many requests waiting in line. Wait for them to finish and try again.", + lease_expired: "Your place in line expired. Send the request again.", + max_wait_exceeded: "The request waited in line too long. Try again later.", + not_found: "Your place in line no longer exists. Send the request again.", +}; +const CLOSED_GENERIC_TEXT = "The request queue closed this request. Try again later."; + +/** The message for a `closed` reason code, keeping the code itself for diagnosis. */ +export function stepModelQueueClosedMessage(reason: string): string { + const text = Object.hasOwn(CLOSED_REASON_TEXT, reason) ? CLOSED_REASON_TEXT[reason] : CLOSED_GENERIC_TEXT; + return reason ? `${text} (${reason})` : text; +} + +/** The status line for a request waiting in line: its position, never a wait estimate. */ +export function stepModelQueueStatusText(state: ModelQueueState): string { + return state.position !== undefined && state.position > 0 ? `Queued: position ${state.position}` : "Queued"; +} + +/** Where the effective queue switch came from. */ +export type StepModelQueueSource = "env" | "settings" | "default"; + +export interface StepModelQueueSwitchInput { + readonly env?: NodeJS.ProcessEnv; + /** Effective Step settings (project over global); `modelQueue` is the configured value. */ + readonly settings?: Pick; +} + +function readSwitch(value: string | undefined): boolean | undefined { + switch (value?.trim().toLowerCase()) { + case "1": + case "true": + return true; + case "0": + case "false": + return false; + default: + return undefined; + } +} + +/** + * Whether Step model requests join the queue. `STEPCODE_MODEL_QUEUE` wins, then + * `model_queue` (project over global); with neither, it is on, whatever the + * host (CLI, desktop, web, subagent children). + */ +export function resolveStepModelQueueEnabled(input: StepModelQueueSwitchInput): { + readonly enabled: boolean; + readonly source: StepModelQueueSource; +} { + const env = input.env ?? process.env; + const forced = readSwitch(env[STEP_MODEL_QUEUE_ENV]); + if (forced !== undefined) return { enabled: forced, source: "env" }; + const configured = input.settings?.modelQueue; + if (typeof configured === "boolean") return { enabled: configured, source: "settings" }; + return { enabled: true, source: "default" }; +} + +/** Hooks for tests; not configuration. */ +export interface StepModelQueueOptions { + /** Replaces the fixed queue endpoints, by request host name. */ + readonly queueEndpoints?: Readonly>; + /** How long polling may fail in a row before the call ends with an error. Default 30s. */ + readonly pollFailureBudgetMs?: number; + readonly queueId?: () => string; + readonly sleep?: (ms: number, signal: AbortSignal) => Promise; + readonly now?: () => number; + readonly env?: NodeJS.ProcessEnv; +} + +export interface StepModelQueueFactoryOptions { + readonly env?: NodeJS.ProcessEnv; + /** The effective Step settings, read on every request so a settings reload applies to the next one. */ + readonly settings: () => Pick | undefined; +} + +/** + * The model-fetch factory every Step entry point installs. With the queue off + * the request is left alone (no wrapper); with it on, the wrapper tags and + * queues only requests to Step's API hosts and passes every other one on as it is. + */ +export function createStepModelQueueFactory( + options: StepModelQueueFactoryOptions, + /** Test hooks; see {@link StepModelQueueOptions}. */ + testing: StepModelQueueOptions = {}, +): ModelFetchFactory { + return (request) => { + const { enabled } = resolveStepModelQueueEnabled({ + env: options.env, + settings: options.settings(), + }); + return enabled ? createStepModelQueueFetch(request, testing) : undefined; + }; +} + +/** + * Whether a URL is one of the queue's own control endpoints. A control request + * passed to the wrapper goes out as it is: never given a new queue id, held or + * queued (the wrapper's own control requests carry the id of the place they ask about). + */ +function isQueueControl(url: URL, queue: string): boolean { + const path = new URL(queue).pathname; + return url.pathname === path || url.pathname.startsWith(`${path}/`); +} + +function requestUrl(input: Parameters[0]): URL | undefined { + try { + return new URL(input instanceof Request ? input.url : input instanceof URL ? input.href : input); + } catch { + return undefined; + } +} + +function nonNegativeInteger(value: unknown): number | undefined { + const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value; + return typeof number === "number" && Number.isSafeInteger(number) && number >= 0 ? number : undefined; +} + +function pollInterval(value: unknown): number { + const ms = nonNegativeInteger(value); + return ms === undefined || ms === 0 ? DEFAULT_POLL_INTERVAL_MS : Math.min(ms, MAX_POLL_INTERVAL_MS); +} + +function isQueued(response: Response): boolean { + return response.status === 429 && response.headers.get(STATE_HEADER)?.trim().toLowerCase() === "waiting"; +} + +/** The cancellation to throw: always an Error, as callers and SDKs test `instanceof Error`. */ +function abortError(signal: AbortSignal): Error { + const reason: unknown = signal.reason; + if (reason instanceof Error) return reason; + return new DOMException(reason === undefined ? "This operation was aborted" : String(reason), "AbortError"); +} + +function defaultSleep(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(abortError(signal)); + return; + } + const onAbort = () => { + clearTimeout(timer); + reject(abortError(signal)); + }; + const timer = setTimeout(() => { + signal.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal.addEventListener("abort", onAbort, { once: true }); + }); +} + +function queueEnded(message: string, reason?: string): Response { + return new Response( + JSON.stringify({ error: { message, type: "queue_closed", code: "queue_closed", ...(reason ? { reason } : {}) } }), + { + status: QUEUE_ENDED_STATUS, + headers: { "content-type": "application/json", "x-should-retry": "false" }, + }, + ); +} + +interface QueueStatus { + readonly state: "waiting" | "ready" | "closed"; + readonly position?: number; + readonly retryAfterMs: number; + readonly reason: string; +} + +function readQueueStatus(value: unknown): QueueStatus | undefined { + if (!value || typeof value !== "object") return undefined; + const state = Reflect.get(value, "state"); + if (state !== "waiting" && state !== "ready" && state !== "closed") return undefined; + const reason = Reflect.get(value, "reason"); + return { + state, + position: nonNegativeInteger(Reflect.get(value, "position")), + retryAfterMs: pollInterval(Reflect.get(value, "retry_after_ms")), + reason: typeof reason === "string" ? reason : "", + }; +} + +/** + * Wrap one Step model request's fetch with the queue protocol. The control + * requests are sent on the unwrapped fetch and are never tagged or held. + */ +export function createStepModelQueueFetch( + request: Pick, + options: StepModelQueueOptions = {}, +): ModelFetch { + const base = request.fetch; + const caller = request.signal; + const sleep = options.sleep ?? defaultSleep; + const now = options.now ?? Date.now; + const failureBudgetMs = options.pollFailureBudgetMs ?? DEFAULT_POLL_FAILURE_BUDGET_MS; + return async (input, init) => { + // Decided from the URL alone, so a request that is not queued is passed on + // without copying its body. + const url = requestUrl(input); + const endpoints = options.queueEndpoints ?? QUEUE_ENDPOINTS; + const queueBase = url && Object.hasOwn(endpoints, url.hostname) ? endpoints[url.hostname] : undefined; + if (!url || !queueBase || isQueueControl(url, queueBase)) return base(input, init); + return queuedFetch(input, init, queueBase); + }; + + async function queuedFetch( + input: Parameters[0], + init: Parameters[1], + queueBase: string, + ): Promise { + const original = new Request(input, init); + const queueId = (options.queueId ?? randomUUID)(); + const headers = new Headers(original.headers); + headers.set(QUEUE_ID_HEADER, queueId); + // Captured once: every resend carries exactly these bytes. + const body = original.body ? new Uint8Array(await original.arrayBuffer()) : undefined; + // A `Request` input carries its own signal; `original` follows it as well as `init.signal`. + const attempt = init?.signal ?? original.signal; + const send = (signal: AbortSignal | undefined) => + base(original.url, { + ...init, + method: original.method, + headers, + ...(body ? { body: body.slice() } : {}), + ...(signal ? { signal } : {}), + }); + // The model request's own credentials and routing headers authorize the + // control requests; what describes its body does not apply to them. Both + // name the place by its queue id header (no query, no body); they go out on + // the unwrapped fetch, so they are never queued themselves. + const controlHeaders = new Headers({ accept: "application/json" }); + for (const [name, value] of original.headers) { + if (!BODY_HEADERS.has(name)) controlHeaders.set(name, value); + } + controlHeaders.set(QUEUE_ID_HEADER, queueId); + // Leave the line so the place is not held until its lease expires. Sent only + // once the server has queued this call, so a host without the queue never + // sees it. Awaited (within CANCEL_TIMEOUT_MS) so a process exiting on the + // stop sends it; its outcome changes nothing for the stopped call, so + // failures are dropped. + const leave = async (): Promise => { + try { + const response = await base(`${queueBase}/cancel`, { + method: "POST", + headers: controlHeaders, + signal: AbortSignal.timeout(CANCEL_TIMEOUT_MS), + }); + await response.body?.cancel().catch(() => {}); + } catch { + // Unreachable or too slow: the server's lease ends the place instead. + } + }; + + // A stop during the first send is the caller's alone: nothing says the server + // queued the call, and if it did, its lease ends the place. + const first = await send(attempt); + if (!isQueued(first)) return first; + // From here the call holds a place in line until it settles, and a stop must + // release it: the settlement is a teardown the disposing session awaits. + let settled = () => {}; + request.registerTeardown( + new Promise((resolve) => { + settled = resolve; + }), + ); + // The idle watchdog is held only while the call waits in line; a resend is + // an ordinary request again and stays under the idle bound. + let release: (() => void) | undefined; + const hold = () => { + release ??= request.holdIdleWatchdog(); + }; + const unhold = () => { + const current = release; + release = undefined; + current?.(); + }; + hold(); + let position = nonNegativeInteger(first.headers.get(POSITION_HEADER)); + let delay = pollInterval(first.headers.get(RETRY_AFTER_HEADER)); + await first.body?.cancel().catch(() => {}); + // Reports go out only when the place in line or being in line changes. + let reported: { readonly queued: boolean; readonly position?: number } = { queued: false }; + const publish = (queued: boolean, closedReason?: string) => { + const next: { readonly queued: boolean; readonly position?: number } = queued + ? { queued, ...(position === undefined ? {} : { position }) } + : { queued }; + if (next.queued === reported.queued && next.position === reported.position) return; + reported = next; + try { + request.reportQueue( + queueId, + queued ? (position === undefined ? {} : { position }) : null, + ...(closedReason === undefined ? [] : [{ closedReason }]), + ); + } catch { + // Presentation must not change the request. + } + }; + publish(true); + let closedReason: string | undefined; + try { + let lastSuccess = now(); + let failures = 0; + let lastFailure = ""; + for (;;) { + // The SDK's per-attempt signal also carries its request timeout, which + // must not end a wait in line: only the caller's cancellation does. + await sleep(delay, caller); + let status: QueueStatus | undefined; + try { + const response = await base(queueBase, { + method: "GET", + headers: controlHeaders, + signal: AbortSignal.any([caller, AbortSignal.timeout(POLL_TIMEOUT_MS)]), + }); + if (response.ok) { + status = readQueueStatus(await response.json().catch(() => undefined)); + if (!status) lastFailure = "invalid queue status"; + } else if (response.status === 401 || response.status === 403) { + // A credential problem is the caller's to see, as it would be on the model route. + return response; + } else { + await response.body?.cancel().catch(() => {}); + // The place is gone: the same as a closed place. + if (response.status === 404) status = { state: "closed", retryAfterMs: delay, reason: "not_found" }; + // A throttled or failing status endpoint is retried; other answers + // cannot improve by asking again. + else if (response.status !== 429 && response.status < 500) + return queueEnded(`Queue status request failed with HTTP ${response.status}`); + else lastFailure = `HTTP ${response.status}`; + } + } catch (error) { + if (caller.aborted) throw abortError(caller); + lastFailure = error instanceof Error ? error.message : String(error); + } + if (!status) { + if (now() - lastSuccess >= failureBudgetMs) + return queueEnded(`Queue status unavailable: ${lastFailure}`); + delay = Math.min(FIRST_POLL_BACKOFF_MS * 2 ** failures, MAX_POLL_BACKOFF_MS); + failures++; + continue; + } + lastSuccess = now(); + failures = 0; + delay = status.retryAfterMs; + if (status.state === "closed") { + closedReason = status.reason; + return queueEnded(stepModelQueueClosedMessage(status.reason), status.reason); + } + if (status.state === "waiting") { + position = status.position ?? position; + publish(true); + continue; + } + // The SDK's per-attempt signal joins the resend only while it is live: an + // abort it already carries is its request timeout expiring in line. + unhold(); + const response = await send(attempt && !attempt.aborted ? AbortSignal.any([caller, attempt]) : caller); + if (!isQueued(response)) return response; + hold(); + position = nonNegativeInteger(response.headers.get(POSITION_HEADER)) ?? position; + delay = pollInterval(response.headers.get(RETRY_AFTER_HEADER)); + void response.body?.cancel().catch(() => {}); + publish(true); + } + } catch (error) { + if (caller.aborted) { + await leave(); + throw abortError(caller); + } + throw error; + } finally { + publish(false, closedReason); + unhold(); + settled(); + } + } +} diff --git a/packages/coding-agent/src/step/sdk.ts b/packages/coding-agent/src/step/sdk.ts index e6fa65f68..6fcf03f5a 100644 --- a/packages/coding-agent/src/step/sdk.ts +++ b/packages/coding-agent/src/step/sdk.ts @@ -13,6 +13,7 @@ import { createAgentSession } from "../core/sdk.ts"; import type { SettingsManager } from "../core/settings-manager.ts"; import { resolvePath } from "../utils/paths.ts"; import { resolveStepAgentDir, resolveStepConfigDir } from "./environment.ts"; +import { createStepModelQueueFactory } from "./model-queue.ts"; import { createStepSessionManager, wrapStepSessionManager } from "./session.ts"; import { createStepSettingsManager, @@ -89,6 +90,16 @@ function ensureStepSettingsManager( }); } +/** + * The Step model request queue for sessions using these settings. A caller's + * own `modelFetch` replaces it. + */ +function stepModelQueueFactory(settingsManager: StepSettingsManager) { + return createStepModelQueueFactory({ + settings: () => settingsManager.getStepSettings(), + }); +} + /** Create a Pi AgentSession with Step's settings decorator installed. */ export async function createStepAgentSession( options: CreateStepAgentSessionOptions = {}, @@ -108,6 +119,7 @@ export async function createStepAgentSession( configDirName: paths.configDirName, settingsManager, sessionManager, + modelFetch: options.modelFetch ?? stepModelQueueFactory(settingsManager), }); } @@ -123,5 +135,6 @@ export async function createStepAgentSessionServices( agentDir: paths.agentDir, configDirName: paths.configDirName, settingsManager, + modelFetch: options.modelFetch ?? stepModelQueueFactory(settingsManager), }) as Promise; } diff --git a/packages/coding-agent/src/step/settings-manager.ts b/packages/coding-agent/src/step/settings-manager.ts index ae09cb1f5..e90190820 100644 --- a/packages/coding-agent/src/step/settings-manager.ts +++ b/packages/coding-agent/src/step/settings-manager.ts @@ -47,6 +47,13 @@ export interface StepSettings { subagentBackgroundTimeoutSeconds?: number; /** `[subagent] max_concurrency`: default number of child processes a parallel subagent batch runs at once. */ subagentMaxConcurrency?: number; + /** + * `model_queue`: model requests sent to Step's API hosts (`api.stepfun.com`, + * `api.stepfun.ai`), whichever provider sends them, carry the queue protocol + * and wait when the server queues them. On unless set; `STEPCODE_MODEL_QUEUE` + * overrides it (`src/step/model-queue.ts`). + */ + modelQueue?: boolean; } type JsonObject = Record; @@ -107,6 +114,16 @@ function rawSubagentConcurrencies(value: JsonObject): unknown[] { ); } +/** The raw configured queue switches, from `model_queue` and the flat key. */ +function rawModelQueueValues(value: JsonObject): unknown[] { + return [value.model_queue, value.modelQueue].filter((candidate) => candidate !== undefined); +} + +/** Message for a configured queue switch that is ignored because it is not a boolean. */ +export function invalidModelQueueMessage(value: unknown, keyPath = "model_queue"): string { + return `${keyPath} must be true or false; ignoring ${JSON.stringify(value)}`; +} + export interface StepSettingsPaths { global: string; project: string; @@ -307,6 +324,10 @@ function normalizeSettings(value: JsonObject, resetLegacy = true): StepSettings isValidSubagentMaxConcurrency, ); if (subagentConcurrency !== undefined) result.subagentMaxConcurrency = subagentConcurrency; + const modelQueue = [value.model_queue, value.modelQueue].find( + (candidate): candidate is boolean => typeof candidate === "boolean", + ); + if (modelQueue !== undefined) result.modelQueue = modelQueue; if (resetLegacy) resetLegacyPermissionSettings(result, winningPresetCandidate, winningModeCandidate); return result; } @@ -335,6 +356,7 @@ const STEP_SETTING_ALIASES: Record = { subagentBackground: [], subagentBackgroundTimeoutSeconds: [], subagentMaxConcurrency: [], + modelQueue: ["model_queue"], }; const STEP_SETTING_NESTED_ALIASES: Record = { @@ -366,6 +388,7 @@ const STEP_SETTING_NESTED_ALIASES: Record): Partial { `Invalid Step subagentMaxConcurrency setting: ${String(settings.subagentMaxConcurrency)} (expected a positive integer)`, ); } + if (settings.modelQueue !== undefined && typeof settings.modelQueue !== "boolean") { + throw new Error(`Invalid Step modelQueue setting: ${String(settings.modelQueue)}`); + } const normalized = { ...settings }; if (settings.permissionPreset !== undefined) { normalized.permissionPreset = getStepPermissionPreset(settings.permissionPreset)!.id; @@ -547,6 +573,10 @@ class StepSettingsStore { if (isValidSubagentMaxConcurrency(concurrency)) continue; this.errors.push({ scope, path, error: new Error(invalidSubagentMaxConcurrencyMessage(concurrency)) }); } + for (const queue of rawModelQueueValues(value)) { + if (typeof queue === "boolean") continue; + this.errors.push({ scope, path, error: new Error(invalidModelQueueMessage(queue)) }); + } return value; } diff --git a/packages/coding-agent/src/step/telemetry-contract.ts b/packages/coding-agent/src/step/telemetry-contract.ts index edd3859e5..7036bf25d 100644 --- a/packages/coding-agent/src/step/telemetry-contract.ts +++ b/packages/coding-agent/src/step/telemetry-contract.ts @@ -1,3 +1,4 @@ +import { isStepPlatformUrl } from "@step-harness/providers/step-provider"; import type { ModelRequestObserver } from "../core/model-request-observer.ts"; import type { StepTelemetryPrimitive as RegistryTelemetryPrimitive, @@ -143,15 +144,7 @@ export function classifyStepEndpoint( ) { return "local"; } - for (const name of ["STEP_BASE_URL", "STEP_MODELS_PROXY_BASE_URL", "STEPFUN_MESSAGES_ENDPOINT"] as const) { - for (const candidate of (_env[name] ?? "").split(",")) { - try { - if (new URL(candidate.trim()).hostname.toLowerCase() === hostname) return "platform"; - } catch { - // Ignore malformed overrides. - } - } - } - if (hostname === "api.stepfun.com") return "platform"; - return "custom"; + // The Step provider's default, its endpoint overrides and a declared models + // proxy decide (comma-separated lists allowed), not a list kept here. + return isStepPlatformUrl(baseUrl, _env) ? "platform" : "custom"; } diff --git a/packages/coding-agent/src/step/trace-headers.ts b/packages/coding-agent/src/step/trace-headers.ts index 23468cd84..647afba62 100644 --- a/packages/coding-agent/src/step/trace-headers.ts +++ b/packages/coding-agent/src/step/trace-headers.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; import process from "node:process"; +import { STEP_CLIENT_DEFAULT } from "./environment.ts"; /** Values copied from the request context into Step's attribution headers. */ export interface StepTraceContext { @@ -49,7 +50,9 @@ const STEP_TRACE_PRODUCT_PROVIDERS = new Set(["stepfunModelProxy", "neocodex"]); /** * Add Step attribution headers in place. * - * `x-step-client` is sent on every request. The high-sensitivity fields + * `x-step-client` is sent on every request (`STEP_CLIENT_DEFAULT`, or the + * caller's `clientType` when it names the product). + * The high-sensitivity fields * (session/workspace/goal/...) are sent only when the request URL matches * `options.allowedBaseUrls` AND the field appears in * `options.highSensitivityFields`; an omitted or empty field list sends none of @@ -62,7 +65,7 @@ export function applyStepTraceHeaders( trace: StepTraceContext, options: StepTraceHeaderOptions = {}, ): void { - setHeader(headers, "x-step-client", options.clientType ?? "cli"); + setHeader(headers, "x-step-client", options.clientType ?? STEP_CLIENT_DEFAULT); const traceAllowed = options.requestUrl === undefined || diff --git a/packages/coding-agent/test/agent-session-runtime-concurrency.test.ts b/packages/coding-agent/test/agent-session-runtime-concurrency.test.ts index 1378d50c2..3488d00f6 100644 --- a/packages/coding-agent/test/agent-session-runtime-concurrency.test.ts +++ b/packages/coding-agent/test/agent-session-runtime-concurrency.test.ts @@ -13,7 +13,10 @@ import { import { createExtensionRuntime } from "../src/core/extensions/index.ts"; import { SessionManager } from "../src/core/session-manager.ts"; -type SessionStub = AgentSession & { readonly dispose: ReturnType }; +type SessionStub = AgentSession & { + readonly dispose: ReturnType; + readonly settleRequestTeardowns: ReturnType; +}; type RuntimeResultStub = Omit & { session: SessionStub }; function createSession(cwd: string, sessionId: string): SessionStub { @@ -28,6 +31,7 @@ function createSession(cwd: string, sessionId: string): SessionStub { }, abort: vi.fn(async () => {}), dispose: vi.fn(), + settleRequestTeardowns: vi.fn(async () => {}), createReplacedSessionContext: vi.fn(() => ({})), } as unknown as SessionStub; } @@ -100,6 +104,10 @@ describe("AgentSessionRuntime replacement coordination", () => { await runtime.dispose(); expect(initial.dispose).toHaveBeenCalledTimes(1); expect(created[1]?.dispose).toHaveBeenCalledTimes(1); + // Every disposed session, replaced or current, gets its request teardowns awaited. + for (const session of [initial, created[0], created[1]]) { + expect(session?.settleRequestTeardowns).toHaveBeenCalledTimes(1); + } }); test("does not rebind or leak a replacement when dispose races its factory", async () => { diff --git a/packages/coding-agent/test/json-event-projection.test.ts b/packages/coding-agent/test/json-event-projection.test.ts index 7870353a7..a94a6fe1a 100644 --- a/packages/coding-agent/test/json-event-projection.test.ts +++ b/packages/coding-agent/test/json-event-projection.test.ts @@ -231,3 +231,13 @@ test("the record is bounded per line even with a large payload", async () => { // message, one execution outcome. expect(hits.length).toBe(4); }); + +test("a queued model request is a live frame: kept out of records, sent to live-event consumers", () => { + const waiting: AgentSessionEvent = { type: "model_queue", queueId: "r1", queue: { position: 2 } }; + const left: AgentSessionEvent = { type: "model_queue", queueId: "r1", queue: null, closedReason: "queue_full" }; + expect(sessionEventDurability(waiting)).toBe("ephemeral"); + expect(toJsonEvent(waiting, { includeLiveEvents: false })).toBeUndefined(); + // A subagent parent starts its child with --include-live-events, so it receives both. + expect(toJsonEvent(waiting, { includeLiveEvents: true })).toEqual(waiting); + expect(toJsonEvent(left, { includeLiveEvents: true })).toEqual(left); +}); diff --git a/packages/coding-agent/test/main-model-fetch.test.ts b/packages/coding-agent/test/main-model-fetch.test.ts new file mode 100644 index 000000000..9c3ba4f11 --- /dev/null +++ b/packages/coding-agent/test/main-model-fetch.test.ts @@ -0,0 +1,121 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { createServer, type Server } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PassThrough } from "node:stream"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ModelFetchFactory } from "../src/core/model-fetch.ts"; +import { main } from "../src/main.ts"; + +/** + * The composition root hands `MainOptions.modelFetch` to the session of every + * one-shot mode. The CLI passes the model request queue's factory this way, so + * a mode that skipped it would send unqueued requests. + */ + +const roots: string[] = []; +const servers: Server[] = []; +const originalStdin = Object.getOwnPropertyDescriptor(process, "stdin"); + +afterEach(async () => { + if (originalStdin) Object.defineProperty(process, "stdin", originalStdin); + vi.restoreAllMocks(); + process.exitCode = undefined; + for (const server of servers.splice(0)) await new Promise((done) => server.close(() => done())); + for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }); +}); + +async function fixtureServer(): Promise { + const server = createServer((request, response) => { + request.resume(); + request.on("end", () => { + const common = { id: "c1", object: "chat.completion.chunk", created: 1, model: "fixture-model" }; + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end( + `data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: { role: "assistant", content: "done" }, finish_reason: null }] })}\n\n` + + `data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } })}\n\n` + + "data: [DONE]\n\n", + ); + }); + }); + servers.push(server); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("fixture server did not start"); + return `http://127.0.0.1:${address.port}/v1`; +} + +async function runOneShot(modeArgs: string[], modelFetch: ModelFetchFactory): Promise { + const root = await mkdtemp(join(tmpdir(), "pi-main-model-fetch-")); + roots.push(root); + const agentDir = join(root, "agent"); + const baseUrl = await fixtureServer(); + const catalog = { + providers: { + fixture: { + baseUrl, + api: "openai-completions", + models: [ + { + id: "fixture-model", + name: "Fixture", + reasoning: false, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 32_000, + maxTokens: 1_000, + }, + ], + }, + }, + }; + await writeFile(join(root, "models.json"), JSON.stringify(catalog)); + vi.spyOn(process.stdout, "write").mockImplementation((...args: unknown[]) => { + const done = args.find((arg): arg is () => void => typeof arg === "function"); + done?.(); + return true; + }); + vi.spyOn(console, "error").mockImplementation(() => {}); + // An empty, closed pipe: the run reads its prompt from argv, not from the test runner's stdin. + const stdin = new PassThrough(); + stdin.end(); + Object.defineProperty(process, "stdin", { value: stdin, configurable: true }); + await main( + [ + "--cwd", + root, + "--provider", + "fixture", + "--model", + "fixture-model", + "--api-key", + "test-key", + "--no-extensions", + "--no-skills", + "--no-prompt-templates", + "--no-themes", + "--no-context-files", + "--no-session", + ...modeArgs, + "Reply done.", + ], + { agentDir, modelsPath: join(root, "models.json"), disableBackgroundServices: true, modelFetch }, + ); +} + +describe("main() installs the host's model fetch in every one-shot mode", () => { + it.each([ + ["-p", ["-p"]], + ["--mode json", ["--mode", "json", "-p"]], + ])("%s", async (_label, modeArgs) => { + const urls: string[] = []; + const factory = vi.fn((request) => async (input, init) => { + urls.push(new Request(input, init).url); + return request.fetch(input, init); + }); + await runOneShot(modeArgs, factory); + expect(factory).toHaveBeenCalled(); + expect(factory.mock.calls[0]?.[0].model.id).toBe("fixture-model"); + expect(urls.some((url) => url.endsWith("/v1/chat/completions"))).toBe(true); + }); +}); diff --git a/packages/coding-agent/test/model-fetch-hook.test.ts b/packages/coding-agent/test/model-fetch-hook.test.ts new file mode 100644 index 000000000..5304eb1fa --- /dev/null +++ b/packages/coding-agent/test/model-fetch-hook.test.ts @@ -0,0 +1,214 @@ +import { existsSync, mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { AssistantMessage } from "@step-harness/providers"; +import { afterEach, describe, expect, it } from "vitest"; +import type { AgentSessionEvent } from "../src/core/agent-session.ts"; +import { AuthStorage } from "../src/core/auth-storage.ts"; +import type { ModelFetch, ModelFetchFactory, ModelFetchRequest } from "../src/core/model-fetch.ts"; +import { ModelRuntime } from "../src/core/model-runtime.ts"; +import { DefaultResourceLoader } from "../src/core/resource-loader.ts"; +import { createAgentSession } from "../src/core/sdk.ts"; +import { SessionManager } from "../src/core/session-manager.ts"; +import { SettingsManager } from "../src/core/settings-manager.ts"; + +const BASE = "https://api.example.test/v1"; +const IDLE_TIMEOUT_MS = 300; +/** Longer than the idle bound: only a hold keeps the stream alive through it. */ +const HELD_WAIT_MS = IDLE_TIMEOUT_MS * 2 + 200; + +function sse(text: string): Response { + const chunk = (body: Record) => + `data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "hook-model", ...body })}\n\n`; + return new Response( + chunk({ choices: [{ index: 0, delta: { role: "assistant", content: text }, finish_reason: null }] }) + + chunk({ + choices: [{ index: 0, delta: {}, finish_reason: "stop" }], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }) + + "data: [DONE]\n\n", + { status: 200, headers: { "content-type": "text/event-stream" } }, + ); +} + +/** A request the server never answers, not even with headers, until it is aborted. */ +function noAnswer(signal: AbortSignal | null | undefined): Promise { + return new Promise((_resolve, reject) => { + signal?.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); +} + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +describe("model fetch hook", () => { + let tempDir: string | undefined; + + afterEach(() => { + if (tempDir && existsSync(tempDir)) rmSync(tempDir, { recursive: true, force: true }); + }); + + async function runPrompt(modelFetch: ModelFetchFactory, events?: AgentSessionEvent[]) { + tempDir = join(tmpdir(), `pi-model-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}`); + const agentDir = join(tempDir, "agent"); + mkdirSync(agentDir, { recursive: true }); + const settingsManager = SettingsManager.inMemory({ + retry: { enabled: false, provider: { streamIdleTimeoutMs: IDLE_TIMEOUT_MS, maxRetries: 0 } }, + }); + expect(settingsManager.getProviderRetrySettings().streamIdleTimeoutMs).toBe(IDLE_TIMEOUT_MS); + // In memory: a file-backed store can persist after the test removed its directory. + const authStorage = AuthStorage.inMemory(); + await authStorage.modify("hook-test", async () => ({ type: "api_key", key: "sk-test" })); + const modelRuntime = await ModelRuntime.create({ + credentials: authStorage, + modelsPath: join(agentDir, "models.json"), + }); + modelRuntime.registerProvider("hook-test", { + baseUrl: BASE, + api: "openai-completions", + models: [ + { + id: "hook-model", + name: "Hook model", + api: "openai-completions", + reasoning: false, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 32_000, + maxTokens: 1_000, + baseUrl: BASE, + }, + ], + }); + const model = modelRuntime.getModel("hook-test", "hook-model"); + expect(model).toBeDefined(); + const resourceLoader = new DefaultResourceLoader({ + cwd: tempDir, + agentDir, + settingsManager, + noSkills: true, + noPromptTemplates: true, + noThemes: true, + }); + await resourceLoader.reload(); + const { session } = await createAgentSession({ + cwd: tempDir, + agentDir, + model, + settingsManager, + sessionManager: SessionManager.inMemory(), + modelRuntime, + resourceLoader, + modelFetch, + }); + const unsubscribe = events ? session.subscribe((event) => events.push(event)) : undefined; + try { + await session.prompt("hello"); + return session.messages.at(-1) as AssistantMessage; + } finally { + unsubscribe?.(); + session.dispose(); + } + } + + /** + * A wrapper that, like a host holding a request before the provider answers, + * keeps the watchdog held for `HELD_WAIT_MS` and then sends to `server`. + */ + function heldThenSend( + server: (init: RequestInit | undefined) => Response | Promise, + seen: ModelFetchRequest[], + ): ModelFetchFactory { + return (request) => { + seen.push(request); + const fetch: ModelFetch = async (_input, init) => { + const release = request.holdIdleWatchdog(); + try { + await sleep(HELD_WAIT_MS); + } finally { + release(); + } + return server(init); + }; + return fetch; + }; + } + + it("routes every model request through the host fetch", async () => { + const seen: ModelFetchRequest[] = []; + const urls: string[] = []; + const last = await runPrompt((request) => { + seen.push(request); + return async (input, init) => { + urls.push(new Request(input, init).url); + return sse("wrapped answer"); + }; + }); + expect(last.stopReason).toBe("stop"); + expect(last.content).toEqual([{ type: "text", text: "wrapped answer" }]); + expect(seen).toHaveLength(1); + expect(seen[0]?.model.id).toBe("hook-model"); + expect(seen[0]?.signal.aborted).toBe(false); + expect(typeof seen[0]?.fetch).toBe("function"); + expect(urls).toEqual([`${BASE}/chat/completions`]); + }); + + it("leaves the request unchanged when the factory returns undefined", async () => { + const original = globalThis.fetch; + const urls: string[] = []; + globalThis.fetch = async (input, init) => { + urls.push(new Request(input, init).url); + return sse("plain answer"); + }; + try { + const last = await runPrompt(() => undefined); + expect(last.content).toEqual([{ type: "text", text: "plain answer" }]); + expect(urls).toEqual([`${BASE}/chat/completions`]); + } finally { + globalThis.fetch = original; + } + }); + + it("does not time out a request while the host holds the idle watchdog", async () => { + const seen: ModelFetchRequest[] = []; + const last = await runPrompt(heldThenSend(() => sse("held answer"), seen)); + expect(last.stopReason).toBe("stop"); + expect(last.content).toEqual([{ type: "text", text: "held answer" }]); + }); + + it("keeps the request under the idle bound once the hold is released", async () => { + const seen: ModelFetchRequest[] = []; + const last = await runPrompt(heldThenSend((init) => noAnswer(init?.signal), seen)); + expect(last.stopReason).toBe("error"); + expect(last.errorMessage).toMatch(/stream idle timeout/); + // The watchdog cancels through the signal the host was handed. + expect(seen[0]?.signal.aborted).toBe(true); + }); + + it("times out a held wait when the host never holds the watchdog", async () => { + const last = await runPrompt((request) => async () => { + await Promise.race([sleep(HELD_WAIT_MS), noAnswer(request.signal)]); + return sse("too late"); + }); + expect(last.stopReason).toBe("error"); + expect(last.errorMessage).toMatch(/stream idle timeout/); + }); + + it("publishes the wrapper's queue reports as model_queue session events", async () => { + const events: AgentSessionEvent[] = []; + const last = await runPrompt( + (request) => async () => { + request.reportQueue("call-1", { position: 2 }); + request.reportQueue("call-1", {}); + request.reportQueue("call-1", null); + return sse("reported"); + }, + events, + ); + expect(last.stopReason).toBe("stop"); + expect(events.filter((event) => event.type === "model_queue")).toEqual([ + { type: "model_queue", queueId: "call-1", queue: { position: 2 } }, + { type: "model_queue", queueId: "call-1", queue: {} }, + { type: "model_queue", queueId: "call-1", queue: null }, + ]); + }); +}); diff --git a/packages/coding-agent/test/print-mode.test.ts b/packages/coding-agent/test/print-mode.test.ts index e65684e19..5d3bd4b73 100644 --- a/packages/coding-agent/test/print-mode.test.ts +++ b/packages/coding-agent/test/print-mode.test.ts @@ -102,6 +102,13 @@ afterEach(() => { vi.restoreAllMocks(); }); +/** A stream `write` stand-in that completes like a real one, so flushes settle. */ +function capturedWrite(...args: unknown[]): boolean { + const done = args.find((arg): arg is (error?: Error | null) => void => typeof arg === "function"); + done?.(null); + return true; +} + describe("runPrintMode", () => { it("emits session_shutdown in text mode", async () => { const runtimeHost = createRuntimeHost(createAssistantMessage({ text: "done" })); @@ -152,6 +159,71 @@ describe("runPrintMode", () => { expect(session.extensionRunner.emit).toHaveBeenCalledWith({ type: "session_shutdown", reason: "quit" }); }); + it("reports each queue report on stderr in text mode in the host's wording, keeping stdout for the answer", async () => { + const run = async (formatModelQueue?: (queue: { position?: number }) => string) => { + const runtimeHost = createRuntimeHost(createAssistantMessage({ text: "done" })); + const { session } = runtimeHost; + const stderr = vi.spyOn(console, "error").mockImplementation(() => {}); + const stdout = vi.spyOn(process.stdout, "write").mockImplementation(capturedWrite); + session.prompt.mockImplementation(async () => { + // The wrapper reports changes only, so every report is a line. + for (const queue of [{ position: 2 }, { position: 1 }, null]) { + session.emitToListeners({ type: "model_queue", queueId: "q1", queue }); + } + }); + const exitCode = await runPrintMode(runtimeHost as unknown as Parameters[0], { + mode: "text", + initialMessage: "hello", + ...(formatModelQueue ? { formatModelQueue } : {}), + }); + const lines = { + exitCode, + stderr: stderr.mock.calls, + stdout: stdout.mock.calls.map(([chunk]) => String(chunk)).join(""), + }; + stderr.mockRestore(); + stdout.mockRestore(); + return lines; + }; + + const formatted = await run((queue) => `waiting at ${queue.position}`); + expect(formatted.exitCode).toBe(0); + expect(formatted.stderr).toEqual([["waiting at 2"], ["waiting at 1"]]); + expect(formatted.stdout).not.toContain("waiting at"); + // A host that supplies no wording gets no queue lines. + expect((await run()).stderr).toEqual([]); + }); + + it("writes queue reports to the JSON stream only with live events", async () => { + const run = async (includeLiveEvents: boolean) => { + const runtimeHost = createRuntimeHost(createAssistantMessage({ text: "done" })); + const { session } = runtimeHost; + const stdout = vi.spyOn(process.stdout, "write").mockImplementation(capturedWrite); + session.prompt.mockImplementation(async () => { + session.emitToListeners({ type: "model_queue", queueId: "r1", queue: { position: 3 } }); + session.emitToListeners({ type: "model_queue", queueId: "r1", queue: null }); + }); + await runPrintMode(runtimeHost as unknown as Parameters[0], { + mode: "json", + initialMessage: "hello", + includeLiveEvents, + }); + const lines = stdout.mock.calls + .map(([chunk]) => String(chunk)) + .join("") + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as { type: string }); + stdout.mockRestore(); + return lines.filter((line) => line.type === "model_queue"); + }; + expect(await run(false)).toEqual([]); + expect(await run(true)).toEqual([ + { type: "model_queue", queueId: "r1", queue: { position: 3 } }, + { type: "model_queue", queueId: "r1", queue: null }, + ]); + }); + // Feedback issue-d8b499026f19831c: with no UI, a denied tool call only reached // the model, so the run looked like it silently did nothing. it("reports a terminating tool block on stderr and exits non-zero", async () => { diff --git a/packages/coding-agent/test/request-teardowns.test.ts b/packages/coding-agent/test/request-teardowns.test.ts new file mode 100644 index 000000000..4224746ef --- /dev/null +++ b/packages/coding-agent/test/request-teardowns.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from "vitest"; +import { RequestTeardowns } from "../src/core/request-teardowns.ts"; + +describe("request teardowns", () => { + it("returns at once when nothing is registered", async () => { + const teardowns = new RequestTeardowns(); + const started = performance.now(); + await teardowns.settle(5_000); + expect(performance.now() - started).toBeLessThan(20); + }); + + it("waits for registered work", async () => { + const teardowns = new RequestTeardowns(); + let done = false; + teardowns.register( + new Promise((resolve) => + setTimeout(() => { + done = true; + resolve(); + }, 30), + ), + ); + await teardowns.settle(5_000); + expect(done).toBe(true); + }); + + it("gives up on hanging work at the limit, and a rejection is not an error", async () => { + const teardowns = new RequestTeardowns(); + teardowns.register(new Promise(() => {})); + teardowns.register(Promise.reject(new Error("unreachable"))); + const started = performance.now(); + await teardowns.settle(100); + const elapsed = performance.now() - started; + expect(elapsed).toBeGreaterThanOrEqual(90); + expect(elapsed).toBeLessThan(1_000); + }); + + it("forgets work once it settles", async () => { + const teardowns = new RequestTeardowns(); + teardowns.register(Promise.resolve()); + await new Promise((resolve) => setTimeout(resolve, 0)); + const started = performance.now(); + await teardowns.settle(5_000); + expect(performance.now() - started).toBeLessThan(20); + }); +}); diff --git a/packages/coding-agent/test/runtime-request-teardowns.test.ts b/packages/coding-agent/test/runtime-request-teardowns.test.ts new file mode 100644 index 000000000..381ee8ec8 --- /dev/null +++ b/packages/coding-agent/test/runtime-request-teardowns.test.ts @@ -0,0 +1,127 @@ +import { existsSync, mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fauxAssistantMessage, registerFauxProvider } from "@step-harness/providers/compat"; +import { afterEach, describe, expect, it } from "vitest"; +import { + type CreateAgentSessionRuntimeFactory, + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, +} from "../src/core/agent-session-runtime.ts"; +import { AuthStorage } from "../src/core/auth-storage.ts"; +import type { ModelFetchFactory } from "../src/core/model-fetch.ts"; +import { ModelRuntime } from "../src/core/model-runtime.ts"; +import { DEFAULT_REQUEST_TEARDOWN_LIMIT_MS } from "../src/core/request-teardowns.ts"; +import { getDefaultSessionDir, SessionManager } from "../src/core/session-manager.ts"; + +/** + * Disposing a runtime waits for the work its sessions' model requests still + * owe (registered through `ModelFetchRequest.registerTeardown`), with a bound, + * and does not wait at all when there is none. + */ +describe("runtime dispose and request teardowns", () => { + const cleanups: Array<() => Promise | void> = []; + + afterEach(async () => { + while (cleanups.length > 0) await cleanups.pop()?.(); + }); + + async function runtimeWith(modelFetch: ModelFetchFactory) { + const tempDir = join(tmpdir(), `pi-runtime-teardown-${Date.now()}-${Math.random().toString(36).slice(2)}`); + mkdirSync(tempDir, { recursive: true }); + const faux = registerFauxProvider(); + faux.setResponses([fauxAssistantMessage("one")]); + const authStorage = AuthStorage.inMemory(); + await authStorage.modify(faux.getModel().provider, async () => ({ type: "api_key", key: "faux-key" })); + const modelRuntime = await ModelRuntime.create({ + credentials: authStorage, + modelsPath: join(tempDir, "models.json"), + }); + const model = faux.getModel(); + modelRuntime.registerProvider(model.provider, { + baseUrl: model.baseUrl, + api: model.api, + models: [ + { + id: model.id, + name: model.name, + api: model.api, + reasoning: model.reasoning, + input: model.input, + cost: model.cost, + contextWindow: model.contextWindow, + maxTokens: model.maxTokens, + baseUrl: model.baseUrl, + }, + ], + }); + const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => { + const services = await createAgentSessionServices({ + cwd, + agentDir: tempDir, + modelRuntime, + resourceLoaderOptions: { noSkills: true, noPromptTemplates: true, noThemes: true }, + modelFetch, + }); + return { + ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent, model })), + services, + diagnostics: services.diagnostics, + }; + }; + const runtimeHost = await createAgentSessionRuntime(createRuntime, { + cwd: tempDir, + agentDir: tempDir, + sessionManager: SessionManager.create(tempDir, getDefaultSessionDir(tempDir, tempDir)), + }); + cleanups.push(() => { + faux.unregister(); + if (existsSync(tempDir)) rmSync(tempDir, { recursive: true, force: true }); + }); + return runtimeHost; + } + + it("waits for registered work, and no longer than the bound when it hangs", async () => { + let factoryCalls = 0; + const runtimeHost = await runtimeWith((request) => { + factoryCalls++; + // A teardown that never settles: a cancel request the server never answers. + request.registerTeardown(new Promise(() => {})); + return undefined; + }); + await runtimeHost.session.prompt("hello"); + expect(factoryCalls).toBeGreaterThan(0); + const started = performance.now(); + await runtimeHost.dispose(); + const elapsed = performance.now() - started; + expect(elapsed).toBeGreaterThanOrEqual(DEFAULT_REQUEST_TEARDOWN_LIMIT_MS - 50); + expect(elapsed).toBeLessThan(DEFAULT_REQUEST_TEARDOWN_LIMIT_MS + 1_000); + }); + + it("waits for work that settles, and only that long", async () => { + let settledAt = 0; + const runtimeHost = await runtimeWith((request) => { + request.registerTeardown( + new Promise((resolve) => + setTimeout(() => { + settledAt = performance.now(); + resolve(); + }, 100), + ), + ); + return undefined; + }); + await runtimeHost.session.prompt("hello"); + await runtimeHost.dispose(); + expect(settledAt).toBeGreaterThan(0); + }); + + it("does not wait when nothing was registered", async () => { + const runtimeHost = await runtimeWith(() => undefined); + await runtimeHost.session.prompt("hello"); + const started = performance.now(); + await runtimeHost.dispose(); + expect(performance.now() - started).toBeLessThan(500); + }); +}); diff --git a/packages/coding-agent/test/step-endpoint-class.test.ts b/packages/coding-agent/test/step-endpoint-class.test.ts new file mode 100644 index 000000000..b6d7181e2 --- /dev/null +++ b/packages/coding-agent/test/step-endpoint-class.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { classifyStepEndpoint } from "../src/step/telemetry-contract.ts"; + +describe("telemetry endpoint classes", () => { + it("keeps every platform endpoint it recognized from the environment", () => { + const env = { + STEP_BASE_URL: "https://one.example.test/step_plan, https://two.example.test/step_plan", + STEP_MODELS_PROXY_BASE_URL: "https://proxy.example.test", + STEPFUN_MESSAGES_ENDPOINT: "https://legacy.example.test/v1/messages", + }; + for (const url of [ + "https://api.stepfun.com/step_plan/v1", + "https://one.example.test/v1", + "https://two.example.test/v1", + "https://proxy.example.test/v1/chat/completions", + "https://legacy.example.test/v1/messages", + ]) { + expect(classifyStepEndpoint(url, env), url).toBe("platform"); + } + }); + + it("keeps local and custom endpoints apart from the platform", () => { + expect(classifyStepEndpoint("http://localhost:8080/v1", {})).toBe("local"); + expect(classifyStepEndpoint("http://127.0.0.1:8080/v1", {})).toBe("local"); + expect(classifyStepEndpoint("https://gateway.example.test/v1", {})).toBe("custom"); + expect(classifyStepEndpoint("not a url", {})).toBe("custom"); + }); +}); diff --git a/packages/coding-agent/test/step-environment.test.ts b/packages/coding-agent/test/step-environment.test.ts index 4fb2571f9..6ddcf1e38 100644 --- a/packages/coding-agent/test/step-environment.test.ts +++ b/packages/coding-agent/test/step-environment.test.ts @@ -11,10 +11,10 @@ describe("Step early environment", () => { expect(getStepDefaultTheme(env)).toBe("step-blue"); }); - test("defaults the downstream client marker to stepcode, honoring an explicit value", () => { + test("defaults the downstream client marker to stepcode-cli, honoring an explicit value", () => { const fresh: NodeJS.ProcessEnv = {}; applyStepEnvironment(fresh); - expect(fresh.STEP_CLIENT).toBe("stepcode"); + expect(fresh.STEP_CLIENT).toBe("stepcode-cli"); const explicit: NodeJS.ProcessEnv = { STEP_CLIENT: "embedding-host" }; applyStepEnvironment(explicit); @@ -22,7 +22,7 @@ describe("Step early environment", () => { const blank: NodeJS.ProcessEnv = { STEP_CLIENT: " " }; applyStepEnvironment(blank); - expect(blank.STEP_CLIENT).toBe("stepcode"); + expect(blank.STEP_CLIENT).toBe("stepcode-cli"); }); test("recognizes source, bundled, and binary launchers", () => { diff --git a/packages/coding-agent/test/step-extension.test.ts b/packages/coding-agent/test/step-extension.test.ts index b2d983392..89788f1ba 100644 --- a/packages/coding-agent/test/step-extension.test.ts +++ b/packages/coding-agent/test/step-extension.test.ts @@ -847,7 +847,7 @@ describe("Step extension", () => { // The native Step endpoint is a direct model API, not the cloud-trace // collector. Keep session/workspace identifiers off custom or direct // provider requests; only the low-sensitivity client marker is universal. - expect(headers).toEqual({ "x-step-client": "cli" }); + expect(headers).toEqual({ "x-step-client": "stepcode-cli" }); const originalOrigin = process.env.STEPCODE_CLOUD_TRACE_ORIGIN; process.env.STEPCODE_CLOUD_TRACE_ORIGIN = "https://trace.example.test/v1"; @@ -863,7 +863,7 @@ describe("Step extension", () => { sessionManager: { getSessionId: () => "session-2" }, } as unknown as Pick); expect(otherHeaders).toMatchObject({ - "x-step-client": "cli", + "x-step-client": "stepcode-cli", "x-step-session-id": "session-2", "x-step-workspace-id": "/workspace", "x-step-provider-id": "stepfunModelProxy", diff --git a/packages/coding-agent/test/step-model-queue-session.test.ts b/packages/coding-agent/test/step-model-queue-session.test.ts new file mode 100644 index 000000000..c9b30e46a --- /dev/null +++ b/packages/coding-agent/test/step-model-queue-session.test.ts @@ -0,0 +1,235 @@ +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { AssistantMessage } from "@step-harness/providers"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { AgentSessionEvent } from "../src/core/agent-session.ts"; +import { AuthStorage } from "../src/core/auth-storage.ts"; +import { ModelRuntime } from "../src/core/model-runtime.ts"; +import { SessionManager } from "../src/core/session-manager.ts"; +import { resolveStepModelQueueEnabled } from "../src/step/model-queue.ts"; +import { createStepAgentSession } from "../src/step/sdk.ts"; +import { createStepSettingsManager } from "../src/step/settings-manager.ts"; + +/** The Step Plan endpoint the product ships; requests never leave the process (fetch is stubbed). */ +const STEP_PLAN = "https://api.stepfun.com/step_plan/v1"; + +const dirs: string[] = []; + +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function fixture(globalToml: string, projectToml?: string) { + const root = join(tmpdir(), `pi-step-queue-${Date.now()}-${Math.random().toString(36).slice(2)}`); + dirs.push(root); + const cwd = join(root, "project"); + mkdirSync(join(cwd, ".stepcode"), { recursive: true }); + const paths = { global: join(root, "config.toml"), project: join(cwd, ".stepcode", "config.toml") }; + writeFileSync(paths.global, globalToml); + if (projectToml !== undefined) writeFileSync(paths.project, projectToml); + return { root, cwd, paths }; +} + +function sse(text: string): Response { + const chunk = (body: Record) => + `data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "queue-model", ...body })}\n\n`; + return new Response( + chunk({ choices: [{ index: 0, delta: { role: "assistant", content: text }, finish_reason: null }] }) + + chunk({ + choices: [{ index: 0, delta: {}, finish_reason: "stop" }], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }) + + "data: [DONE]\n\n", + { status: 200, headers: { "content-type": "text/event-stream" } }, + ); +} + +describe("model_queue setting", () => { + it("reads model_queue globally, lets a trusted project override it, and ignores an untrusted one", () => { + const { cwd, paths } = fixture("model_queue = true\n", "model_queue = false\n"); + const trusted = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: true }); + expect(trusted.getStepSettings().modelQueue).toBe(false); + expect(resolveStepModelQueueEnabled({ env: {}, settings: trusted.getStepSettings() })).toEqual({ + enabled: false, + source: "settings", + }); + const untrusted = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: false }); + expect(untrusted.getStepSettings().modelQueue).toBe(true); + // Unset everywhere: the queue is on. + const unset = fixture(""); + const plain = createStepSettingsManager(unset.cwd, undefined, { paths: unset.paths, projectTrusted: true }); + expect(plain.getStepSettings().modelQueue).toBeUndefined(); + expect(resolveStepModelQueueEnabled({ env: {}, settings: plain.getStepSettings() })).toEqual({ + enabled: true, + source: "default", + }); + // The flat spelling is the same switch. + const flat = fixture("modelQueue = true\n"); + const flatSettings = createStepSettingsManager(flat.cwd, undefined, { paths: flat.paths, projectTrusted: true }); + expect(flatSettings.getStepSettings().modelQueue).toBe(true); + }); + + it("persists the switch and rejects a non-boolean value", () => { + const { cwd, paths } = fixture(""); + const settings = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: true }); + settings.setStepSettings({ modelQueue: true }); + const reread = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: true }); + expect(reread.getStepSettings().modelQueue).toBe(true); + expect(() => settings.setStepSettings({ modelQueue: "yes" as unknown as boolean })).toThrow(/modelQueue/); + }); + + it("ignores a non-boolean value with a settings warning", () => { + const { cwd, paths } = fixture('model_queue = "yes"\n'); + const settings = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: true }); + expect(settings.getStepSettings().modelQueue).toBeUndefined(); + const messages = settings.drainErrors().map((entry) => entry.error.message); + expect(messages).toContain('model_queue must be true or false; ignoring "yes"'); + }); +}); + +describe("Step sessions install the queue", () => { + async function prompt(globalToml: string, server: typeof globalThis.fetch) { + const { root, cwd, paths } = fixture(globalToml); + const agentDir = join(root, "agent"); + mkdirSync(agentDir, { recursive: true }); + vi.stubGlobal("fetch", server); + const authStorage = AuthStorage.inMemory(); + await authStorage.modify("step", async () => ({ type: "api_key", key: "sk-test" })); + const modelRuntime = await ModelRuntime.create({ + credentials: authStorage, + modelsPath: join(agentDir, "models.json"), + }); + // The official Step provider id, at a stubbed endpoint. + modelRuntime.registerProvider("step", { + baseUrl: STEP_PLAN, + api: "openai-completions", + models: [ + { + id: "queue-model", + name: "Queue model", + api: "openai-completions", + reasoning: false, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 32_000, + maxTokens: 1_000, + baseUrl: STEP_PLAN, + }, + ], + }); + const settingsManager = createStepSettingsManager(cwd, agentDir, { paths, projectTrusted: true }); + // Session retries stay on: a closed place must not be retried by the session or the SDK. + settingsManager.applyOverrides({ retry: { enabled: true, maxRetries: 2, baseDelayMs: 1 } }); + const { session } = await createStepAgentSession({ + cwd, + agentDir, + model: modelRuntime.getModel("step", "queue-model"), + settingsManager, + sessionManager: SessionManager.inMemory(), + modelRuntime, + }); + const events: AgentSessionEvent[] = []; + const unsubscribe = session.subscribe((event) => events.push(event)); + try { + await session.prompt("hello"); + return { last: session.messages.at(-1) as AssistantMessage, events }; + } finally { + unsubscribe(); + session.dispose(); + } + } + + const queuedAnswer = (position: number) => + new Response("{}", { + status: 429, + headers: { + "X-StepCode-Queue-State": "waiting", + "X-StepCode-Queue-Position": String(position), + "Retry-After-Ms": "20", + }, + }); + + it("queues a request to Step's host when the setting turns the queue on", async () => { + vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); + const calls: Array<{ method: string; url: string; id: string | null }> = []; + const replies = [ + () => queuedAnswer(2), + () => Response.json({ state: "ready", position: 0, retry_after_ms: 20, reason: "" }), + () => sse("after the line"), + ]; + const { last, events } = await prompt("model_queue = true\n", async (input, init) => { + const request = new Request(input, init); + calls.push({ method: request.method, url: request.url, id: request.headers.get("X-StepCode-Queue-ID") }); + const reply = replies.shift(); + if (!reply) throw new Error(`unexpected ${request.method} ${request.url}`); + return reply(); + }); + expect(last.content).toEqual([{ type: "text", text: "after the line" }]); + expect(calls.map((call) => call.method)).toEqual(["POST", "GET", "POST"]); + expect(calls[0]?.id).toMatch(/^[0-9a-f-]{36}$/u); + expect(calls[1]?.url).toBe("https://api.stepfun.com/stepcode/v1/queue"); + expect(calls[1]?.id).toBe(calls[0]?.id); + expect(calls[2]?.id).toBe(calls[0]?.id); + expect(events.filter((event) => event.type === "model_queue").map((event) => event.queue)).toEqual([ + { position: 2 }, + null, + ]); + }); + + it("queues by default, with no setting and no environment override", async () => { + vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); + const calls: string[] = []; + const replies = [ + () => queuedAnswer(1), + () => Response.json({ state: "ready", position: 0, retry_after_ms: 20, reason: "" }), + () => sse("by default"), + ]; + const { last } = await prompt("", async (input, init) => { + const request = new Request(input, init); + calls.push(`${request.method} ${new URL(request.url).pathname}`); + const reply = replies.shift(); + if (!reply) throw new Error(`unexpected ${request.method} ${request.url}`); + return reply(); + }); + expect(last.content).toEqual([{ type: "text", text: "by default" }]); + expect(calls).toEqual([ + "POST /step_plan/v1/chat/completions", + "GET /stepcode/v1/queue", + "POST /step_plan/v1/chat/completions", + ]); + }); + + it("leaves the request alone when the queue is off", async () => { + vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); + const ids: Array = []; + const { last } = await prompt("model_queue = false\n", async (input, init) => { + ids.push(new Request(input, init).headers.get("X-StepCode-Queue-ID")); + return sse("direct"); + }); + expect(last.content).toEqual([{ type: "text", text: "direct" }]); + expect(ids).toEqual([null]); + }); + + it("ends a closed place with one readable error that neither the SDK nor the session retries", async () => { + vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); + const calls: string[] = []; + const { last, events } = await prompt("model_queue = true\n", async (input, init) => { + const request = new Request(input, init); + calls.push(`${request.method} ${new URL(request.url).pathname}`); + if (request.method === "GET") + return Response.json({ state: "closed", position: 0, retry_after_ms: 20, reason: "queue_full" }); + return queuedAnswer(9); + }); + expect(calls).toEqual(["POST /step_plan/v1/chat/completions", "GET /stepcode/v1/queue"]); + expect(last.stopReason).toBe("error"); + expect(last.errorMessage).toContain("The request queue is full. Try again later. (queue_full)"); + expect(events.filter((event) => event.type === "auto_retry_start")).toEqual([]); + expect(events.filter((event) => event.type === "model_queue").at(-1)).toMatchObject({ + queue: null, + closedReason: "queue_full", + }); + }); +}); diff --git a/packages/coding-agent/test/step-model-queue.test.ts b/packages/coding-agent/test/step-model-queue.test.ts new file mode 100644 index 000000000..68761eaac --- /dev/null +++ b/packages/coding-agent/test/step-model-queue.test.ts @@ -0,0 +1,772 @@ +import assert from "node:assert/strict"; +import { test } from "vitest"; +import type { ModelFetchRequest, ModelQueueExit, ModelQueueState } from "../src/core/model-fetch.ts"; +import { + createStepModelQueueFactory, + createStepModelQueueFetch, + resolveStepModelQueueEnabled, + stepModelQueueClosedMessage, + stepModelQueueStatusText, +} from "../src/step/model-queue.ts"; + +const PLAN = "https://api.example.test/step_plan/v1"; +const CHAT = `${PLAN}/chat/completions`; +/** Stand-ins for the fixed endpoints, injected through the test hook: mainland on `.test`, overseas on `.ai`. */ +const QUEUE = "https://api.example.test/stepcode/v1/queue"; +const QUEUE_OVERSEAS = "https://api.example.ai/stepcode/v1/queue"; +const QUEUE_ENDPOINTS = { "api.example.test": QUEUE, "api.example.ai": QUEUE_OVERSEAS }; +const BODY = JSON.stringify({ model: "step", messages: [{ role: "user", content: "你好 🌏" }], stream: true }); + +interface Call { + readonly url: string; + readonly method: string; + readonly headers: Headers; + readonly body?: Uint8Array; + readonly signal?: AbortSignal; + /** Whether the idle watchdog was held when the request went out. */ + readonly held: boolean; +} + +type Reply = Response | Error | ((call: Call) => Response | Promise); + +function queued(position?: number, retryAfterMs?: number): Response { + const headers = new Headers({ "X-StepCode-Queue-State": "waiting", "content-type": "application/json" }); + if (position !== undefined) headers.set("X-StepCode-Queue-Position", String(position)); + if (retryAfterMs !== undefined) headers.set("Retry-After-Ms", String(retryAfterMs)); + return new Response(JSON.stringify({ error: { type: "queued", code: "queued" } }), { status: 429, headers }); +} + +function status(state: string, extra: Record = {}): Response { + return new Response(JSON.stringify({ state, position: 0, retry_after_ms: 2000, reason: "", ...extra }), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +const ok = () => new Response("data: [DONE]\n\n", { status: 200, headers: { "content-type": "text/event-stream" } }); + +function harness(replies: Reply[], options: { budgetMs?: number } = {}) { + const calls: Call[] = []; + const sleeps: number[] = []; + const states: Array = []; + const exits: Array = []; + const teardowns: Array> = []; + const caller = new AbortController(); + let holds = 0; + let released = 0; + let clock = 0; + const fetch: typeof globalThis.fetch = async (input, init) => { + const request = new Request(input, init); + const call: Call = { + url: request.url, + method: request.method, + headers: new Headers(request.headers), + ...(request.body ? { body: new Uint8Array(await request.arrayBuffer()) } : {}), + ...(init?.signal ? { signal: init.signal } : {}), + held: holds > released, + }; + calls.push(call); + const reply = replies.shift(); + if (!reply) throw new Error(`unexpected request ${call.method} ${call.url}`); + if (reply instanceof Error) throw reply; + return typeof reply === "function" ? reply(call) : reply; + }; + const wrapped = createStepModelQueueFetch( + { + signal: caller.signal, + fetch, + reportQueue: (queueId, state, exit) => { + assert.equal(queueId, "q-1"); + states.push(state); + if (state === null) exits.push(exit); + }, + registerTeardown: (task) => teardowns.push(task), + holdIdleWatchdog: () => { + holds++; + let done = false; + return () => { + if (done) throw new Error("released twice"); + done = true; + released++; + }; + }, + }, + { + queueId: () => "q-1", + queueEndpoints: QUEUE_ENDPOINTS, + now: () => clock, + sleep: async (ms, signal) => { + signal.throwIfAborted(); + sleeps.push(ms); + clock += ms; + }, + ...(options.budgetMs === undefined ? {} : { pollFailureBudgetMs: options.budgetMs }), + }, + ); + const fetchRequest = (input: Request) => wrapped(input); + const post = (url = CHAT, init: RequestInit = {}) => + wrapped(url, { + method: "POST", + headers: { authorization: "Bearer sk-test", "content-type": "application/json" }, + body: BODY, + ...init, + }); + return { + calls, + sleeps, + states, + exits, + teardowns, + caller, + post, + fetchRequest, + holds: () => holds, + released: () => released, + }; +} + +const text = (bytes: Uint8Array | undefined) => new TextDecoder().decode(bytes); + +/** The cancel: `POST /cancel` with the request's credentials, naming the place by its queue id header, no body. */ +function assertCancel(call: Call | undefined): void { + assert.equal(call?.method, "POST"); + assert.equal(call?.url, `${QUEUE}/cancel`); + assert.equal(call?.headers.get("authorization"), "Bearer sk-test"); + assert.equal(call?.headers.get("X-StepCode-Queue-ID"), "q-1"); + assert.equal(call?.headers.has("content-type"), false); + assert.equal(call?.body, undefined); +} + +test("tags each Step model call with a queue id and passes the answer through", async () => { + const h = harness([ok()]); + const response = await h.post(); + assert.equal(response.status, 200); + assert.equal(h.calls.length, 1); + assert.equal(h.calls[0]?.headers.get("X-StepCode-Queue-ID"), "q-1"); + assert.equal(text(h.calls[0]?.body), BODY); + assert.deepEqual(h.states, []); + assert.equal(h.holds(), 0); +}); + +test("generates a fresh id per call", async () => { + const ids: string[] = []; + const fetch: typeof globalThis.fetch = async (input, init) => { + ids.push(new Request(input, init).headers.get("X-StepCode-Queue-ID") ?? ""); + return ok(); + }; + const wrapped = createStepModelQueueFetch( + { + signal: new AbortController().signal, + fetch, + holdIdleWatchdog: () => () => {}, + reportQueue: () => {}, + registerTeardown: () => {}, + }, + { queueEndpoints: QUEUE_ENDPOINTS }, + ); + await wrapped(CHAT, { method: "POST", body: BODY }); + await wrapped(CHAT, { method: "POST", body: BODY }); + assert.equal(ids.length, 2); + assert.match(ids[0], /^[0-9a-f-]{36}$/u); + assert.notEqual(ids[0], ids[1]); +}); + +test("tags every request to a Step API host, whatever its route; the server decides whether it waits", async () => { + const h = harness([ok(), ok(), ok()]); + await h.post("https://api.example.test/v1/chat/completions"); + await h.post(`${PLAN}/messages`); + await h.post(`${PLAN}/models`, { method: "GET", body: null }); + assert.deepEqual( + h.calls.map((call) => call.headers.has("X-StepCode-Queue-ID")), + [true, true, true], + ); +}); + +test("picks the queue of the request's region", async () => { + const mainland = harness([queued(1), status("ready"), ok()]); + await mainland.post("https://api.example.test/v1/chat/completions"); + assert.equal(mainland.calls[1]?.url, QUEUE); + const overseas = harness([queued(1), status("ready"), ok()]); + await overseas.post("https://api.example.ai/step_plan/v1/chat/completions"); + assert.equal(overseas.calls[1]?.url, QUEUE_OVERSEAS); +}); + +test("sends a request to any other host as it is: no header, no queue", async () => { + const h = harness([queued(1)]); + // An endpoint override, or a gateway: even a queued-looking answer is the caller's. + const response = await h.post("https://gateway.example.test/step_plan/v1/chat/completions"); + assert.equal(response.status, 429); + assert.equal(h.calls.length, 1); + assert.equal(h.calls[0]?.headers.has("X-StepCode-Queue-ID"), false); + assert.deepEqual(h.states, []); +}); + +test("knows Step's own two API hosts by default", async () => { + const seen: string[] = []; + const replies = [queued(1), status("ready"), ok(), queued(1), status("ready"), ok(), ok()]; + const wrapped = createStepModelQueueFetch( + { + signal: new AbortController().signal, + fetch: async (input, init) => { + const request = new Request(input, init); + seen.push(`${request.headers.get("X-StepCode-Queue-ID") ?? "plain"} ${request.method} ${request.url}`); + return replies.shift() ?? ok(); + }, + holdIdleWatchdog: () => () => {}, + reportQueue: () => {}, + registerTeardown: () => {}, + }, + { queueId: () => "id", sleep: async () => {} }, + ); + await wrapped("https://api.stepfun.com/step_plan/v1/chat/completions", { method: "POST", body: BODY }); + await wrapped("https://api.stepfun.ai/v1/chat/completions", { method: "POST", body: BODY }); + await wrapped("https://staging.example.test/step_plan/v1/chat/completions", { method: "POST", body: BODY }); + assert.deepEqual(seen, [ + "id POST https://api.stepfun.com/step_plan/v1/chat/completions", + "id GET https://api.stepfun.com/stepcode/v1/queue", + "id POST https://api.stepfun.com/step_plan/v1/chat/completions", + "id POST https://api.stepfun.ai/v1/chat/completions", + "id GET https://api.stepfun.ai/stepcode/v1/queue", + "id POST https://api.stepfun.ai/v1/chat/completions", + "plain POST https://staging.example.test/step_plan/v1/chat/completions", + ]); +}); + +test("never wraps the queue control endpoints: they go out as they are", async () => { + const h = harness([ok(), queued(1)]); + await h.post(QUEUE, { method: "GET", body: null, headers: { "X-StepCode-Queue-ID": "other" } }); + const response = await h.post(`${QUEUE}/cancel`, { body: null, headers: { "X-StepCode-Queue-ID": "other" } }); + // Not wrapped: a queued-looking answer to a control request is not a place in line. + assert.equal(response.status, 429); + // The id they name is their own, never replaced by a fresh one. + assert.deepEqual( + h.calls.map((call) => call.headers.get("X-StepCode-Queue-ID")), + ["other", "other"], + ); + assert.deepEqual(h.states, []); + assert.equal(h.holds(), 0); +}); + +test("forwards the request's own headers to the control requests, except those describing its body", async () => { + const h = harness([queued(1), status("ready"), ok()]); + await h.post(CHAT, { + headers: { + authorization: "Bearer sk-test", + "x-api-key": "k", + "x-step-session-id": "s1", + "content-type": "application/json", + "content-length": String(BODY.length), + }, + }); + const poll = h.calls[1]; + assert.equal(poll?.headers.get("authorization"), "Bearer sk-test"); + assert.equal(poll?.headers.get("x-api-key"), "k"); + assert.equal(poll?.headers.get("x-step-session-id"), "s1"); + assert.equal(poll?.headers.get("accept"), "application/json"); + assert.equal(poll?.headers.has("content-type"), false); + assert.equal(poll?.headers.has("content-length"), false); + // The control requests name the place they ask about. + assert.equal(poll?.headers.get("X-StepCode-Queue-ID"), "q-1"); +}); + +test("passes a non-queued answer through unchanged", async () => { + const answer = new Response('{"error":"bad"}', { status: 400, headers: { "content-type": "application/json" } }); + const h = harness([answer]); + const response = await h.post(); + assert.equal(response, answer); + assert.equal(h.holds(), 0); + assert.deepEqual(h.states, []); +}); + +test("passes an ordinary 429 through to the existing retry policy", async () => { + const h = harness([new Response("{}", { status: 429, headers: { "retry-after": "1" } })]); + const response = await h.post(); + assert.equal(response.status, 429); + assert.equal(h.calls.length, 1); + assert.deepEqual(h.states, []); +}); + +test("waits in line, then resends the same bytes under the same id", async () => { + const h = harness([ + queued(3, 1500), + status("waiting", { position: 2, retry_after_ms: 1000 }), + status("waiting", { position: 1 }), + status("ready"), + ok(), + ]); + const response = await h.post(); + assert.equal(response.status, 200); + assert.deepEqual( + h.calls.map((call) => call.method), + ["POST", "GET", "GET", "GET", "POST"], + ); + for (const poll of h.calls.slice(1, 4)) { + // No query: the place is named by its queue id header. + assert.equal(poll.url, QUEUE); + assert.equal(poll.headers.get("X-StepCode-Queue-ID"), "q-1"); + assert.equal(poll.headers.get("authorization"), "Bearer sk-test"); + assert.equal(poll.body, undefined); + } + const [first, resend] = [h.calls[0], h.calls[4]]; + assert.equal(resend?.headers.get("X-StepCode-Queue-ID"), "q-1"); + assert.equal(resend?.url, CHAT); + assert.deepEqual(resend?.body, first?.body); + assert.equal(text(resend?.body), BODY); + assert.deepEqual(h.sleeps, [1500, 1000, 2000]); + assert.deepEqual(h.states, [{ position: 3 }, { position: 2 }, { position: 1 }, null]); + assert.deepEqual(h.exits, [undefined]); + assert.deepEqual([h.holds(), h.released()], [1, 1]); + // Held only while polling; the resend is back under the idle bound. + assert.deepEqual( + h.calls.map((call) => call.held), + [false, true, true, true, false], + ); +}); + +test("sends the queue id as it is, in a header, never in the URL", async () => { + const calls: Array<{ url: string; id: string | null }> = []; + const replies = [queued(1), status("ready"), ok()]; + const wrapped = createStepModelQueueFetch( + { + signal: new AbortController().signal, + fetch: async (input, init) => { + const request = new Request(input, init); + calls.push({ url: request.url, id: request.headers.get("X-StepCode-Queue-ID") }); + return replies.shift() ?? ok(); + }, + holdIdleWatchdog: () => () => {}, + reportQueue: () => {}, + registerTeardown: () => {}, + }, + { queueId: () => "a b&c", sleep: async () => {}, queueEndpoints: QUEUE_ENDPOINTS }, + ); + await wrapped(CHAT, { method: "POST", body: BODY }); + assert.deepEqual(calls[1], { url: QUEUE, id: "a b&c" }); +}); + +test("keeps polling when the resend is queued again", async () => { + const h = harness([ + queued(2), + status("ready"), + queued(4, 500), + status("waiting", { position: 1 }), + status("ready"), + ok(), + ]); + const response = await h.post(); + assert.equal(response.status, 200); + const posts = h.calls.filter((call) => call.method === "POST"); + assert.equal(posts.length, 3); + assert.deepEqual(new Set(posts.map((call) => call.headers.get("X-StepCode-Queue-ID"))), new Set(["q-1"])); + assert.deepEqual(new Set(posts.map((call) => text(call.body))), new Set([BODY])); + assert.deepEqual(h.states, [{ position: 2 }, { position: 4 }, { position: 1 }, null]); + assert.deepEqual(h.sleeps, [2000, 500, 2000]); + // Released before each resend, held again when the resend is queued. + assert.deepEqual( + h.calls.map((call) => `${call.method}:${call.held}`), + ["POST:false", "GET:true", "POST:false", "GET:true", "GET:true", "POST:false"], + ); + assert.deepEqual([h.holds(), h.released()], [2, 2]); +}); + +test("releases the hold once when the caller stops during a resend", async () => { + const h = harness([ + queued(1), + status("ready"), + (call) => + new Promise((_resolve, reject) => { + assert.equal(call.held, false); + call.signal?.addEventListener("abort", () => reject(call.signal?.reason), { once: true }); + h.caller.abort(new DOMException("stop", "AbortError")); + }), + new Response(null, { status: 204 }), + ]); + await assert.rejects(h.post(), { name: "AbortError" }); + assertCancel(h.calls.at(-1)); + assert.deepEqual([h.holds(), h.released()], [1, 1]); + assert.equal(h.states.at(-1), null); +}); + +test("ends with a non-retryable, readable error that keeps the reason code when the place is closed", async () => { + const h = harness([queued(5), status("closed", { reason: "max_wait_exceeded" })]); + const response = await h.post(); + assert.equal(response.status, 410); + assert.equal(response.headers.get("x-should-retry"), "false"); + const body = (await response.json()) as { error: { message: string; code: string; reason: string } }; + assert.equal(body.error.message, "The request waited in line too long. Try again later. (max_wait_exceeded)"); + assert.equal(body.error.code, "queue_closed"); + assert.equal(body.error.reason, "max_wait_exceeded"); + assert.equal(h.states.at(-1), null); + // The reason code reaches the host, for its own wording. + assert.deepEqual(h.exits, [{ closedReason: "max_wait_exceeded" }]); + assert.equal(h.released(), 1); +}); + +test("a status answer of 404 closes the place as not_found", async () => { + const h = harness([queued(1), new Response("gone", { status: 404 })]); + const response = await h.post(); + assert.equal(response.status, 410); + const body = (await response.json()) as { error: { reason: string } }; + assert.equal(body.error.reason, "not_found"); + assert.deepEqual(h.exits, [{ closedReason: "not_found" }]); +}); + +test("a status answer of 401 or 403 goes back to the caller as it is", async () => { + for (const status of [401, 403]) { + const denied = new Response('{"error":"unauthorized"}', { status }); + const h = harness([queued(1), denied]); + const response = await h.post(); + assert.equal(response, denied); + assert.equal(h.states.at(-1), null); + assert.equal(h.released(), 1); + } +}); + +test("a throttled status endpoint is retried like a failing one", async () => { + const h = harness([queued(1), new Response("slow down", { status: 429 }), status("ready"), ok()]); + const response = await h.post(); + assert.equal(response.status, 200); + assert.deepEqual(h.sleeps, [2000, 1000]); +}); + +test("reports only changes of place or of being in line", async () => { + const h = harness([ + queued(2), + status("waiting", { position: 2 }), + status("waiting", { position: 2 }), + status("waiting", { position: 1 }), + status("ready"), + ok(), + ]); + await h.post(); + assert.deepEqual(h.states, [{ position: 2 }, { position: 1 }, null]); +}); + +test("names every closed reason code in readable text, generic for unknown codes", () => { + const codes = ["queue_full", "user_limit", "lease_expired", "max_wait_exceeded", "not_found"]; + const generic = stepModelQueueClosedMessage(""); + const texts = codes.map((code) => stepModelQueueClosedMessage(code)); + for (const [index, text] of texts.entries()) { + assert.equal(text.endsWith(` (${codes[index]})`), true); + assert.equal(text.startsWith(generic), false); + } + assert.equal(new Set(texts).size, codes.length); + assert.equal(stepModelQueueClosedMessage("brand_new_reason"), `${generic} (brand_new_reason)`); + assert.equal(stepModelQueueClosedMessage("toString"), `${generic} (toString)`); + assert.equal(stepModelQueueClosedMessage("queue_full"), "The request queue is full. Try again later. (queue_full)"); +}); + +test("a stop always surfaces as an Error", async () => { + const h = harness([ + queued(1), + () => { + h.caller.abort("user pressed stop"); + return status("waiting", { position: 1 }); + }, + new Response(null, { status: 204 }), + ]); + const error = await h.post().then( + () => undefined, + (caught: unknown) => caught, + ); + assert.ok(error instanceof Error); + assert.equal((error as Error).name, "AbortError"); +}); + +test("sends no cancel when the caller stops during the first send: nothing said the call was queued", async () => { + const h = harness([ + (call) => + new Promise((_resolve, reject) => { + call.signal?.addEventListener("abort", () => reject(call.signal?.reason), { once: true }); + h.caller.abort(new DOMException("stop", "AbortError")); + }), + ]); + const attempt = new AbortController(); + h.caller.signal.addEventListener("abort", () => attempt.abort(h.caller.signal.reason), { once: true }); + await assert.rejects(h.post(CHAT, { signal: attempt.signal }), { name: "AbortError" }); + // The model request alone: no cancel, no teardown for a disposing session to wait on. + assert.deepEqual( + h.calls.map((call) => `${call.method} ${call.url}`), + [`POST ${CHAT}`], + ); + assert.deepEqual(h.teardowns, []); + assert.equal(h.holds(), 0); + assert.deepEqual(h.states, []); +}); + +test("a Request input's own signal stops the first send", async () => { + const stop = new AbortController(); + const h = harness([ + (call) => + new Promise((_resolve, reject) => { + assert.ok(call.signal); + call.signal.addEventListener("abort", () => reject(call.signal?.reason), { once: true }); + stop.abort(new DOMException("stop", "AbortError")); + }), + ]); + const input = new Request(CHAT, { + method: "POST", + headers: { authorization: "Bearer sk-test", "content-type": "application/json" }, + body: BODY, + signal: stop.signal, + }); + await assert.rejects(h.fetchRequest(input), { name: "AbortError" }); + assert.equal(h.calls.length, 1); + assert.deepEqual(h.teardowns, []); +}); + +test("a Request input's own signal also reaches the resend", async () => { + const stop = new AbortController(); + const h = harness([ + queued(1), + status("ready"), + (call) => + new Promise((_resolve, reject) => { + assert.ok(call.signal); + call.signal.addEventListener("abort", () => reject(call.signal?.reason), { once: true }); + stop.abort(new DOMException("stop", "AbortError")); + }), + ]); + const input = new Request(CHAT, { + method: "POST", + headers: { authorization: "Bearer sk-test", "content-type": "application/json" }, + body: BODY, + signal: stop.signal, + }); + await assert.rejects(h.fetchRequest(input), { name: "AbortError" }); + assert.deepEqual( + h.calls.map((call) => call.method), + ["POST", "GET", "POST"], + ); + assert.equal(h.released(), 1); + assert.equal(h.states.at(-1), null); +}); + +test("does not leave the line when the first send fails without a stop", async () => { + const h = harness([new TypeError("fetch failed")]); + await assert.rejects(h.post(), { message: "fetch failed" }); + assert.deepEqual( + h.calls.map((call) => call.method), + ["POST"], + ); +}); + +test("backs off on poll failures without changing the id", async () => { + const h = harness([ + queued(1), + new TypeError("fetch failed"), + new Response("busy", { status: 503 }), + status("waiting", { position: 1 }), + status("ready"), + ok(), + ]); + const response = await h.post(); + assert.equal(response.status, 200); + assert.deepEqual(h.sleeps, [2000, 1000, 2000, 2000]); + const polls = new Set( + h.calls + .filter((call) => call.method === "GET") + .map((call) => `${call.url} ${call.headers.get("X-StepCode-Queue-ID")}`), + ); + assert.deepEqual(polls, new Set([`${QUEUE} q-1`])); +}); + +test("gives up once polling has failed for the whole budget", async () => { + const failures: Reply[] = Array.from({ length: 20 }, () => new Response("down", { status: 502 })); + const h = harness([queued(1), ...failures], { budgetMs: 10_000 }); + const response = await h.post(); + assert.equal(response.status, 410); + const body = (await response.json()) as { error: { message: string } }; + assert.match(body.error.message, /HTTP 502/u); + // 2000 + 1000 + 2000 + 4000 + 8000 >= 10000 since the last success. + assert.deepEqual(h.sleeps, [2000, 1000, 2000, 4000, 8000]); + assert.equal(h.states.at(-1), null); +}); + +test("leaves the line with a cancel request when the caller aborts while waiting", async () => { + const h = harness([ + queued(2), + () => { + h.caller.abort(new DOMException("stop", "AbortError")); + return status("waiting", { position: 1 }); + }, + new Response(null, { status: 204 }), + ]); + await assert.rejects(h.post(), { name: "AbortError" }); + assertCancel(h.calls.at(-1)); + assert.equal(h.states.at(-1), null); + assert.equal(h.released(), 1); +}); + +test("ignores the SDK's own attempt timeout while waiting in line", async () => { + const attempt = new AbortController(); + const h = harness([ + queued(1), + () => { + attempt.abort(new Error("Request timed out.")); + return status("ready"); + }, + (call) => { + assert.equal(call.signal?.aborted, false); + return ok(); + }, + ]); + const response = await h.post(CHAT, { signal: attempt.signal }); + assert.equal(response.status, 200); + assert.deepEqual( + h.calls.map((call) => call.method), + ["POST", "GET", "POST"], + ); +}); + +test("switch: the environment wins, then settings, and the queue is on otherwise", () => { + const resolve = resolveStepModelQueueEnabled; + // Neither the environment nor a setting decides: on, whatever the host. + assert.deepEqual(resolve({ env: {} }), { enabled: true, source: "default" }); + // An explicit setting turns it off, or on. + assert.deepEqual(resolve({ env: {}, settings: { modelQueue: false } }), { + enabled: false, + source: "settings", + }); + assert.deepEqual(resolve({ env: {}, settings: { modelQueue: true } }), { + enabled: true, + source: "settings", + }); + // The environment beats the setting. + assert.deepEqual(resolve({ env: { STEPCODE_MODEL_QUEUE: "1" }, settings: { modelQueue: false } }), { + enabled: true, + source: "env", + }); + assert.deepEqual(resolve({ env: { STEPCODE_MODEL_QUEUE: "0" }, settings: { modelQueue: true } }), { + enabled: false, + source: "env", + }); + // An unrecognized value is no override. + assert.deepEqual(resolve({ env: { STEPCODE_MODEL_QUEUE: "maybe" }, settings: { modelQueue: false } }), { + enabled: false, + source: "settings", + }); + assert.deepEqual(resolve({ env: { STEPCODE_MODEL_QUEUE: "maybe" } }), { enabled: true, source: "default" }); +}); + +function factoryRequest(provider: string, baseUrl = "https://api.stepfun.com/step_plan/v1"): ModelFetchRequest { + return { + model: { provider, baseUrl } as ModelFetchRequest["model"], + signal: new AbortController().signal, + fetch: globalThis.fetch, + holdIdleWatchdog: () => () => {}, + reportQueue: () => {}, + registerTeardown: () => {}, + }; +} + +test("the factory wraps every model's requests only with the switch on", () => { + let settings: { modelQueue?: boolean } = { modelQueue: false }; + const factory = createStepModelQueueFactory({ env: {}, settings: () => settings }); + assert.equal(factory(factoryRequest("step")), undefined); + // Read per request: turning it on applies to the next one. + settings = { modelQueue: true }; + assert.equal(typeof factory(factoryRequest("step")), "function"); + assert.equal(typeof factory(factoryRequest("my-gateway")), "function"); + // Unset is on; the environment can still turn it off. + assert.equal( + typeof createStepModelQueueFactory({ env: {}, settings: () => undefined })(factoryRequest("step")), + "function", + ); + assert.equal( + createStepModelQueueFactory({ env: { STEPCODE_MODEL_QUEUE: "0" }, settings: () => undefined })( + factoryRequest("step"), + ), + undefined, + ); +}); + +test("the request host decides, not the provider: a custom provider at Step's host queues, elsewhere it does not", async () => { + const factory = createStepModelQueueFactory( + { env: {}, settings: () => ({ modelQueue: true }) }, + { queueId: () => "id", sleep: async () => {} }, + ); + const seen: string[] = []; + const replies = [queued(4), status("ready"), ok(), queued(4)]; + const wrapped = factory({ + ...factoryRequest("my-gateway"), + fetch: async (input, init) => { + const request = new Request(input, init); + seen.push(`${request.headers.get("X-StepCode-Queue-ID") ?? "plain"} ${request.method} ${request.url}`); + return replies.shift() ?? ok(); + }, + }); + assert.ok(wrapped); + const atStep = await wrapped("https://api.stepfun.com/v1/chat/completions", { method: "POST", body: BODY }); + assert.equal(atStep.status, 200); + // Elsewhere, even a queued-looking answer is the caller's. + const elsewhere = await wrapped("https://gateway.example.test/v1/chat/completions", { method: "POST", body: BODY }); + assert.equal(elsewhere.status, 429); + assert.deepEqual(seen, [ + "id POST https://api.stepfun.com/v1/chat/completions", + "id GET https://api.stepfun.com/stepcode/v1/queue", + "id POST https://api.stepfun.com/v1/chat/completions", + "plain POST https://gateway.example.test/v1/chat/completions", + ]); +}); + +test("status text names the position, never a wait estimate", () => { + assert.equal(stepModelQueueStatusText({ position: 3 }), "Queued: position 3"); + assert.equal(stepModelQueueStatusText({}), "Queued"); + assert.equal(stepModelQueueStatusText({ position: 0 }), "Queued"); +}); + +test("a stop waits for the cancel request, and the call stays a registered teardown until it settles", async () => { + let cancelReceived = false; + const h = harness([ + queued(1), + () => { + h.caller.abort(new DOMException("stop", "AbortError")); + return status("waiting", { position: 1 }); + }, + async () => { + await new Promise((resolve) => setTimeout(resolve, 20)); + cancelReceived = true; + return new Response(null, { status: 200 }); + }, + ]); + await assert.rejects(h.post(), { name: "AbortError" }); + // The stopped call returned only after its cancel answered. + assert.equal(cancelReceived, true); + assert.equal(h.teardowns.length, 1); + await h.teardowns[0]; +}); + +test("a call becomes a teardown only once the server queues it, and stops being one when it settles", async () => { + const h = harness([ok(), queued(1), status("ready"), ok()]); + await h.post(); + // Answered on the first send: nothing to release, nothing registered. + assert.deepEqual(h.teardowns, []); + await h.post(); + assert.equal(h.teardowns.length, 1); + await h.teardowns[0]; +}); + +test("requests to other hosts register no teardown", async () => { + const h = harness([ok()]); + await h.post("https://gateway.example.test/v1/chat/completions"); + assert.deepEqual(h.teardowns, []); +}); + +test("a hanging cancel ends within its own bound", async () => { + const h = harness([ + queued(1), + () => { + h.caller.abort(new DOMException("stop", "AbortError")); + return status("waiting", { position: 1 }); + }, + (call) => + new Promise((_resolve, reject) => { + call.signal?.addEventListener("abort", () => reject(call.signal?.reason), { once: true }); + }), + ]); + const started = Date.now(); + await assert.rejects(h.post(), { name: "AbortError" }); + const elapsed = Date.now() - started; + assert.ok(elapsed >= 900 && elapsed < 3_000, `cancel bound: ${elapsed}ms`); +}); diff --git a/packages/coding-agent/test/step-trace-headers.test.ts b/packages/coding-agent/test/step-trace-headers.test.ts index 7710b4f7f..12f2deeab 100644 --- a/packages/coding-agent/test/step-trace-headers.test.ts +++ b/packages/coding-agent/test/step-trace-headers.test.ts @@ -68,13 +68,13 @@ describe("Step trace headers", () => { accept: "application/json", }; applyStepTraceHeaders(headers, trace, { - clientType: " cli ", + clientType: " stepcode-desktop ", requestUrl: "https://other.example/v1/messages", allowedBaseUrls: ["https://allowed.example/v1"], }); expect(headers).toEqual({ - "x-step-client": "cli", + "x-step-client": "stepcode-desktop", "x-step-session-id": "stale-session", accept: "application/json", }); @@ -86,7 +86,7 @@ describe("Step trace headers", () => { requestUrl: "https://collector.example/v1/messages", allowedBaseUrls: [], }); - expect(headers).toEqual({ "x-step-client": "cli" }); + expect(headers).toEqual({ "x-step-client": "stepcode-cli" }); }); it("matches only a complete URL prefix", () => { diff --git a/packages/coding-agent/test/subagent-child-env.test.ts b/packages/coding-agent/test/subagent-child-env.test.ts index 49e568530..a77f2d9a1 100644 --- a/packages/coding-agent/test/subagent-child-env.test.ts +++ b/packages/coding-agent/test/subagent-child-env.test.ts @@ -21,6 +21,7 @@ import { resolveSubagentTurnIdleTimeoutMs, } from "../src/features/subagent/rpc-adapter.ts"; import { WORKFLOW_ACL_ENV } from "../src/features/workflow/acl-extension.ts"; +import { resolveStepModelQueueEnabled } from "../src/step/model-queue.ts"; const agent: StepAgentConfig = { name: "general", @@ -265,3 +266,22 @@ test("the wall-clock limit ends a turn even while the child keeps streaming", as process.argv[1] = originalArgv1; } }, 20_000); + +// A child agent decides the model request queue from its own environment: the +// queue is on unless the parent's environment says otherwise, and an override +// reaches the child unchanged. +test("an rpc child inherits the queue switch, and queues by default without one", () => { + vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); + const defaultChild = buildSubagentChildEnv(runInput()); + expect(resolveStepModelQueueEnabled({ env: defaultChild })).toEqual({ enabled: true, source: "default" }); + // A user setting the child reads from the same config still turns it off. + expect(resolveStepModelQueueEnabled({ env: defaultChild, settings: { modelQueue: false } }).enabled).toBe(false); + + vi.stubEnv("STEPCODE_MODEL_QUEUE", "1"); + const forcedChild = buildSubagentChildEnv(runInput()); + expect(forcedChild.STEPCODE_MODEL_QUEUE).toBe("1"); + expect(resolveStepModelQueueEnabled({ env: forcedChild, settings: { modelQueue: false } })).toEqual({ + enabled: true, + source: "env", + }); +}); diff --git a/packages/providers/src/step-provider/index.ts b/packages/providers/src/step-provider/index.ts index 8f76a8941..dd24caa2f 100644 --- a/packages/providers/src/step-provider/index.ts +++ b/packages/providers/src/step-provider/index.ts @@ -602,3 +602,53 @@ function readStringArray(value: Record, key: string): string[] const items = result.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0); return items.length > 0 ? items : undefined; } + +/** + * Whether a model (or provider id) belongs to the Step provider: the one rule + * every "is this Step's own provider?" question uses. A custom provider pointed + * at a Step endpoint is not the Step provider; its id, not its URL, decides. + * Questions about a request's destination use {@link isStepPlatformUrl}. + */ +export function isStepProvider(model: { readonly provider: string } | string | undefined): boolean { + const provider = typeof model === "string" ? model : model?.provider; + return provider === STEP_PROVIDER_ID; +} + +/** + * Variables that declare a Step platform endpoint without being one the provider + * sends model requests to: the models proxy a host routes Step requests through. + */ +const PLATFORM_DECLARATION_ENV_NAMES = ["STEP_MODELS_PROXY_BASE_URL"] as const; + +/** + * Host names of the Step platform API this process is configured for: the + * provider default, every API base URL override the Step provider reads, and a + * declared models proxy. A variable may list several URLs, comma-separated. For + * callers that only have a URL (telemetry endpoint classes); provider questions + * use {@link isStepProvider}. + */ +export function stepPlatformHosts(env: Record = process.env): ReadonlySet { + const hosts = new Set(); + const declared = [...API_BASE_URL_ENV_NAMES, ...PLATFORM_DECLARATION_ENV_NAMES].map((name) => env[name]); + for (const value of [STEP_PROVIDER_DEFAULTS.apiBaseUrl, ...declared]) { + for (const candidate of (value ?? "").split(",")) { + const url = candidate.trim(); + if (!url) continue; + try { + hosts.add(new URL(url).hostname.toLowerCase()); + } catch { + // A malformed override names no host; the provider reports it on use. + } + } + } + return hosts; +} + +/** Whether a URL addresses the Step platform API (exact host match, see {@link stepPlatformHosts}). */ +export function isStepPlatformUrl(url: string, env: Record = process.env): boolean { + try { + return stepPlatformHosts(env).has(new URL(url).hostname.toLowerCase()); + } catch { + return false; + } +} diff --git a/packages/providers/src/utils/stream-watchdog.ts b/packages/providers/src/utils/stream-watchdog.ts index 1d930680e..ff79a9b6d 100644 --- a/packages/providers/src/utils/stream-watchdog.ts +++ b/packages/providers/src/utils/stream-watchdog.ts @@ -15,6 +15,41 @@ export interface StreamIdleWatchdogOptions { onTimeout: () => void; /** Response shell used when the provider has not produced a partial response yet. */ fallback: () => AssistantMessage; + /** Suspends the idle bound while the request waits outside the provider (see {@link StreamIdleHold}). */ + hold?: StreamIdleHold; +} + +/** + * Pauses a stream's idle bound while its request is deliberately held before + * the provider answers, e.g. while the server has not admitted it yet. While any + * acquisition is outstanding the watchdog does not fire; releasing the last one + * starts a full idle window again. + */ +export class StreamIdleHold { + private count = 0; + private readonly listeners = new Set<() => void>(); + + get held(): boolean { + return this.count > 0; + } + + /** Hold the bound; the returned function releases this acquisition (idempotent). */ + acquire(): () => void { + this.count++; + let released = false; + return () => { + if (released) return; + released = true; + this.count--; + if (this.count === 0) for (const listener of this.listeners) listener(); + }; + } + + /** Called whenever the last acquisition is released. Returns the unsubscribe function. */ + onRelease(listener: () => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } } /** @@ -62,8 +97,17 @@ async function pump( }; for (;;) { let timer: ReturnType | undefined; + let stopRearming: (() => void) | undefined; const expired = new Promise<"timeout">((resolve) => { - timer = setTimeout(() => resolve("timeout"), options.idleTimeoutMs); + const arm = () => { + clearTimeout(timer); + timer = setTimeout(() => { + // A held request is not stalled; the release re-arms a full window. + if (!options.hold?.held) resolve("timeout"); + }, options.idleTimeoutMs); + }; + stopRearming = options.hold?.onRelease(arm); + arm(); }); let next: IteratorResult | "timeout"; try { @@ -73,6 +117,7 @@ async function pump( return; } finally { clearTimeout(timer); + stopRearming?.(); } if (next === "timeout") { options.onTimeout(); diff --git a/packages/providers/test/step-identity.test.ts b/packages/providers/test/step-identity.test.ts new file mode 100644 index 000000000..2d261d5c6 --- /dev/null +++ b/packages/providers/test/step-identity.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; +import { isStepPlatformUrl, isStepProvider, stepPlatformHosts } from "../src/step-provider/index.ts"; + +describe("Step identity", () => { + it("tells the Step provider by its id, never by its URL", () => { + expect(isStepProvider({ provider: "step" })).toBe(true); + expect(isStepProvider("step")).toBe(true); + expect(isStepProvider({ provider: "my-gateway" })).toBe(false); + expect(isStepProvider(undefined)).toBe(false); + }); + + it("knows the platform hosts from the provider default and its endpoint overrides", () => { + expect([...stepPlatformHosts({})]).toEqual(["api.stepfun.com"]); + expect( + stepPlatformHosts({ + STEP_BASE_URL: "https://staging.example.test/step_plan", + STEP_LOGIN_PROFILE_API_URL: "https://api.stepfun.ai/step_plan", + STEP_API_URL: "not a url", + }), + ).toEqual(new Set(["api.stepfun.com", "staging.example.test", "api.stepfun.ai"])); + expect(isStepPlatformUrl("https://api.stepfun.com/v1/chat/completions", {})).toBe(true); + // Exact host match: a sibling subdomain is not the platform. + expect(isStepPlatformUrl("https://evil.stepfun.com/v1", {})).toBe(false); + expect(isStepPlatformUrl("garbage", {})).toBe(false); + }); + + it("still recognizes every endpoint the telemetry classification recognized before", () => { + // A declared models proxy is the platform. + expect( + isStepPlatformUrl("https://proxy.example.test/v1", { + STEP_MODELS_PROXY_BASE_URL: "https://proxy.example.test", + }), + ).toBe(true); + // Comma-separated lists, in any of the variables, each name a host. + const env = { + STEP_BASE_URL: "https://one.example.test/step_plan, https://two.example.test/step_plan", + STEP_MODELS_PROXY_BASE_URL: "https://proxy-a.example.test,https://proxy-b.example.test", + STEPFUN_MESSAGES_ENDPOINT: "https://legacy.example.test/v1/messages, not a url", + }; + for (const host of [ + "one.example.test", + "two.example.test", + "proxy-a.example.test", + "proxy-b.example.test", + "legacy.example.test", + ]) { + expect(isStepPlatformUrl(`https://${host}/v1`, env)).toBe(true); + } + expect(isStepPlatformUrl("https://other.example.test/v1", env)).toBe(false); + }); +}); diff --git a/packages/providers/test/stream-watchdog.test.ts b/packages/providers/test/stream-watchdog.test.ts index 1e53dc860..a827b1fb2 100644 --- a/packages/providers/test/stream-watchdog.test.ts +++ b/packages/providers/test/stream-watchdog.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import type { AssistantMessage } from "../src/types.ts"; import { createAssistantMessageEventStream } from "../src/utils/event-stream.ts"; import { isRetryableAssistantError } from "../src/utils/retry.ts"; -import { withStreamIdleWatchdog } from "../src/utils/stream-watchdog.ts"; +import { StreamIdleHold, withStreamIdleWatchdog } from "../src/utils/stream-watchdog.ts"; function shell(): AssistantMessage { return { @@ -94,4 +94,47 @@ describe("stream idle watchdog", () => { const source = createAssistantMessageEventStream(); expect(withStreamIdleWatchdog(source, { idleTimeoutMs: 0, onTimeout: () => {}, fallback: shell })).toBe(source); }); + + it("does not fire while held and restarts a full window on release", async () => { + const source = createAssistantMessageEventStream(); + const hold = new StreamIdleHold(); + let cancelled = 0; + const watched = withStreamIdleWatchdog(source, { + idleTimeoutMs: 40, + onTimeout: () => cancelled++, + fallback: shell, + hold, + }); + const release = hold.acquire(); + await sleep(120); + expect(cancelled).toBe(0); + release(); + release(); + expect(hold.held).toBe(false); + // Released just now: the next window is a full one, not the tail of a held one. + await sleep(25); + expect(cancelled).toBe(0); + const partial = shell(); + source.push({ type: "start", partial }); + source.push({ type: "done", reason: "stop", message: partial }); + expect((await watched.result()).stopReason).toBe("stop"); + expect(cancelled).toBe(0); + }); + + it("fires once the hold is released and the stream stays silent", async () => { + const hold = new StreamIdleHold(); + let cancelled = 0; + const watched = withStreamIdleWatchdog(createAssistantMessageEventStream(), { + idleTimeoutMs: 30, + onTimeout: () => cancelled++, + fallback: shell, + hold, + }); + const release = hold.acquire(); + await sleep(70); + release(); + const result = await watched.result(); + expect(cancelled).toBe(1); + expect(result.errorMessage).toMatch(/stream idle timeout/); + }); }); From 9dd2f4fdc5a3054e4641e4249cb3269e2222c4dd Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:09:11 +0800 Subject: [PATCH 2/5] feat(step): let the server alone decide queueing, and bound a wait at 20 minutes - Drop the client switch (STEPCODE_MODEL_QUEUE and model_queue): the queue only engages when Step's server answers with a queued 429. - Poll every 5s when the server names no interval (capped at 30s); one call waits in line at most 20 minutes across resends, then ends as wait_timeout. - Leave the line with a cancel whenever this side stops waiting: a stop, the wait bound, a status endpoint that keeps failing, or an unexpected status. - Send x-step-client-version with x-step-client so the server can admit client releases per client. - /btw side questions carry the client identity and go through the queue. --- apps/cli/src/main.ts | 6 +- apps/cli/test/queue-signal-exit.test.ts | 1 - docs/step-configuration.md | 14 +- .../docs/environment-variables.md | 1 - .../coding-agent/docs/step-integration.md | 38 +++-- packages/coding-agent/src/index.ts | 10 +- packages/coding-agent/src/step/model-queue.ts | 117 +++++--------- packages/coding-agent/src/step/sdk.ts | 16 +- .../coding-agent/src/step/settings-manager.ts | 30 ---- .../coding-agent/src/step/slash-commands.ts | 28 +++- .../coding-agent/src/step/trace-headers.ts | 11 +- .../coding-agent/test/step-extension.test.ts | 9 +- .../test/step-model-queue-session.test.ts | 99 +++--------- .../test/step-model-queue.test.ts | 144 ++++++++++-------- .../test/step-slash-commands.test.ts | 10 +- .../test/step-trace-headers.test.ts | 13 +- .../test/subagent-child-env.test.ts | 20 --- 17 files changed, 248 insertions(+), 319 deletions(-) diff --git a/apps/cli/src/main.ts b/apps/cli/src/main.ts index 9c77837a0..b170aa175 100644 --- a/apps/cli/src/main.ts +++ b/apps/cli/src/main.ts @@ -324,10 +324,8 @@ const stepMainOptions: MainOptions = { }, ...(modelRequestObserver ? { modelRequestObserver } : {}), // Every mode (interactive, print/json, rpc and the subagent children it - // starts) runs through here; the switch decides per request. - modelFetch: createStepModelQueueFactory({ - settings: () => currentStepSettingsManager?.getStepSettings(), - }), + // starts) runs through here; whether a request waits is the server's decision. + modelFetch: createStepModelQueueFactory(), systemPromptProduct: { name: "StepCode", role: "an interactive terminal coding agent developed by StepFun", diff --git a/apps/cli/test/queue-signal-exit.test.ts b/apps/cli/test/queue-signal-exit.test.ts index a5d1fe4d2..407886b61 100644 --- a/apps/cli/test/queue-signal-exit.test.ts +++ b/apps/cli/test/queue-signal-exit.test.ts @@ -200,7 +200,6 @@ describe.skipIf(process.platform === "win32")("-p in the model request queue", ( STEP_CODING_AGENT_DIR: agentDir, STEP_NO_LOCAL_LLM: "1", AWS_EC2_METADATA_DISABLED: "true", - STEPCODE_MODEL_QUEUE: "1", HTTPS_PROXY: `http://127.0.0.1:${proxyPort}`, NODE_TLS_REJECT_UNAUTHORIZED: "0", }, diff --git a/docs/step-configuration.md b/docs/step-configuration.md index 04c6e9178..843037c47 100644 --- a/docs/step-configuration.md +++ b/docs/step-configuration.md @@ -186,17 +186,9 @@ when a reply respawns its child. ### Model request queue When Step's model pool is busy, the server can keep a model request sent to -Step's API in a first-come line instead of rejecting it. The client side is on -by default: - -```toml -model_queue = true -``` - -Every model request sent to `api.stepfun.com` or `api.stepfun.ai` takes part, -whichever provider sends it. `STEPCODE_MODEL_QUEUE=1` / `0` overrides the setting; a trusted project's -`.stepcode/config.toml` overrides the global one; with neither, the queue is on, -for every host alike. See +Step's API in a first-come line instead of rejecting it. Every model request sent +to `api.stepfun.com` or `api.stepfun.ai` takes part, whichever provider sends it. +There is no client setting: whether a request waits is decided by the server. See [Step integration](../packages/coding-agent/docs/step-integration.md#model-request-queue) for the protocol. diff --git a/packages/coding-agent/docs/environment-variables.md b/packages/coding-agent/docs/environment-variables.md index 937a8328e..b4a4ffa84 100644 --- a/packages/coding-agent/docs/environment-variables.md +++ b/packages/coding-agent/docs/environment-variables.md @@ -16,7 +16,6 @@ Step reads the variables below. Configuration shared across launches belongs in | `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_PROVIDER`, `STEP_MODEL` | Default provider and model selection | -| `STEPCODE_MODEL_QUEUE` | Model request queue: `1` on, `0` off, over `model_queue`; on by default. See [Step integration](step-integration.md#model-request-queue) | | `VISUAL`, `EDITOR` | External editor fallback when `externalEditor` is unset | | `HTTP_PROXY`, `HTTPS_PROXY` | Proxy outbound HTTP requests | diff --git a/packages/coding-agent/docs/step-integration.md b/packages/coding-agent/docs/step-integration.md index e9786d047..07de67c01 100644 --- a/packages/coding-agent/docs/step-integration.md +++ b/packages/coding-agent/docs/step-integration.md @@ -53,6 +53,10 @@ saved settings, then the Step product default. Every Step request names the product it came from in `x-step-client`: `stepcode-cli` (this build's default, `STEP_CLIENT`), or whatever a host sets — `stepcode-desktop` for the desktop app, `stepcode-web` for its web server. +It also sends that product's release version in `x-step-client-version`: the +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. Set `STEP_PROVIDER`, `STEP_MODEL`, `STEP_API_KEY`, or the provider endpoint variables to override the defaults. The Step launcher also disables upstream @@ -223,19 +227,20 @@ API in a first-come line instead of rejecting it, and the client waits its turn (`src/step/model-queue.ts`, installed through the generic [`modelFetch`](sdk.md#model-request-fetch) hook). -**Switch.** `STEPCODE_MODEL_QUEUE` (`1` / `0`) wins; then `model_queue` (a -trusted project's `.stepcode/config.toml` over `~/.stepcode/config.toml`; a -value that is not a boolean is ignored with a settings warning); with neither, -the queue is on, for every host alike (the CLI, the desktop app, the web app and -subagent children). The switch is read for every request, so a settings reload -applies to the next one. +**Switch.** There is no client switch. The client always speaks the protocol +on Step's API hosts, and whether a request waits is the server's decision alone, +for every host alike (the CLI, the desktop app, the web app and subagent +children). The server tells StepCode clients apart by `x-step-client` and +`x-step-client-version`. **Mount points.** The CLI composition root passes the queue factory to every mode (interactive, `-p`, `--mode json`, `--mode rpc`, and the subagent children that run those modes). `createStepAgentSession()` and `createStepAgentSessionServices()` install it by default for embedded hosts. -**Which requests.** Every model request sent to one of Step's two API hosts, +**Which requests.** Every model request sent to one of Step's two API hosts +(conversation turns, compaction and branch summaries, subagent children, and +`/btw` side questions), whatever the provider (the official `step` provider or a user's own provider pointed at Step), login profile or route: the request host makes it a StepCode request. The host also picks the queue: @@ -253,14 +258,16 @@ The endpoints are fixed, not configurable. A request to any other host (for example an endpoint override through `STEP_BASE_URL`) is sent as it is, with no header and no queue. -**Protocol.** With the switch on, every such request carries a fresh +**Protocol.** Every such request carries a fresh `X-StepCode-Queue-ID`; whether it waits is the server's decision: - HTTP 429 with `X-StepCode-Queue-State: waiting` means the request holds a place in line (`X-StepCode-Queue-Position`). The client polls its region's - status endpoint every `Retry-After-Ms` (default 2s) and on `ready` sends the - original bytes again under the same id; a queued answer to the resend keeps - polling. + status endpoint every `Retry-After-Ms` (status `retry_after_ms`; 5s when the + server names none, at most 30s) and on `ready` sends the original bytes again + under the same id; a queued answer to the resend keeps polling. One call waits + in line at most 20 minutes in all, across resends; past that it ends with the + 410 below, reason `wait_timeout`. The stream idle watchdog is held only while polling. - `closed`, or a status answer of 404 (`not_found`), ends the request with a synthesized HTTP 410 `queue_closed` error carrying `x-should-retry: false`, so @@ -271,9 +278,12 @@ header and no queue. caller as it is. A 429 or 5xx status answer, or a network error, is retried with backoff from 1s to 8s; after 30s without a good answer the request ends with the same 410. Any other status answer ends it too. -- A stop after the server queued the call (it answered `429` with - `X-StepCode-Queue-State: waiting`) releases the place with the region's cancel - endpoint (queue id header, no body; 200 on success). A stop before any such +- Once the server queued the call (it answered `429` with + `X-StepCode-Queue-State: waiting`), every way this side stops waiting releases + the place with the region's cancel endpoint (queue id header, no body; 200 on + success): a stop, the 20-minute bound, or a status endpoint that keeps failing + or answers an unexpected status. A place the server closed is not cancelled + again. A stop before any such answer sends nothing more; the server's lease ends a place the client never saw, so a host without the queue never gets a cancel. The stopped call awaits the cancel for at most 1s, and a queued call is a registered request teardown diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts index afb909270..b8d172cf2 100644 --- a/packages/coding-agent/src/index.ts +++ b/packages/coding-agent/src/index.ts @@ -739,15 +739,7 @@ export { export { ambiguousPluginServerNames, resolveStepMcpServer } from "./step/mcp.ts"; export { describeStepMcpImportOutcome, runStepMcpImportPrompt } from "./step/mcp-import-prompt.ts"; export { hasStoredMcpOAuthCredential, loginMcpServer, logoutMcpServer } from "./step/mcp-oauth.ts"; -export { - createStepModelQueueFactory, - resolveStepModelQueueEnabled, - STEP_MODEL_QUEUE_ENV, - type StepModelQueueFactoryOptions, - type StepModelQueueSource, - type StepModelQueueSwitchInput, - stepModelQueueStatusText, -} from "./step/model-queue.ts"; +export { createStepModelQueueFactory, stepModelQueueStatusText } from "./step/model-queue.ts"; export { resolveStepLoginProfiles } from "./step/onboarding.ts"; export { AUTO_RESUME_PROMPT, diff --git a/packages/coding-agent/src/step/model-queue.ts b/packages/coding-agent/src/step/model-queue.ts index a8c78caca..b8d46e9ff 100644 --- a/packages/coding-agent/src/step/model-queue.ts +++ b/packages/coding-agent/src/step/model-queue.ts @@ -1,25 +1,26 @@ import { randomUUID } from "node:crypto"; import type { ModelFetch, ModelFetchFactory, ModelFetchRequest, ModelQueueState } from "../core/model-fetch.ts"; -import type { StepSettings } from "./settings-manager.ts"; /** * Client side of the Step model request queue. * - * With the queue enabled, every model request sent to Step's mainland or - * overseas API host carries a fresh `X-StepCode-Queue-ID`, whichever provider + * Every model request sent to Step's mainland or overseas API host carries a + * fresh `X-StepCode-Queue-ID`, whichever provider * (the official one or a user's own) sent it: the host, not the provider id, - * makes it a StepCode request. Whether a request waits is the server's - * decision: when the pool is busy it answers HTTP 429 with + * makes it a StepCode request. There is no client switch: whether a request + * waits is the server's decision alone. When the pool is busy it answers HTTP 429 with * `X-StepCode-Queue-State: waiting` instead of running the request. That answer * is not a rate-limit failure: the request holds a place in line. The wrapper * then polls the queue of the request's region * (`GET https://api.stepfun.com/stepcode/v1/queue`, or `api.stepfun.ai` * overseas, naming the place in `X-StepCode-Queue-ID`), and once the place is - * `ready` sends the original bytes again under the same id. A `closed` place - * ends the call with an error; a stop after the server queued the call releases - * the place with `POST /cancel` (the id in `X-StepCode-Queue-ID`, no - * body). A stop before any queued answer sends nothing more: the server's lease - * ends a place nobody saw. + * `ready` sends the original bytes again under the same id. The poll interval is + * the server's `retry_after_ms` (5 s when it names none). A `closed` place ends + * the call with an error. A call waits in line at most 20 minutes in all; when it + * stops waiting on its own side (the caller's stop, that bound, or a status + * endpoint that keeps failing) it releases the place with `POST /cancel` + * (the id in `X-StepCode-Queue-ID`, no body). A stop before any queued answer + * sends nothing more: the server's lease ends a place nobody saw. * * POST .../chat/completions -> 429 queued (position 3) * GET (X-StepCode-Queue-ID) -> waiting (position 1) @@ -48,11 +49,12 @@ const QUEUE_ENDPOINTS: Readonly> = { "api.stepfun.com": "https://api.stepfun.com/stepcode/v1/queue", "api.stepfun.ai": "https://api.stepfun.ai/stepcode/v1/queue", }; -/** `1` / `0` force the queue on or off, over every setting. */ -export const STEP_MODEL_QUEUE_ENV = "STEPCODE_MODEL_QUEUE"; - -const DEFAULT_POLL_INTERVAL_MS = 2_000; +/** Poll interval when the server names none. */ +const DEFAULT_POLL_INTERVAL_MS = 5_000; +/** Upper bound of a server-named poll interval, so one bad value cannot stall a waiting call. */ const MAX_POLL_INTERVAL_MS = 30_000; +/** How long one call may wait in line in all, from the server's first queued answer. */ +const DEFAULT_MAX_WAIT_MS = 20 * 60_000; const POLL_TIMEOUT_MS = 10_000; const FIRST_POLL_BACKOFF_MS = 1_000; const MAX_POLL_BACKOFF_MS = 8_000; @@ -68,6 +70,7 @@ const CLOSED_REASON_TEXT: Readonly> = { user_limit: "You have too many requests waiting in line. Wait for them to finish and try again.", lease_expired: "Your place in line expired. Send the request again.", max_wait_exceeded: "The request waited in line too long. Try again later.", + wait_timeout: "The request waited in line too long. Try again later.", not_found: "Your place in line no longer exists. Send the request again.", }; const CLOSED_GENERIC_TEXT = "The request queue closed this request. Try again later."; @@ -83,80 +86,28 @@ export function stepModelQueueStatusText(state: ModelQueueState): string { return state.position !== undefined && state.position > 0 ? `Queued: position ${state.position}` : "Queued"; } -/** Where the effective queue switch came from. */ -export type StepModelQueueSource = "env" | "settings" | "default"; - -export interface StepModelQueueSwitchInput { - readonly env?: NodeJS.ProcessEnv; - /** Effective Step settings (project over global); `modelQueue` is the configured value. */ - readonly settings?: Pick; -} - -function readSwitch(value: string | undefined): boolean | undefined { - switch (value?.trim().toLowerCase()) { - case "1": - case "true": - return true; - case "0": - case "false": - return false; - default: - return undefined; - } -} - -/** - * Whether Step model requests join the queue. `STEPCODE_MODEL_QUEUE` wins, then - * `model_queue` (project over global); with neither, it is on, whatever the - * host (CLI, desktop, web, subagent children). - */ -export function resolveStepModelQueueEnabled(input: StepModelQueueSwitchInput): { - readonly enabled: boolean; - readonly source: StepModelQueueSource; -} { - const env = input.env ?? process.env; - const forced = readSwitch(env[STEP_MODEL_QUEUE_ENV]); - if (forced !== undefined) return { enabled: forced, source: "env" }; - const configured = input.settings?.modelQueue; - if (typeof configured === "boolean") return { enabled: configured, source: "settings" }; - return { enabled: true, source: "default" }; -} - /** Hooks for tests; not configuration. */ export interface StepModelQueueOptions { /** Replaces the fixed queue endpoints, by request host name. */ readonly queueEndpoints?: Readonly>; /** How long polling may fail in a row before the call ends with an error. Default 30s. */ readonly pollFailureBudgetMs?: number; + /** How long one call may wait in line in all. Default 20 minutes. */ + readonly maxWaitMs?: number; readonly queueId?: () => string; readonly sleep?: (ms: number, signal: AbortSignal) => Promise; readonly now?: () => number; - readonly env?: NodeJS.ProcessEnv; -} - -export interface StepModelQueueFactoryOptions { - readonly env?: NodeJS.ProcessEnv; - /** The effective Step settings, read on every request so a settings reload applies to the next one. */ - readonly settings: () => Pick | undefined; } /** - * The model-fetch factory every Step entry point installs. With the queue off - * the request is left alone (no wrapper); with it on, the wrapper tags and + * The model-fetch factory every Step entry point installs. The wrapper tags and * queues only requests to Step's API hosts and passes every other one on as it is. */ export function createStepModelQueueFactory( - options: StepModelQueueFactoryOptions, /** Test hooks; see {@link StepModelQueueOptions}. */ testing: StepModelQueueOptions = {}, ): ModelFetchFactory { - return (request) => { - const { enabled } = resolveStepModelQueueEnabled({ - env: options.env, - settings: options.settings(), - }); - return enabled ? createStepModelQueueFetch(request, testing) : undefined; - }; + return (request) => createStepModelQueueFetch(request, testing); } /** @@ -259,6 +210,7 @@ export function createStepModelQueueFetch( const sleep = options.sleep ?? defaultSleep; const now = options.now ?? Date.now; const failureBudgetMs = options.pollFailureBudgetMs ?? DEFAULT_POLL_FAILURE_BUDGET_MS; + const maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS; return async (input, init) => { // Decided from the URL alone, so a request that is not queued is passed on // without copying its body. @@ -301,9 +253,11 @@ export function createStepModelQueueFetch( controlHeaders.set(QUEUE_ID_HEADER, queueId); // Leave the line so the place is not held until its lease expires. Sent only // once the server has queued this call, so a host without the queue never - // sees it. Awaited (within CANCEL_TIMEOUT_MS) so a process exiting on the - // stop sends it; its outcome changes nothing for the stopped call, so - // failures are dropped. + // sees it, and only when this side stops waiting (a stop, the wait bound, or + // a status endpoint that keeps failing); a place the server closed is gone + // already. Awaited (within CANCEL_TIMEOUT_MS) so a process exiting on the + // stop sends it; its outcome changes nothing for the call, so failures are + // dropped. const leave = async (): Promise => { try { const response = await base(`${queueBase}/cancel`, { @@ -364,14 +318,25 @@ export function createStepModelQueueFetch( }; publish(true); let closedReason: string | undefined; + // This side stops waiting: release the place, then end the call like a closed one. + const giveUp = async (message: string, reason?: string): Promise => { + closedReason = reason; + await leave(); + return queueEnded(message, reason); + }; + // One bound for the whole wait, across every resend that is queued again. + const deadline = now() + maxWaitMs; try { let lastSuccess = now(); let failures = 0; let lastFailure = ""; for (;;) { + const remaining = deadline - now(); + if (remaining <= 0) return await giveUp(stepModelQueueClosedMessage("wait_timeout"), "wait_timeout"); // The SDK's per-attempt signal also carries its request timeout, which // must not end a wait in line: only the caller's cancellation does. - await sleep(delay, caller); + await sleep(Math.min(delay, remaining), caller); + if (deadline - now() <= 0) continue; let status: QueueStatus | undefined; try { const response = await base(queueBase, { @@ -392,7 +357,7 @@ export function createStepModelQueueFetch( // A throttled or failing status endpoint is retried; other answers // cannot improve by asking again. else if (response.status !== 429 && response.status < 500) - return queueEnded(`Queue status request failed with HTTP ${response.status}`); + return await giveUp(`Queue status request failed with HTTP ${response.status}`); else lastFailure = `HTTP ${response.status}`; } } catch (error) { @@ -401,7 +366,7 @@ export function createStepModelQueueFetch( } if (!status) { if (now() - lastSuccess >= failureBudgetMs) - return queueEnded(`Queue status unavailable: ${lastFailure}`); + return await giveUp(`Queue status unavailable: ${lastFailure}`); delay = Math.min(FIRST_POLL_BACKOFF_MS * 2 ** failures, MAX_POLL_BACKOFF_MS); failures++; continue; diff --git a/packages/coding-agent/src/step/sdk.ts b/packages/coding-agent/src/step/sdk.ts index 6fcf03f5a..db566ed48 100644 --- a/packages/coding-agent/src/step/sdk.ts +++ b/packages/coding-agent/src/step/sdk.ts @@ -90,16 +90,6 @@ function ensureStepSettingsManager( }); } -/** - * The Step model request queue for sessions using these settings. A caller's - * own `modelFetch` replaces it. - */ -function stepModelQueueFactory(settingsManager: StepSettingsManager) { - return createStepModelQueueFactory({ - settings: () => settingsManager.getStepSettings(), - }); -} - /** Create a Pi AgentSession with Step's settings decorator installed. */ export async function createStepAgentSession( options: CreateStepAgentSessionOptions = {}, @@ -119,7 +109,8 @@ export async function createStepAgentSession( configDirName: paths.configDirName, settingsManager, sessionManager, - modelFetch: options.modelFetch ?? stepModelQueueFactory(settingsManager), + // The Step model request queue; a caller's own `modelFetch` replaces it. + modelFetch: options.modelFetch ?? createStepModelQueueFactory(), }); } @@ -135,6 +126,7 @@ export async function createStepAgentSessionServices( agentDir: paths.agentDir, configDirName: paths.configDirName, settingsManager, - modelFetch: options.modelFetch ?? stepModelQueueFactory(settingsManager), + // The Step model request queue; a caller's own `modelFetch` replaces it. + modelFetch: options.modelFetch ?? createStepModelQueueFactory(), }) as Promise; } diff --git a/packages/coding-agent/src/step/settings-manager.ts b/packages/coding-agent/src/step/settings-manager.ts index e90190820..ae09cb1f5 100644 --- a/packages/coding-agent/src/step/settings-manager.ts +++ b/packages/coding-agent/src/step/settings-manager.ts @@ -47,13 +47,6 @@ export interface StepSettings { subagentBackgroundTimeoutSeconds?: number; /** `[subagent] max_concurrency`: default number of child processes a parallel subagent batch runs at once. */ subagentMaxConcurrency?: number; - /** - * `model_queue`: model requests sent to Step's API hosts (`api.stepfun.com`, - * `api.stepfun.ai`), whichever provider sends them, carry the queue protocol - * and wait when the server queues them. On unless set; `STEPCODE_MODEL_QUEUE` - * overrides it (`src/step/model-queue.ts`). - */ - modelQueue?: boolean; } type JsonObject = Record; @@ -114,16 +107,6 @@ function rawSubagentConcurrencies(value: JsonObject): unknown[] { ); } -/** The raw configured queue switches, from `model_queue` and the flat key. */ -function rawModelQueueValues(value: JsonObject): unknown[] { - return [value.model_queue, value.modelQueue].filter((candidate) => candidate !== undefined); -} - -/** Message for a configured queue switch that is ignored because it is not a boolean. */ -export function invalidModelQueueMessage(value: unknown, keyPath = "model_queue"): string { - return `${keyPath} must be true or false; ignoring ${JSON.stringify(value)}`; -} - export interface StepSettingsPaths { global: string; project: string; @@ -324,10 +307,6 @@ function normalizeSettings(value: JsonObject, resetLegacy = true): StepSettings isValidSubagentMaxConcurrency, ); if (subagentConcurrency !== undefined) result.subagentMaxConcurrency = subagentConcurrency; - const modelQueue = [value.model_queue, value.modelQueue].find( - (candidate): candidate is boolean => typeof candidate === "boolean", - ); - if (modelQueue !== undefined) result.modelQueue = modelQueue; if (resetLegacy) resetLegacyPermissionSettings(result, winningPresetCandidate, winningModeCandidate); return result; } @@ -356,7 +335,6 @@ const STEP_SETTING_ALIASES: Record = { subagentBackground: [], subagentBackgroundTimeoutSeconds: [], subagentMaxConcurrency: [], - modelQueue: ["model_queue"], }; const STEP_SETTING_NESTED_ALIASES: Record = { @@ -388,7 +366,6 @@ const STEP_SETTING_NESTED_ALIASES: Record): Partial { `Invalid Step subagentMaxConcurrency setting: ${String(settings.subagentMaxConcurrency)} (expected a positive integer)`, ); } - if (settings.modelQueue !== undefined && typeof settings.modelQueue !== "boolean") { - throw new Error(`Invalid Step modelQueue setting: ${String(settings.modelQueue)}`); - } const normalized = { ...settings }; if (settings.permissionPreset !== undefined) { normalized.permissionPreset = getStepPermissionPreset(settings.permissionPreset)!.id; @@ -573,10 +547,6 @@ class StepSettingsStore { if (isValidSubagentMaxConcurrency(concurrency)) continue; this.errors.push({ scope, path, error: new Error(invalidSubagentMaxConcurrencyMessage(concurrency)) }); } - for (const queue of rawModelQueueValues(value)) { - if (typeof queue === "boolean") continue; - this.errors.push({ scope, path, error: new Error(invalidModelQueueMessage(queue)) }); - } return value; } diff --git a/packages/coding-agent/src/step/slash-commands.ts b/packages/coding-agent/src/step/slash-commands.ts index 4e847e3b7..423a7b4da 100644 --- a/packages/coding-agent/src/step/slash-commands.ts +++ b/packages/coding-agent/src/step/slash-commands.ts @@ -35,9 +35,11 @@ import { } from "./feedback/types.ts"; import { normalizeFeedbackCategory } from "./feedback/validate.ts"; import { formatStepMcpStatuses } from "./mcp.ts"; +import { createStepModelQueueFetch } from "./model-queue.ts"; import { registerStepPluginCommand } from "./plugins.ts"; import { resolveStepStorageRoot } from "./storage-root.ts"; import { type StepTelemetryReporter, trackStepTelemetry } from "./telemetry.ts"; +import { applyStepTraceHeaders } from "./trace-headers.ts"; import { registerStepUsageCommands, type StepUsageHost } from "./usage/commands.ts"; /** @@ -171,6 +173,26 @@ const BTW_SYSTEM_REMINDER = [ "Tools are unavailable here. Do not continue, plan, or edit anything for the main task.", ].join("\n"); +/** + * What a model request outside the agent loop needs to reach Step's API like a + * conversation turn does: the client identity headers and the model request + * queue. A side request has no session to report its place in line to or to + * own a teardown; it waits silently, and closing it stops the wait (which + * releases its place). + */ +function stepSideRequestOptions(signal: AbortSignal): { headers: Record; fetch: typeof fetch } { + const headers: Record = {}; + applyStepTraceHeaders(headers, {}, { clientType: process.env.STEP_CLIENT }); + const fetch = createStepModelQueueFetch({ + signal, + fetch: (input, init) => globalThis.fetch(input, init), + holdIdleWatchdog: () => () => {}, + reportQueue: () => {}, + registerTeardown: () => {}, + }); + return { headers, fetch }; +} + /** * `/btw `: one side question that leaves the conversation untouched. * @@ -214,7 +236,11 @@ async function handleStepBtwCommand(args: string, ctx: ExtensionCommandContext): let panel: BtwPanel | undefined; const answer = ctx.modelRegistry - .complete(model, context, { signal: controller.signal, maxTokens: 2048 }) + .complete(model, context, { + signal: controller.signal, + maxTokens: 2048, + ...stepSideRequestOptions(controller.signal), + }) .then((message) => { btwHistory.append(question, message); panel?.setAnswer(assistantText(message)); diff --git a/packages/coding-agent/src/step/trace-headers.ts b/packages/coding-agent/src/step/trace-headers.ts index 647afba62..a53afbb2f 100644 --- a/packages/coding-agent/src/step/trace-headers.ts +++ b/packages/coding-agent/src/step/trace-headers.ts @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import process from "node:process"; import { STEP_CLIENT_DEFAULT } from "./environment.ts"; +import { STEPCODE_VERSION } from "./version.ts"; /** Values copied from the request context into Step's attribution headers. */ export interface StepTraceContext { @@ -21,6 +22,8 @@ export interface StepTraceHeaderOptions { readonly allowedBaseUrls?: readonly string[]; /** Low-sensitivity client label sent to the provider. */ readonly clientType?: string; + /** Low-sensitivity client release version sent to the provider; defaults to the Step product version. */ + readonly clientVersion?: string; /** High-sensitivity fields permitted by the host observability policy. */ readonly highSensitivityFields?: readonly string[]; } @@ -50,8 +53,11 @@ const STEP_TRACE_PRODUCT_PROVIDERS = new Set(["stepfunModelProxy", "neocodex"]); /** * Add Step attribution headers in place. * - * `x-step-client` is sent on every request (`STEP_CLIENT_DEFAULT`, or the - * caller's `clientType` when it names the product). + * `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. * The high-sensitivity fields * (session/workspace/goal/...) are sent only when the request URL matches * `options.allowedBaseUrls` AND the field appears in @@ -66,6 +72,7 @@ export function applyStepTraceHeaders( 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 traceAllowed = options.requestUrl === undefined || diff --git a/packages/coding-agent/test/step-extension.test.ts b/packages/coding-agent/test/step-extension.test.ts index 89788f1ba..a08117e8d 100644 --- a/packages/coding-agent/test/step-extension.test.ts +++ b/packages/coding-agent/test/step-extension.test.ts @@ -7,6 +7,7 @@ import type { } from "../src/core/extensions/types.ts"; import { createStepExtension, stepExtension } from "../src/features/step.ts"; import { STEP_INIT_PROMPT } from "../src/step/init-prompt.ts"; +import { STEPCODE_VERSION } from "../src/step/version.ts"; function commandContext( isIdle: boolean, @@ -846,8 +847,11 @@ describe("Step extension", () => { } as unknown as Pick); // The native Step endpoint is a direct model API, not the cloud-trace // collector. Keep session/workspace identifiers off custom or direct - // provider requests; only the low-sensitivity client marker is universal. - expect(headers).toEqual({ "x-step-client": "stepcode-cli" }); + // provider requests; only the low-sensitivity client markers are universal. + expect(headers).toEqual({ + "x-step-client": "stepcode-cli", + "x-step-client-version": STEPCODE_VERSION.value, + }); const originalOrigin = process.env.STEPCODE_CLOUD_TRACE_ORIGIN; process.env.STEPCODE_CLOUD_TRACE_ORIGIN = "https://trace.example.test/v1"; @@ -864,6 +868,7 @@ describe("Step extension", () => { } as unknown as Pick); expect(otherHeaders).toMatchObject({ "x-step-client": "stepcode-cli", + "x-step-client-version": STEPCODE_VERSION.value, "x-step-session-id": "session-2", "x-step-workspace-id": "/workspace", "x-step-provider-id": "stepfunModelProxy", diff --git a/packages/coding-agent/test/step-model-queue-session.test.ts b/packages/coding-agent/test/step-model-queue-session.test.ts index c9b30e46a..49fcf2c8f 100644 --- a/packages/coding-agent/test/step-model-queue-session.test.ts +++ b/packages/coding-agent/test/step-model-queue-session.test.ts @@ -7,7 +7,6 @@ import type { AgentSessionEvent } from "../src/core/agent-session.ts"; import { AuthStorage } from "../src/core/auth-storage.ts"; import { ModelRuntime } from "../src/core/model-runtime.ts"; import { SessionManager } from "../src/core/session-manager.ts"; -import { resolveStepModelQueueEnabled } from "../src/step/model-queue.ts"; import { createStepAgentSession } from "../src/step/sdk.ts"; import { createStepSettingsManager } from "../src/step/settings-manager.ts"; @@ -47,52 +46,9 @@ function sse(text: string): Response { ); } -describe("model_queue setting", () => { - it("reads model_queue globally, lets a trusted project override it, and ignores an untrusted one", () => { - const { cwd, paths } = fixture("model_queue = true\n", "model_queue = false\n"); - const trusted = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: true }); - expect(trusted.getStepSettings().modelQueue).toBe(false); - expect(resolveStepModelQueueEnabled({ env: {}, settings: trusted.getStepSettings() })).toEqual({ - enabled: false, - source: "settings", - }); - const untrusted = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: false }); - expect(untrusted.getStepSettings().modelQueue).toBe(true); - // Unset everywhere: the queue is on. - const unset = fixture(""); - const plain = createStepSettingsManager(unset.cwd, undefined, { paths: unset.paths, projectTrusted: true }); - expect(plain.getStepSettings().modelQueue).toBeUndefined(); - expect(resolveStepModelQueueEnabled({ env: {}, settings: plain.getStepSettings() })).toEqual({ - enabled: true, - source: "default", - }); - // The flat spelling is the same switch. - const flat = fixture("modelQueue = true\n"); - const flatSettings = createStepSettingsManager(flat.cwd, undefined, { paths: flat.paths, projectTrusted: true }); - expect(flatSettings.getStepSettings().modelQueue).toBe(true); - }); - - it("persists the switch and rejects a non-boolean value", () => { - const { cwd, paths } = fixture(""); - const settings = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: true }); - settings.setStepSettings({ modelQueue: true }); - const reread = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: true }); - expect(reread.getStepSettings().modelQueue).toBe(true); - expect(() => settings.setStepSettings({ modelQueue: "yes" as unknown as boolean })).toThrow(/modelQueue/); - }); - - it("ignores a non-boolean value with a settings warning", () => { - const { cwd, paths } = fixture('model_queue = "yes"\n'); - const settings = createStepSettingsManager(cwd, undefined, { paths, projectTrusted: true }); - expect(settings.getStepSettings().modelQueue).toBeUndefined(); - const messages = settings.drainErrors().map((entry) => entry.error.message); - expect(messages).toContain('model_queue must be true or false; ignoring "yes"'); - }); -}); - describe("Step sessions install the queue", () => { - async function prompt(globalToml: string, server: typeof globalThis.fetch) { - const { root, cwd, paths } = fixture(globalToml); + async function prompt(server: typeof globalThis.fetch) { + const { root, cwd, paths } = fixture(""); const agentDir = join(root, "agent"); mkdirSync(agentDir, { recursive: true }); vi.stubGlobal("fetch", server); @@ -152,15 +108,14 @@ describe("Step sessions install the queue", () => { }, }); - it("queues a request to Step's host when the setting turns the queue on", async () => { - vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); + it("queues a request to Step's host when the server asks it to wait", async () => { const calls: Array<{ method: string; url: string; id: string | null }> = []; const replies = [ () => queuedAnswer(2), () => Response.json({ state: "ready", position: 0, retry_after_ms: 20, reason: "" }), () => sse("after the line"), ]; - const { last, events } = await prompt("model_queue = true\n", async (input, init) => { + const { last, events } = await prompt(async (input, init) => { const request = new Request(input, init); calls.push({ method: request.method, url: request.url, id: request.headers.get("X-StepCode-Queue-ID") }); const reply = replies.shift(); @@ -179,44 +134,40 @@ describe("Step sessions install the queue", () => { ]); }); - it("queues by default, with no setting and no environment override", async () => { - vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); + it("a normal answer goes through with a queue id and no queue events", async () => { + const ids: Array = []; + const { last, events } = await prompt(async (input, init) => { + ids.push(new Request(input, init).headers.get("X-StepCode-Queue-ID")); + return sse("direct"); + }); + expect(last.content).toEqual([{ type: "text", text: "direct" }]); + expect(ids).toHaveLength(1); + expect(ids[0]).toMatch(/^[0-9a-f-]{36}$/u); + expect(events.filter((event) => event.type === "model_queue")).toEqual([]); + }); + + it("an ordinary 429 goes to the existing retry policy, never into the queue", async () => { const calls: string[] = []; const replies = [ - () => queuedAnswer(1), - () => Response.json({ state: "ready", position: 0, retry_after_ms: 20, reason: "" }), - () => sse("by default"), + () => new Response('{"error":{"message":"rate limited","type":"rate_limited"}}', { status: 429 }), + () => sse("after a retry"), ]; - const { last } = await prompt("", async (input, init) => { + const { last, events } = await prompt(async (input, init) => { const request = new Request(input, init); calls.push(`${request.method} ${new URL(request.url).pathname}`); const reply = replies.shift(); if (!reply) throw new Error(`unexpected ${request.method} ${request.url}`); return reply(); }); - expect(last.content).toEqual([{ type: "text", text: "by default" }]); - expect(calls).toEqual([ - "POST /step_plan/v1/chat/completions", - "GET /stepcode/v1/queue", - "POST /step_plan/v1/chat/completions", - ]); - }); - - it("leaves the request alone when the queue is off", async () => { - vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); - const ids: Array = []; - const { last } = await prompt("model_queue = false\n", async (input, init) => { - ids.push(new Request(input, init).headers.get("X-StepCode-Queue-ID")); - return sse("direct"); - }); - expect(last.content).toEqual([{ type: "text", text: "direct" }]); - expect(ids).toEqual([null]); + expect(last.content).toEqual([{ type: "text", text: "after a retry" }]); + expect(calls.every((call) => call === "POST /step_plan/v1/chat/completions")).toBe(true); + expect(calls.length).toBeGreaterThanOrEqual(2); + expect(events.filter((event) => event.type === "model_queue")).toEqual([]); }); it("ends a closed place with one readable error that neither the SDK nor the session retries", async () => { - vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); const calls: string[] = []; - const { last, events } = await prompt("model_queue = true\n", async (input, init) => { + const { last, events } = await prompt(async (input, init) => { const request = new Request(input, init); calls.push(`${request.method} ${new URL(request.url).pathname}`); if (request.method === "GET") diff --git a/packages/coding-agent/test/step-model-queue.test.ts b/packages/coding-agent/test/step-model-queue.test.ts index 68761eaac..724d80149 100644 --- a/packages/coding-agent/test/step-model-queue.test.ts +++ b/packages/coding-agent/test/step-model-queue.test.ts @@ -4,7 +4,6 @@ import type { ModelFetchRequest, ModelQueueExit, ModelQueueState } from "../src/ import { createStepModelQueueFactory, createStepModelQueueFetch, - resolveStepModelQueueEnabled, stepModelQueueClosedMessage, stepModelQueueStatusText, } from "../src/step/model-queue.ts"; @@ -45,7 +44,7 @@ function status(state: string, extra: Record = {}): Response { const ok = () => new Response("data: [DONE]\n\n", { status: 200, headers: { "content-type": "text/event-stream" } }); -function harness(replies: Reply[], options: { budgetMs?: number } = {}) { +function harness(replies: Reply[], options: { budgetMs?: number; maxWaitMs?: number } = {}) { const calls: Call[] = []; const sleeps: number[] = []; const states: Array = []; @@ -101,6 +100,7 @@ function harness(replies: Reply[], options: { budgetMs?: number } = {}) { clock += ms; }, ...(options.budgetMs === undefined ? {} : { pollFailureBudgetMs: options.budgetMs }), + ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }), }, ); const fetchRequest = (input: Request) => wrapped(input); @@ -360,7 +360,7 @@ test("keeps polling when the resend is queued again", async () => { assert.deepEqual(new Set(posts.map((call) => call.headers.get("X-StepCode-Queue-ID"))), new Set(["q-1"])); assert.deepEqual(new Set(posts.map((call) => text(call.body))), new Set([BODY])); assert.deepEqual(h.states, [{ position: 2 }, { position: 4 }, { position: 1 }, null]); - assert.deepEqual(h.sleeps, [2000, 500, 2000]); + assert.deepEqual(h.sleeps, [5000, 500, 2000]); // Released before each resend, held again when the resend is queued. assert.deepEqual( h.calls.map((call) => `${call.method}:${call.held}`), @@ -426,7 +426,7 @@ test("a throttled status endpoint is retried like a failing one", async () => { const h = harness([queued(1), new Response("slow down", { status: 429 }), status("ready"), ok()]); const response = await h.post(); assert.equal(response.status, 200); - assert.deepEqual(h.sleeps, [2000, 1000]); + assert.deepEqual(h.sleeps, [5000, 1000]); }); test("reports only changes of place or of being in line", async () => { @@ -562,7 +562,7 @@ test("backs off on poll failures without changing the id", async () => { ]); const response = await h.post(); assert.equal(response.status, 200); - assert.deepEqual(h.sleeps, [2000, 1000, 2000, 2000]); + assert.deepEqual(h.sleeps, [5000, 1000, 2000, 2000]); const polls = new Set( h.calls .filter((call) => call.method === "GET") @@ -572,14 +572,16 @@ test("backs off on poll failures without changing the id", async () => { }); test("gives up once polling has failed for the whole budget", async () => { - const failures: Reply[] = Array.from({ length: 20 }, () => new Response("down", { status: 502 })); - const h = harness([queued(1), ...failures], { budgetMs: 10_000 }); + const failures: Reply[] = Array.from({ length: 4 }, () => new Response("down", { status: 502 })); + const h = harness([queued(1), ...failures, new Response("{}", { status: 200 })], { budgetMs: 10_000 }); const response = await h.post(); assert.equal(response.status, 410); const body = (await response.json()) as { error: { message: string } }; assert.match(body.error.message, /HTTP 502/u); - // 2000 + 1000 + 2000 + 4000 + 8000 >= 10000 since the last success. - assert.deepEqual(h.sleeps, [2000, 1000, 2000, 4000, 8000]); + // 5000 + 1000 + 2000 + 4000 >= 10000 since the last success. + assert.deepEqual(h.sleeps, [5000, 1000, 2000, 4000]); + // This side stopped waiting, so it releases the place. + assertCancel(h.calls.at(-1)); assert.equal(h.states.at(-1), null); }); @@ -619,36 +621,6 @@ test("ignores the SDK's own attempt timeout while waiting in line", async () => ); }); -test("switch: the environment wins, then settings, and the queue is on otherwise", () => { - const resolve = resolveStepModelQueueEnabled; - // Neither the environment nor a setting decides: on, whatever the host. - assert.deepEqual(resolve({ env: {} }), { enabled: true, source: "default" }); - // An explicit setting turns it off, or on. - assert.deepEqual(resolve({ env: {}, settings: { modelQueue: false } }), { - enabled: false, - source: "settings", - }); - assert.deepEqual(resolve({ env: {}, settings: { modelQueue: true } }), { - enabled: true, - source: "settings", - }); - // The environment beats the setting. - assert.deepEqual(resolve({ env: { STEPCODE_MODEL_QUEUE: "1" }, settings: { modelQueue: false } }), { - enabled: true, - source: "env", - }); - assert.deepEqual(resolve({ env: { STEPCODE_MODEL_QUEUE: "0" }, settings: { modelQueue: true } }), { - enabled: false, - source: "env", - }); - // An unrecognized value is no override. - assert.deepEqual(resolve({ env: { STEPCODE_MODEL_QUEUE: "maybe" }, settings: { modelQueue: false } }), { - enabled: false, - source: "settings", - }); - assert.deepEqual(resolve({ env: { STEPCODE_MODEL_QUEUE: "maybe" } }), { enabled: true, source: "default" }); -}); - function factoryRequest(provider: string, baseUrl = "https://api.stepfun.com/step_plan/v1"): ModelFetchRequest { return { model: { provider, baseUrl } as ModelFetchRequest["model"], @@ -660,32 +632,14 @@ function factoryRequest(provider: string, baseUrl = "https://api.stepfun.com/ste }; } -test("the factory wraps every model's requests only with the switch on", () => { - let settings: { modelQueue?: boolean } = { modelQueue: false }; - const factory = createStepModelQueueFactory({ env: {}, settings: () => settings }); - assert.equal(factory(factoryRequest("step")), undefined); - // Read per request: turning it on applies to the next one. - settings = { modelQueue: true }; +test("the factory wraps every model's requests: there is no client switch", () => { + const factory = createStepModelQueueFactory(); assert.equal(typeof factory(factoryRequest("step")), "function"); assert.equal(typeof factory(factoryRequest("my-gateway")), "function"); - // Unset is on; the environment can still turn it off. - assert.equal( - typeof createStepModelQueueFactory({ env: {}, settings: () => undefined })(factoryRequest("step")), - "function", - ); - assert.equal( - createStepModelQueueFactory({ env: { STEPCODE_MODEL_QUEUE: "0" }, settings: () => undefined })( - factoryRequest("step"), - ), - undefined, - ); }); test("the request host decides, not the provider: a custom provider at Step's host queues, elsewhere it does not", async () => { - const factory = createStepModelQueueFactory( - { env: {}, settings: () => ({ modelQueue: true }) }, - { queueId: () => "id", sleep: async () => {} }, - ); + const factory = createStepModelQueueFactory({ queueId: () => "id", sleep: async () => {} }); const seen: string[] = []; const replies = [queued(4), status("ready"), ok(), queued(4)]; const wrapped = factory({ @@ -770,3 +724,73 @@ test("a hanging cancel ends within its own bound", async () => { const elapsed = Date.now() - started; assert.ok(elapsed >= 900 && elapsed < 3_000, `cancel bound: ${elapsed}ms`); }); + +test("polls every 5s when the server names no interval, and at the server's interval when it does", async () => { + const h = harness([ + queued(3), + status("waiting", { position: 2, retry_after_ms: 0 }), + status("waiting", { position: 1, retry_after_ms: 1200 }), + status("ready"), + ok(), + ]); + const response = await h.post(); + assert.equal(response.status, 200); + // No Retry-After-Ms on the queued answer, 0 on the next status (no interval named), then 1200; ready resends at once. + assert.deepEqual(h.sleeps, [5000, 5000, 1200]); +}); + +test("a server interval above the bound is capped", async () => { + const h = harness([queued(1, 600_000), status("ready"), ok()]); + await h.post(); + assert.deepEqual(h.sleeps, [30_000]); +}); + +test("waits in line 20 minutes at most in all, then releases the place and ends with wait_timeout", async () => { + const waiting = () => status("waiting", { position: 9, retry_after_ms: 30_000 }); + const polls: Reply[] = Array.from({ length: 40 }, waiting); + const h = harness([queued(9, 30_000), ...polls, new Response("{}", { status: 200 })]); + const response = await h.post(); + assert.equal(response.status, 410); + assert.equal(response.headers.get("x-should-retry"), "false"); + const body = (await response.json()) as { error: { type: string; reason: string } }; + assert.equal(body.error.type, "queue_closed"); + assert.equal(body.error.reason, "wait_timeout"); + assert.equal( + h.sleeps.reduce((sum, ms) => sum + ms, 0), + 20 * 60_000, + ); + assertCancel(h.calls.at(-1)); + assert.deepEqual(h.exits.at(-1), { closedReason: "wait_timeout" }); +}); + +test("the wait bound spans resends that are queued again", async () => { + const h = harness( + [queued(2, 400), status("ready"), queued(1, 400), status("ready"), queued(1, 400), new Response("{}")], + { + maxWaitMs: 1000, + }, + ); + const response = await h.post(); + assert.equal(response.status, 410); + // 400 + 400 + 200: the bound counts from the first queued answer, not from each resend. + assert.deepEqual(h.sleeps, [400, 400, 200]); + assertCancel(h.calls.at(-1)); +}); + +test("an unexpected status answer ends the wait and releases the place", async () => { + const h = harness([queued(1), new Response("teapot", { status: 418 }), new Response("{}")]); + const response = await h.post(); + assert.equal(response.status, 410); + assert.match(((await response.json()) as { error: { message: string } }).error.message, /HTTP 418/u); + assertCancel(h.calls.at(-1)); +}); + +test("a place the server closed is not cancelled again", async () => { + const h = harness([queued(1), status("closed", { reason: "queue_full" })]); + const response = await h.post(); + assert.equal(response.status, 410); + assert.equal( + h.calls.some((call) => call.url.endsWith("/cancel")), + false, + ); +}); diff --git a/packages/coding-agent/test/step-slash-commands.test.ts b/packages/coding-agent/test/step-slash-commands.test.ts index 6aa19ddef..e05e2a0a0 100644 --- a/packages/coding-agent/test/step-slash-commands.test.ts +++ b/packages/coding-agent/test/step-slash-commands.test.ts @@ -191,8 +191,16 @@ describe("Step Pi slash command adapters", () => { // Nothing is appended to the session: no custom message, no agent turn. expect(sendMessage).not.toHaveBeenCalled(); expect(complete).toHaveBeenCalledOnce(); - const [, sent] = complete.mock.calls[0] as [unknown, { systemPrompt: string; messages: unknown[] }]; + const [, sent, sentOptions] = complete.mock.calls[0] as [ + unknown, + { systemPrompt: string; messages: unknown[] }, + { headers?: Record; fetch?: unknown }, + ]; expect(sent.systemPrompt).toBe("SYSTEM"); + // A side question reaches Step's API like a conversation turn: client identity and the request queue. + expect(sentOptions.headers?.["x-step-client"]).toBeTruthy(); + expect(sentOptions.headers?.["x-step-client-version"]).toMatch(/^\d+\.\d+\.\d+/u); + expect(typeof sentOptions.fetch).toBe("function"); // The dangling tool call is gone; the question is the last message. expect(sent.messages).toHaveLength(2); expect(JSON.stringify(sent.messages.at(-1))).toContain("eta on the deploy?"); diff --git a/packages/coding-agent/test/step-trace-headers.test.ts b/packages/coding-agent/test/step-trace-headers.test.ts index 12f2deeab..16171ca19 100644 --- a/packages/coding-agent/test/step-trace-headers.test.ts +++ b/packages/coding-agent/test/step-trace-headers.test.ts @@ -7,6 +7,7 @@ import { resolveStepTraceAllowlist, resolveStepTraceHeaderBaseUrls, } from "../src/step/trace-headers.ts"; +import { STEPCODE_VERSION } from "../src/step/version.ts"; function decode(value: string): string { const mode = value.slice(0, 3); @@ -64,17 +65,20 @@ describe("Step trace headers", () => { it("replaces client case variants without adding trace fields for untrusted URLs", () => { const headers: Record = { "X-Step-Client": "stale", + "X-Step-Client-Version": "0.0.1", "x-step-session-id": "stale-session", accept: "application/json", }; applyStepTraceHeaders(headers, trace, { clientType: " stepcode-desktop ", + clientVersion: " 1.4.0 ", requestUrl: "https://other.example/v1/messages", allowedBaseUrls: ["https://allowed.example/v1"], }); expect(headers).toEqual({ "x-step-client": "stepcode-desktop", + "x-step-client-version": "1.4.0", "x-step-session-id": "stale-session", accept: "application/json", }); @@ -86,7 +90,14 @@ describe("Step trace headers", () => { requestUrl: "https://collector.example/v1/messages", allowedBaseUrls: [], }); - expect(headers).toEqual({ "x-step-client": "stepcode-cli" }); + expect(headers).toEqual({ "x-step-client": "stepcode-cli", "x-step-client-version": STEPCODE_VERSION.value }); + }); + + it("names the Step product version by default", () => { + const headers: Record = {}; + applyStepTraceHeaders(headers, trace); + expect(headers["x-step-client-version"]).toBe(STEPCODE_VERSION.value); + expect(headers["x-step-client-version"]).toMatch(/^\d+\.\d+\.\d+/u); }); it("matches only a complete URL prefix", () => { diff --git a/packages/coding-agent/test/subagent-child-env.test.ts b/packages/coding-agent/test/subagent-child-env.test.ts index a77f2d9a1..49e568530 100644 --- a/packages/coding-agent/test/subagent-child-env.test.ts +++ b/packages/coding-agent/test/subagent-child-env.test.ts @@ -21,7 +21,6 @@ import { resolveSubagentTurnIdleTimeoutMs, } from "../src/features/subagent/rpc-adapter.ts"; import { WORKFLOW_ACL_ENV } from "../src/features/workflow/acl-extension.ts"; -import { resolveStepModelQueueEnabled } from "../src/step/model-queue.ts"; const agent: StepAgentConfig = { name: "general", @@ -266,22 +265,3 @@ test("the wall-clock limit ends a turn even while the child keeps streaming", as process.argv[1] = originalArgv1; } }, 20_000); - -// A child agent decides the model request queue from its own environment: the -// queue is on unless the parent's environment says otherwise, and an override -// reaches the child unchanged. -test("an rpc child inherits the queue switch, and queues by default without one", () => { - vi.stubEnv("STEPCODE_MODEL_QUEUE", ""); - const defaultChild = buildSubagentChildEnv(runInput()); - expect(resolveStepModelQueueEnabled({ env: defaultChild })).toEqual({ enabled: true, source: "default" }); - // A user setting the child reads from the same config still turns it off. - expect(resolveStepModelQueueEnabled({ env: defaultChild, settings: { modelQueue: false } }).enabled).toBe(false); - - vi.stubEnv("STEPCODE_MODEL_QUEUE", "1"); - const forcedChild = buildSubagentChildEnv(runInput()); - expect(forcedChild.STEPCODE_MODEL_QUEUE).toBe("1"); - expect(resolveStepModelQueueEnabled({ env: forcedChild, settings: { modelQueue: false } })).toEqual({ - enabled: true, - source: "env", - }); -}); From 1bc21a7240b9e0e64a836c5d4fdbd902b0b698e5 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:43:05 +0800 Subject: [PATCH 3/5] feat(step): end a call the server closed, and say whose limit a 429 hit - A 429 with X-StepCode-Queue-State: closed, on the first send or a resend, ends the call with the non-retryable 410 a closed poll gives. A resend the server closed used to go back to the retry policy, which re-entered the line at the tail under a new id. - A 429 with X-StepCode-Limit-Scope keeps its status, codes and headers and gains a leading sentence: the user's own usage limit, or Step's capacity. - Closed reasons and limit scopes are fixed lists shared with the server (StepQueueClosedReason, StepLimitScope). Only reasons a user can act on are named: queue_full, user_limit, max_wait_exceeded; the 20-minute wait on this side reports max_wait_exceeded too. Anything else reads as the generic text. --- .../coding-agent/docs/step-integration.md | 21 ++- packages/coding-agent/src/index.ts | 7 +- packages/coding-agent/src/step/model-queue.ts | 134 ++++++++++++---- .../test/step-model-queue.test.ts | 145 ++++++++++++++++-- 4 files changed, 257 insertions(+), 50 deletions(-) diff --git a/packages/coding-agent/docs/step-integration.md b/packages/coding-agent/docs/step-integration.md index 07de67c01..bd34fd404 100644 --- a/packages/coding-agent/docs/step-integration.md +++ b/packages/coding-agent/docs/step-integration.md @@ -267,14 +267,18 @@ header and no queue. server names none, at most 30s) and on `ready` sends the original bytes again under the same id; a queued answer to the resend keeps polling. One call waits in line at most 20 minutes in all, across resends; past that it ends with the - 410 below, reason `wait_timeout`. + 410 below, reason `max_wait_exceeded`. The stream idle watchdog is held only while polling. -- `closed`, or a status answer of 404 (`not_found`), ends the request with a +- `closed` (a status answer, or a 429 with `X-StepCode-Queue-State: closed` and + the code in `X-StepCode-Queue-Reason` on the first send or a resend), or a + status answer of 404, ends the request with a synthesized HTTP 410 `queue_closed` error carrying `x-should-retry: false`, so no retry re-enters the line under a new id. Its message is readable English - followed by the reason code (`queue_full`, `user_limit`, `lease_expired`, - `max_wait_exceeded`, `not_found`; unknown codes get a generic text), and - `error.reason` keeps the code. A 401 or 403 status answer is returned to the + followed by the reason code. The server names only reasons a user can act on, + a fixed list shared with it (`StepQueueClosedReason`): `queue_full`, + `user_limit`, `max_wait_exceeded`; a place closed for any other reason, or with + a code this client does not know, gets the generic text and no code. + `error.reason` keeps a named code. A 401 or 403 status answer is returned to the caller as it is. A 429 or 5xx status answer, or a network error, is retried with backoff from 1s to 8s; after 30s without a good answer the request ends with the same 410. Any other status answer ends it too. @@ -291,8 +295,11 @@ header and no queue. signals, rpc shutdown, the TUI, a desktop session closing) waits for it before the process exits. A request to a control endpoint is never wrapped or queued, and keeps the queue id it names. -- Any other response, including an ordinary 429, goes back unchanged to the - existing retry policy. +- Any other response, including an ordinary 429, goes back to the existing retry + policy with its status, error codes and headers unchanged. A 429 carrying + `X-StepCode-Limit-Scope` gains a leading sentence on whose limit it hit: + `user_quota` (the user's own usage limit) or `upstream_capacity` (Step's + capacity). **Presentation.** Each change of place in line (and entering or leaving it) is a `model_queue` session event (`{ queueId, queue: { position? } | null, diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts index b8d172cf2..5472eb30f 100644 --- a/packages/coding-agent/src/index.ts +++ b/packages/coding-agent/src/index.ts @@ -739,7 +739,12 @@ export { export { ambiguousPluginServerNames, resolveStepMcpServer } from "./step/mcp.ts"; export { describeStepMcpImportOutcome, runStepMcpImportPrompt } from "./step/mcp-import-prompt.ts"; export { hasStoredMcpOAuthCredential, loginMcpServer, logoutMcpServer } from "./step/mcp-oauth.ts"; -export { createStepModelQueueFactory, stepModelQueueStatusText } from "./step/model-queue.ts"; +export { + createStepModelQueueFactory, + type StepLimitScope, + type StepQueueClosedReason, + stepModelQueueStatusText, +} from "./step/model-queue.ts"; export { resolveStepLoginProfiles } from "./step/onboarding.ts"; export { AUTO_RESUME_PROMPT, diff --git a/packages/coding-agent/src/step/model-queue.ts b/packages/coding-agent/src/step/model-queue.ts index b8d46e9ff..56e3eea47 100644 --- a/packages/coding-agent/src/step/model-queue.ts +++ b/packages/coding-agent/src/step/model-queue.ts @@ -15,8 +15,9 @@ import type { ModelFetch, ModelFetchFactory, ModelFetchRequest, ModelQueueState * (`GET https://api.stepfun.com/stepcode/v1/queue`, or `api.stepfun.ai` * overseas, naming the place in `X-StepCode-Queue-ID`), and once the place is * `ready` sends the original bytes again under the same id. The poll interval is - * the server's `retry_after_ms` (5 s when it names none). A `closed` place ends - * the call with an error. A call waits in line at most 20 minutes in all; when it + * the server's `retry_after_ms` (5 s when it names none). A `closed` place (a + * poll, or a 429 with `X-StepCode-Queue-State: closed` on the first send or a + * resend) ends the call with an error naming the reason. A call waits in line at most 20 minutes in all; when it * stops waiting on its own side (the caller's stop, that bound, or a status * endpoint that keeps failing) it releases the place with `POST /cancel` * (the id in `X-StepCode-Queue-ID`, no body). A stop before any queued answer @@ -28,13 +29,17 @@ import type { ModelFetch, ModelFetchFactory, ModelFetchRequest, ModelQueueState * POST .../chat/completions -> 200 stream (same id, same body) * * A request to any other host (an endpoint override) is sent as it is, without - * the header. Any other response, including an ordinary 429, is returned - * unchanged so the existing retry policy handles it. + * the header. Any other response, including an ordinary 429, keeps its status, + * codes and headers so the existing retry policy handles it; a 429 carrying + * `X-StepCode-Limit-Scope` only gains a leading sentence on whose limit it hit + * (the user's own quota, or Step's capacity). */ const QUEUE_ID_HEADER = "x-stepcode-queue-id"; const STATE_HEADER = "x-stepcode-queue-state"; const POSITION_HEADER = "x-stepcode-queue-position"; +const REASON_HEADER = "x-stepcode-queue-reason"; +const LIMIT_SCOPE_HEADER = "x-stepcode-limit-scope"; const RETRY_AFTER_HEADER = "retry-after-ms"; /** Request headers that describe the model request's body; the control requests carry their own. */ const BODY_HEADERS = new Set(["content-length", "content-type", "content-encoding", "transfer-encoding", "accept"]); @@ -64,21 +69,44 @@ const CANCEL_TIMEOUT_MS = 1_000; /** Status of the synthesized response that ends a queued call: no SDK or session retry re-enters the queue. */ const QUEUE_ENDED_STATUS = 410; -/** Readable text for the server's stable `closed` reason codes; unknown codes read as the generic text. */ -const CLOSED_REASON_TEXT: Readonly> = { +/** + * Why a place in line ended, as Step names it (`X-StepCode-Queue-Reason` on a generation answer, `reason` in a + * status answer). A fixed list shared with the server: only reasons a user can act on are named; any other + * closed place carries no reason and reads as the generic text. A wait this side gives up after 20 minutes is + * `max_wait_exceeded` as well. + */ +export type StepQueueClosedReason = "queue_full" | "user_limit" | "max_wait_exceeded"; + +/** Whose limit a throttled Step request hit (`X-StepCode-Limit-Scope`). A fixed list shared with the server. */ +export type StepLimitScope = "user_quota" | "upstream_capacity"; + +/** Readable text for every reason the server names; a new reason fails to compile until it has its text. */ +const CLOSED_REASON_TEXT: Readonly> = { queue_full: "The request queue is full. Try again later.", user_limit: "You have too many requests waiting in line. Wait for them to finish and try again.", - lease_expired: "Your place in line expired. Send the request again.", max_wait_exceeded: "The request waited in line too long. Try again later.", - wait_timeout: "The request waited in line too long. Try again later.", - not_found: "Your place in line no longer exists. Send the request again.", }; -const CLOSED_GENERIC_TEXT = "The request queue closed this request. Try again later."; +/** What a throttled Step request ran into, by the server's limit scope; leads the server's own message. */ +const LIMIT_SCOPE_TEXT: Readonly> = { + user_quota: "Your Step usage limit was reached.", + upstream_capacity: "Step is at capacity right now.", +}; +const CLOSED_GENERIC_TEXT = "The request left the queue. Send it again."; + +/** A reason off the wire, or undefined for an absent or unknown one (read as the generic text). */ +function closedReasonFrom(value: unknown): StepQueueClosedReason | undefined { + const code = typeof value === "string" ? value.trim().toLowerCase() : ""; + return Object.hasOwn(CLOSED_REASON_TEXT, code) ? (code as StepQueueClosedReason) : undefined; +} + +function limitScopeFrom(value: unknown): StepLimitScope | undefined { + const scope = typeof value === "string" ? value.trim().toLowerCase() : ""; + return Object.hasOwn(LIMIT_SCOPE_TEXT, scope) ? (scope as StepLimitScope) : undefined; +} -/** The message for a `closed` reason code, keeping the code itself for diagnosis. */ -export function stepModelQueueClosedMessage(reason: string): string { - const text = Object.hasOwn(CLOSED_REASON_TEXT, reason) ? CLOSED_REASON_TEXT[reason] : CLOSED_GENERIC_TEXT; - return reason ? `${text} (${reason})` : text; +/** The message for a closed place, keeping the reason code itself for diagnosis. */ +export function stepModelQueueClosedMessage(reason?: StepQueueClosedReason): string { + return reason ? `${CLOSED_REASON_TEXT[reason]} (${reason})` : CLOSED_GENERIC_TEXT; } /** The status line for a request waiting in line: its position, never a wait estimate. */ @@ -138,8 +166,50 @@ function pollInterval(value: unknown): number { return ms === undefined || ms === 0 ? DEFAULT_POLL_INTERVAL_MS : Math.min(ms, MAX_POLL_INTERVAL_MS); } +function queueState(response: Response): string | undefined { + return response.status === 429 ? response.headers.get(STATE_HEADER)?.trim().toLowerCase() : undefined; +} + function isQueued(response: Response): boolean { - return response.status === 429 && response.headers.get(STATE_HEADER)?.trim().toLowerCase() === "waiting"; + return queueState(response) === "waiting"; +} + +function isClosed(response: Response): boolean { + return queueState(response) === "closed"; +} + +/** + * A Step answer that is not a queued one. A place the server closed ends the call like a closed poll; any + * other throttled answer keeps its status, codes and headers (so the retry policy sees what it always saw) + * and only gains a leading sentence on whose limit it hit. + */ +async function settle(response: Response): Promise { + if (isClosed(response)) { + await response.body?.cancel().catch(() => {}); + return queueEnded(closedReasonFrom(response.headers.get(REASON_HEADER))); + } + return await withLimitScope(response); +} + +async function withLimitScope(response: Response): Promise { + const scope = response.status === 429 ? limitScopeFrom(response.headers.get(LIMIT_SCOPE_HEADER)) : undefined; + if (!scope) return response; + const text = await response.text(); + let body: unknown; + try { + body = JSON.parse(text); + } catch { + body = undefined; + } + const error = body && typeof body === "object" ? Reflect.get(body, "error") : undefined; + const message = error && typeof error === "object" ? Reflect.get(error, "message") : undefined; + const headers = new Headers(response.headers); + headers.delete("content-length"); + headers.delete("content-encoding"); + if (typeof message !== "string") + return new Response(text, { status: response.status, statusText: response.statusText, headers }); + Reflect.set(error as object, "message", `${LIMIT_SCOPE_TEXT[scope]} ${message}`); + return new Response(JSON.stringify(body), { status: response.status, statusText: response.statusText, headers }); } /** The cancellation to throw: always an Error, as callers and SDKs test `instanceof Error`. */ @@ -167,7 +237,8 @@ function defaultSleep(ms: number, signal: AbortSignal): Promise { }); } -function queueEnded(message: string, reason?: string): Response { +/** The 410 that ends a call; the message is the closed text unless this side names its own failure. */ +function queueEnded(reason?: StepQueueClosedReason, message = stepModelQueueClosedMessage(reason)): Response { return new Response( JSON.stringify({ error: { message, type: "queue_closed", code: "queue_closed", ...(reason ? { reason } : {}) } }), { @@ -181,7 +252,7 @@ interface QueueStatus { readonly state: "waiting" | "ready" | "closed"; readonly position?: number; readonly retryAfterMs: number; - readonly reason: string; + readonly reason?: StepQueueClosedReason; } function readQueueStatus(value: unknown): QueueStatus | undefined { @@ -193,7 +264,7 @@ function readQueueStatus(value: unknown): QueueStatus | undefined { state, position: nonNegativeInteger(Reflect.get(value, "position")), retryAfterMs: pollInterval(Reflect.get(value, "retry_after_ms")), - reason: typeof reason === "string" ? reason : "", + reason: closedReasonFrom(reason), }; } @@ -274,7 +345,7 @@ export function createStepModelQueueFetch( // A stop during the first send is the caller's alone: nothing says the server // queued the call, and if it did, its lease ends the place. const first = await send(attempt); - if (!isQueued(first)) return first; + if (!isQueued(first)) return await settle(first); // From here the call holds a place in line until it settles, and a stop must // release it: the settlement is a teardown the disposing session awaits. let settled = () => {}; @@ -300,7 +371,7 @@ export function createStepModelQueueFetch( await first.body?.cancel().catch(() => {}); // Reports go out only when the place in line or being in line changes. let reported: { readonly queued: boolean; readonly position?: number } = { queued: false }; - const publish = (queued: boolean, closedReason?: string) => { + const publish = (queued: boolean, closedReason?: StepQueueClosedReason) => { const next: { readonly queued: boolean; readonly position?: number } = queued ? { queued, ...(position === undefined ? {} : { position }) } : { queued }; @@ -317,12 +388,12 @@ export function createStepModelQueueFetch( } }; publish(true); - let closedReason: string | undefined; + let closedReason: StepQueueClosedReason | undefined; // This side stops waiting: release the place, then end the call like a closed one. - const giveUp = async (message: string, reason?: string): Promise => { + const giveUp = async (reason?: StepQueueClosedReason, message?: string): Promise => { closedReason = reason; await leave(); - return queueEnded(message, reason); + return queueEnded(reason, message); }; // One bound for the whole wait, across every resend that is queued again. const deadline = now() + maxWaitMs; @@ -332,7 +403,7 @@ export function createStepModelQueueFetch( let lastFailure = ""; for (;;) { const remaining = deadline - now(); - if (remaining <= 0) return await giveUp(stepModelQueueClosedMessage("wait_timeout"), "wait_timeout"); + if (remaining <= 0) return await giveUp("max_wait_exceeded"); // The SDK's per-attempt signal also carries its request timeout, which // must not end a wait in line: only the caller's cancellation does. await sleep(Math.min(delay, remaining), caller); @@ -353,11 +424,11 @@ export function createStepModelQueueFetch( } else { await response.body?.cancel().catch(() => {}); // The place is gone: the same as a closed place. - if (response.status === 404) status = { state: "closed", retryAfterMs: delay, reason: "not_found" }; + if (response.status === 404) status = { state: "closed", retryAfterMs: delay }; // A throttled or failing status endpoint is retried; other answers // cannot improve by asking again. else if (response.status !== 429 && response.status < 500) - return await giveUp(`Queue status request failed with HTTP ${response.status}`); + return await giveUp(undefined, `Queue status request failed with HTTP ${response.status}`); else lastFailure = `HTTP ${response.status}`; } } catch (error) { @@ -366,7 +437,7 @@ export function createStepModelQueueFetch( } if (!status) { if (now() - lastSuccess >= failureBudgetMs) - return await giveUp(`Queue status unavailable: ${lastFailure}`); + return await giveUp(undefined, `Queue status unavailable: ${lastFailure}`); delay = Math.min(FIRST_POLL_BACKOFF_MS * 2 ** failures, MAX_POLL_BACKOFF_MS); failures++; continue; @@ -376,7 +447,7 @@ export function createStepModelQueueFetch( delay = status.retryAfterMs; if (status.state === "closed") { closedReason = status.reason; - return queueEnded(stepModelQueueClosedMessage(status.reason), status.reason); + return queueEnded(status.reason); } if (status.state === "waiting") { position = status.position ?? position; @@ -387,7 +458,12 @@ export function createStepModelQueueFetch( // abort it already carries is its request timeout expiring in line. unhold(); const response = await send(attempt && !attempt.aborted ? AbortSignal.any([caller, attempt]) : caller); - if (!isQueued(response)) return response; + if (!isQueued(response)) { + // The server closed the place on the resend (the wait bound, say): end the call, never re-enter + // the line under a new id through a retry. + if (isClosed(response)) closedReason = closedReasonFrom(response.headers.get(REASON_HEADER)); + return await settle(response); + } hold(); position = nonNegativeInteger(response.headers.get(POSITION_HEADER)) ?? position; delay = pollInterval(response.headers.get(RETRY_AFTER_HEADER)); diff --git a/packages/coding-agent/test/step-model-queue.test.ts b/packages/coding-agent/test/step-model-queue.test.ts index 724d80149..b036223d3 100644 --- a/packages/coding-agent/test/step-model-queue.test.ts +++ b/packages/coding-agent/test/step-model-queue.test.ts @@ -4,6 +4,7 @@ import type { ModelFetchRequest, ModelQueueExit, ModelQueueState } from "../src/ import { createStepModelQueueFactory, createStepModelQueueFetch, + type StepQueueClosedReason, stepModelQueueClosedMessage, stepModelQueueStatusText, } from "../src/step/model-queue.ts"; @@ -286,6 +287,103 @@ test("passes an ordinary 429 through to the existing retry policy", async () => assert.deepEqual(h.states, []); }); +function closed(reason?: string): Response { + const headers = new Headers({ "X-StepCode-Queue-State": "closed", "content-type": "application/json" }); + if (reason !== undefined) headers.set("X-StepCode-Queue-Reason", reason); + const message = `Rate limit reached, please try again later.${reason ? ` (${reason})` : ""}`; + return new Response(JSON.stringify({ error: { message, type: "rate_limited" } }), { status: 429, headers }); +} + +function limited(scope: string, message = "Rate limit reached, please try again later."): Response { + return new Response(JSON.stringify({ error: { message, type: "rate_limited" } }), { + status: 429, + headers: { "content-type": "application/json", "retry-after": "3", "X-StepCode-Limit-Scope": scope }, + }); +} + +test("a place the server closes on the first send ends the call, without polling or a cancel", async () => { + const h = harness([closed("queue_full")]); + const response = await h.post(); + assert.equal(response.status, 410); + assert.equal(response.headers.get("x-should-retry"), "false"); + const body = (await response.json()) as { error: { message: string; code: string; reason: string } }; + assert.equal(body.error.code, "queue_closed"); + assert.equal(body.error.reason, "queue_full"); + assert.equal(body.error.message, "The request queue is full. Try again later. (queue_full)"); + assert.equal(h.calls.length, 1); + // Never in line: no queue events, no watchdog hold. + assert.deepEqual(h.states, []); + assert.equal(h.holds(), 0); +}); + +test("a closed first send without a reason still ends the call with the generic text", async () => { + const h = harness([closed()]); + const response = await h.post(); + assert.equal(response.status, 410); + const body = (await response.json()) as { error: { message: string; reason?: string } }; + assert.equal(body.error.message, stepModelQueueClosedMessage()); + assert.equal(body.error.reason, undefined); +}); + +test("a place closed on the resend ends the call instead of re-entering the line under a new id", async () => { + const h = harness([queued(1), status("ready"), closed("max_wait_exceeded")]); + const response = await h.post(); + assert.equal(response.status, 410); + const body = (await response.json()) as { error: { reason: string } }; + assert.equal(body.error.reason, "max_wait_exceeded"); + assert.deepEqual(h.exits, [{ closedReason: "max_wait_exceeded" }]); + // The server closed the place itself: no cancel goes out. + assert.deepEqual( + h.calls.map((call) => `${call.method} ${new URL(call.url).pathname}`), + ["POST /step_plan/v1/chat/completions", "GET /stepcode/v1/queue", "POST /step_plan/v1/chat/completions"], + ); + assert.equal(h.released(), 1); +}); + +for (const [scope, lead] of [ + ["user_quota", "Your Step usage limit was reached."], + ["upstream_capacity", "Step is at capacity right now."], +] as const) { + test(`a ${scope} 429 keeps its status, codes and headers and names whose limit it hit`, async () => { + const h = harness([limited(scope, "rpm exceeded")]); + const response = await h.post(); + assert.equal(response.status, 429); + assert.equal(response.headers.get("retry-after"), "3"); + assert.equal(response.headers.get("x-stepcode-limit-scope"), scope); + const body = (await response.json()) as { error: { message: string; type: string } }; + assert.equal(body.error.type, "rate_limited"); + assert.equal(body.error.message, `${lead} rpm exceeded`); + assert.deepEqual(h.states, []); + }); +} + +test("a limit scope on a resend names whose limit it hit as well", async () => { + const h = harness([queued(1), status("ready"), limited("upstream_capacity")]); + const response = await h.post(); + assert.equal(response.status, 429); + const body = (await response.json()) as { error: { message: string } }; + assert.match(body.error.message, /^Step is at capacity right now\. /u); + assert.deepEqual(h.exits, [undefined]); +}); + +test("an unknown limit scope or a body without a message passes through as it is", async () => { + const unknown = harness([limited("something_new")]); + assert.equal( + ((await (await unknown.post()).json()) as { error: { message: string } }).error.message, + "Rate limit reached, please try again later.", + ); + const plain = harness([ + new Response("busy", { + status: 429, + headers: { "X-StepCode-Limit-Scope": "upstream_capacity", "retry-after": "1" }, + }), + ]); + const response = await plain.post(); + assert.equal(response.status, 429); + assert.equal(response.headers.get("retry-after"), "1"); + assert.equal(await response.text(), "busy"); +}); + test("waits in line, then resends the same bytes under the same id", async () => { const h = harness([ queued(3, 1500), @@ -402,13 +500,22 @@ test("ends with a non-retryable, readable error that keeps the reason code when assert.equal(h.released(), 1); }); -test("a status answer of 404 closes the place as not_found", async () => { +test("a status answer of 404 closes the place, with no reason to name", async () => { const h = harness([queued(1), new Response("gone", { status: 404 })]); const response = await h.post(); assert.equal(response.status, 410); - const body = (await response.json()) as { error: { reason: string } }; - assert.equal(body.error.reason, "not_found"); - assert.deepEqual(h.exits, [{ closedReason: "not_found" }]); + const body = (await response.json()) as { error: { message: string; reason?: string } }; + assert.equal(body.error.reason, undefined); + assert.equal(body.error.message, stepModelQueueClosedMessage()); + assert.deepEqual(h.exits, [undefined]); +}); + +test("a closed status answer with a reason the client does not know reads as the generic text", async () => { + const h = harness([queued(1), status("closed", { reason: "lease_expired" })]); + const response = await h.post(); + const body = (await response.json()) as { error: { message: string; reason?: string } }; + assert.equal(body.error.reason, undefined); + assert.equal(body.error.message, stepModelQueueClosedMessage()); }); test("a status answer of 401 or 403 goes back to the caller as it is", async () => { @@ -442,20 +549,32 @@ test("reports only changes of place or of being in line", async () => { assert.deepEqual(h.states, [{ position: 2 }, { position: 1 }, null]); }); -test("names every closed reason code in readable text, generic for unknown codes", () => { - const codes = ["queue_full", "user_limit", "lease_expired", "max_wait_exceeded", "not_found"]; - const generic = stepModelQueueClosedMessage(""); +test("names every reason the server names in readable text, generic without one", () => { + // The wire values are a contract shared with the server: this list is pinned word for word. + const codes: StepQueueClosedReason[] = ["queue_full", "user_limit", "max_wait_exceeded"]; + const generic = stepModelQueueClosedMessage(); const texts = codes.map((code) => stepModelQueueClosedMessage(code)); for (const [index, text] of texts.entries()) { assert.equal(text.endsWith(` (${codes[index]})`), true); - assert.equal(text.startsWith(generic), false); + assert.notEqual(text, generic); } assert.equal(new Set(texts).size, codes.length); - assert.equal(stepModelQueueClosedMessage("brand_new_reason"), `${generic} (brand_new_reason)`); - assert.equal(stepModelQueueClosedMessage("toString"), `${generic} (toString)`); assert.equal(stepModelQueueClosedMessage("queue_full"), "The request queue is full. Try again later. (queue_full)"); }); +test("a closed first send with a reason the client does not know, or a prototype key, reads as the generic text", async () => { + for (const reason of ["brand_new_reason", "toString", "QUEUE_FULL "]) { + const h = harness([closed(reason)]); + const body = (await (await h.post()).json()) as { error: { message: string; reason?: string } }; + if (reason === "QUEUE_FULL ") { + assert.equal(body.error.reason, "queue_full"); + continue; + } + assert.equal(body.error.reason, undefined); + assert.equal(body.error.message, stepModelQueueClosedMessage()); + } +}); + test("a stop always surfaces as an Error", async () => { const h = harness([ queued(1), @@ -745,7 +864,7 @@ test("a server interval above the bound is capped", async () => { assert.deepEqual(h.sleeps, [30_000]); }); -test("waits in line 20 minutes at most in all, then releases the place and ends with wait_timeout", async () => { +test("waits in line 20 minutes at most in all, then releases the place and ends as max_wait_exceeded", async () => { const waiting = () => status("waiting", { position: 9, retry_after_ms: 30_000 }); const polls: Reply[] = Array.from({ length: 40 }, waiting); const h = harness([queued(9, 30_000), ...polls, new Response("{}", { status: 200 })]); @@ -754,13 +873,13 @@ test("waits in line 20 minutes at most in all, then releases the place and ends assert.equal(response.headers.get("x-should-retry"), "false"); const body = (await response.json()) as { error: { type: string; reason: string } }; assert.equal(body.error.type, "queue_closed"); - assert.equal(body.error.reason, "wait_timeout"); + assert.equal(body.error.reason, "max_wait_exceeded"); assert.equal( h.sleeps.reduce((sum, ms) => sum + ms, 0), 20 * 60_000, ); assertCancel(h.calls.at(-1)); - assert.deepEqual(h.exits.at(-1), { closedReason: "wait_timeout" }); + assert.deepEqual(h.exits.at(-1), { closedReason: "max_wait_exceeded" }); }); test("the wait bound spans resends that are queued again", async () => { From 3001ee7171a09c1beede3805838ddfc761d921e8 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:33:47 +0800 Subject: [PATCH 4/5] feat(step): report an admitted place in line instead of dropping the row - A queued call now reports its phase, not just its place: `waiting` while it waits, `ready` once the server admitted it and the same bytes go out again. The resend used to leave the row showing the last place it had, then the row vanished with no way to tell an admitted call from one still in line. - ModelQueueState carries `state` (`ModelQueuePhase`: waiting | ready) and the position only while waiting. Reports go out on a change of either, so an admitted place reaches live consumers and `--include-live-events` streams. - Presentation follows: the TUI status row reads "Starting..." for an admitted place, and `-p` writes it like every other change. --- .../session-events-working-tracker.test.ts | 29 +++++++++---- packages/coding-agent/docs/json.md | 2 +- packages/coding-agent/docs/rpc.md | 2 +- packages/coding-agent/docs/sdk.md | 5 ++- .../coding-agent/docs/step-integration.md | 24 ++++++----- .../coding-agent/src/core/agent-session.ts | 7 ++-- packages/coding-agent/src/core/index.ts | 1 + packages/coding-agent/src/core/model-fetch.ts | 20 +++++---- packages/coding-agent/src/index.ts | 1 + packages/coding-agent/src/step/model-queue.ts | 42 +++++++++++-------- .../test/json-event-projection.test.ts | 2 +- .../test/model-fetch-hook.test.ts | 10 +++-- packages/coding-agent/test/print-mode.test.ts | 20 ++++++--- .../test/step-model-queue-session.test.ts | 3 +- .../test/step-model-queue.test.ts | 36 ++++++++++++---- 15 files changed, 135 insertions(+), 69 deletions(-) diff --git a/apps/cli/test/session-events-working-tracker.test.ts b/apps/cli/test/session-events-working-tracker.test.ts index c2432861e..76522bc8d 100644 --- a/apps/cli/test/session-events-working-tracker.test.ts +++ b/apps/cli/test/session-events-working-tracker.test.ts @@ -251,10 +251,10 @@ test("the queue row covers the current row and gives the same one back when the const compaction = new CompactionStatusIndicator(host.ui(), "threshold", "step"); state.active = compaction; - slot.update("r1", { position: 3 }); + slot.update("r1", { state: "waiting", position: 3 }); expect(state.active).toBeInstanceOf(ModelQueueStatusIndicator); - slot.update("r1", { position: 1 }); - expect(state.active?.render(80).join("\n")).toContain(stepModelQueueStatusText({ position: 1 })); + slot.update("r1", { state: "waiting", position: 1 }); + expect(state.active?.render(80).join("\n")).toContain(stepModelQueueStatusText({ state: "waiting", position: 1 })); slot.update("r1", null); // Not a working row: the compaction row it covered. @@ -262,14 +262,27 @@ test("the queue row covers the current row and gives the same one back when the compaction.dispose(); }); +test("an admitted place reads as starting until the request settles", () => { + initTheme("dark"); + const { state, host } = queueSlotHost(); + const slot = new ModelQueueStatusSlot(host); + + slot.update("r1", { state: "waiting", position: 1 }); + slot.update("r1", { state: "ready" }); + // The place is gone; the request itself is about to run, so the row says so instead of vanishing. + expect(state.active?.render(80).join("\n")).toContain("Starting..."); + slot.update("r1", null); + expect(state.active).toBeUndefined(); +}); + test("one request leaving the line keeps another's queue row", () => { initTheme("dark"); const { state, host } = queueSlotHost(); const slot = new ModelQueueStatusSlot(host); - slot.update("a", { position: 2 }); - slot.update("b", { position: 5 }); + slot.update("a", { state: "waiting", position: 2 }); + slot.update("b", { state: "waiting", position: 5 }); slot.update("a", null); - expect(state.active?.render(80).join("\n")).toContain(stepModelQueueStatusText({ position: 5 })); + expect(state.active?.render(80).join("\n")).toContain(stepModelQueueStatusText({ state: "waiting", position: 5 })); slot.update("b", null); expect(state.active).toBeUndefined(); }); @@ -289,8 +302,8 @@ test("model_queue events reach the queue slot, and agent_end clears it", async ( turnEndedAbnormally: true, redraw: { requestRender: vi.fn() }, } as unknown as RuntimeContext; - await handleSessionEvent(ctx, { type: "model_queue", queueId: "r1", queue: { position: 2 } }); - expect(updateModelQueue).toHaveBeenCalledWith("r1", { position: 2 }); + await handleSessionEvent(ctx, { type: "model_queue", queueId: "r1", queue: { state: "waiting", position: 2 } }); + expect(updateModelQueue).toHaveBeenCalledWith("r1", { state: "waiting", position: 2 }); await handleSessionEvent(ctx, { type: "agent_end", messages: [], willRetry: false }); expect(clearModelQueue).toHaveBeenCalledOnce(); }); diff --git a/packages/coding-agent/docs/json.md b/packages/coding-agent/docs/json.md index fa269be1c..c7e1bf593 100644 --- a/packages/coding-agent/docs/json.md +++ b/packages/coding-agent/docs/json.md @@ -36,7 +36,7 @@ type JsonAgentSessionEvent = | { type: "agent_end"; willRetry: boolean; messageCount: number }; ``` -`queue_update` emits the full pending steering and follow-up queues whenever they change. `model_queue` is a live frame (written only with `--include-live-events`): a model request waits in the model request queue (`{ queueId, queue: { position? } }`), then `queue: null` (with `closedReason` when the server closed its place) when it leaves the line. Text mode (`-p`) writes each change to stderr instead. `compaction_start` and `compaction_end` cover both manual and automatic compaction. +`queue_update` emits the full pending steering and follow-up queues whenever they change. `model_queue` is a live frame (written only with `--include-live-events`): a model request waits in the model request queue (`{ queueId, queue: { state: "waiting", position? } }`), is admitted and about to run (`queue: { state: "ready" }`), then `queue: null` (with `closedReason` when the server closed its place) when it leaves the line. Text mode (`-p`) writes each change to stderr instead. `compaction_start` and `compaction_end` cover both manual and automatic compaction. Other events are the session loop's own [`AgentSessionEvent`](https://github.com/stepfun-ai/step-harness/blob/main/packages/coding-agent/src/core/agent-session.ts), diff --git a/packages/coding-agent/docs/rpc.md b/packages/coding-agent/docs/rpc.md index 4810dd758..45ff6c5d9 100644 --- a/packages/coding-agent/docs/rpc.md +++ b/packages/coding-agent/docs/rpc.md @@ -913,7 +913,7 @@ Events are streamed to stdout as JSON lines during agent operation. Events do no | `queue_update` | Pending steering/follow-up queue changed | | `compaction_start` | Compaction begins | | `compaction_end` | Compaction completes | -| `model_queue` | **Opt-in frame** (`--include-live-events`): a model request waits in the model request queue (`queue.position`), or left it (`queue: null`, with `closedReason` when the server closed its place); carries the call's `queueId`. Subagent parents start their children with this flag, so they receive it | +| `model_queue` | **Opt-in frame** (`--include-live-events`): a model request waits in the model request queue (`queue.state`, `queue.position`) or is admitted and about to run (`queue.state: "ready"`), or left it (`queue: null`, with `closedReason` when the server closed its place); carries the call's `queueId`. Subagent parents start their children with this flag, so they receive it | | `auto_retry_start` | Auto-retry begins (after transient error) | | `auto_retry_end` | Auto-retry completes (success or final failure) | | `summarization_retry_scheduled` | Retry scheduled for a transient compaction or branch-summary summarization error | diff --git a/packages/coding-agent/docs/sdk.md b/packages/coding-agent/docs/sdk.md index 6423b37af..73b2e9f54 100644 --- a/packages/coding-agent/docs/sdk.md +++ b/packages/coding-agent/docs/sdk.md @@ -610,8 +610,9 @@ const { session } = await createAgentSession({ modelFetch }); answer still ends as a stall. Releasing the last hold starts a full idle window. The release function is idempotent. - `reportQueue(queueId, state, exit?)` tells the session that the request - waits in a server-side line (`state`, optionally with `position`) or left it - (`null`, with `exit.closedReason` when the server closed the place). The + waits in a server-side line (`state`, with its `position` while waiting, or + `state: "ready"` once the server admitted it and it is about to run) or left + it (`null`, with `exit.closedReason` when the server closed the place). The session publishes each report as a `model_queue` event: a live frame the TUI presents and `--mode json` / `--mode rpc` write with `--include-live-events`. - `registerTeardown(task)` registers work the request still owes after its diff --git a/packages/coding-agent/docs/step-integration.md b/packages/coding-agent/docs/step-integration.md index bd34fd404..ab45f99c0 100644 --- a/packages/coding-agent/docs/step-integration.md +++ b/packages/coding-agent/docs/step-integration.md @@ -264,8 +264,9 @@ header and no queue. - HTTP 429 with `X-StepCode-Queue-State: waiting` means the request holds a place in line (`X-StepCode-Queue-Position`). The client polls its region's status endpoint every `Retry-After-Ms` (status `retry_after_ms`; 5s when the - server names none, at most 30s) and on `ready` sends the original bytes again - under the same id; a queued answer to the resend keeps polling. One call waits + server names none, at most 30s) and on `ready` reports the new phase and sends + the original bytes again under the same id; a queued answer to the resend + keeps polling. One call waits in line at most 20 minutes in all, across resends; past that it ends with the 410 below, reason `max_wait_exceeded`. The stream idle watchdog is held only while polling. @@ -301,14 +302,17 @@ header and no queue. `user_quota` (the user's own usage limit) or `upstream_capacity` (Step's capacity). -**Presentation.** Each change of place in line (and entering or leaving it) is -a `model_queue` session event (`{ queueId, queue: { position? } | null, -closedReason? }`), a live frame like `message_update`. The TUI covers the status -row with "Queued: position N" while any request waits and restores the covered -row (working, retry or compaction) when the last one leaves; `-p` writes each -change to stderr; `--mode json` / `--mode rpc` write the event with -`--include-live-events`, which subagent parents always pass. The status shows -the place in line only, never a wait estimate. +**Presentation.** Each change of place in line, and each change of phase +(waiting → ready), is a `model_queue` session event (`{ queueId, queue: +{ state: "waiting" | "ready", position? } | null, closedReason? }`), a live +frame like `message_update`. A `ready` place has no position left: the server +admitted the request and it is about to be sent again. The TUI covers the status +row with "Queued: position N" while any request waits, "Starting..." while one +waits for its resend, and restores the covered row (working, retry or +compaction) when the last one leaves; `-p` writes each change to stderr; +`--mode json` / `--mode rpc` write the event with `--include-live-events`, which +subagent parents always pass. The status shows the place in line only, never a +wait estimate. ## Shell command execution diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts index 92c0049d0..fe7fa8cb2 100644 --- a/packages/coding-agent/src/core/agent-session.ts +++ b/packages/coding-agent/src/core/agent-session.ts @@ -226,9 +226,10 @@ export type AgentSessionEvent = | { type: "bash_execution_update"; id?: string; delta: string } | { /** - * A model request waits in a server-side line (`queue`), or left it - * (`queue: null`, with `closedReason` when the server closed its place). - * Reported by the host's model-fetch wrapper. A live frame (see + * A model request is in a server-side line (`queue`: waiting with its + * place, or ready once admitted), or left it (`queue: null`, with + * `closedReason` when the server closed its place). Reported by the + * host's model-fetch wrapper. A live frame (see * `session-event-durability.ts`): records skip it, live consumers and * `--include-live-events` streams (a subagent's parent) receive it. */ diff --git a/packages/coding-agent/src/core/index.ts b/packages/coding-agent/src/core/index.ts index 1e1a4f026..71e04f908 100644 --- a/packages/coding-agent/src/core/index.ts +++ b/packages/coding-agent/src/core/index.ts @@ -92,6 +92,7 @@ export { ModelQueueChannel, type ModelQueueExit, type ModelQueueListener, + type ModelQueuePhase, type ModelQueueState, } from "./model-fetch.ts"; export { diff --git a/packages/coding-agent/src/core/model-fetch.ts b/packages/coding-agent/src/core/model-fetch.ts index c18342dd9..96ef61a28 100644 --- a/packages/coding-agent/src/core/model-fetch.ts +++ b/packages/coding-agent/src/core/model-fetch.ts @@ -3,9 +3,14 @@ import type { Api, Model } from "@step-harness/providers/compat"; /** The HTTP fetch a provider adapter uses for one model request. */ export type ModelFetch = typeof globalThis.fetch; -/** A model request waiting in a server-side line before it runs. */ +/** What a place in a server-side line is doing: waiting for its turn, or admitted and about to run. */ +export type ModelQueuePhase = "waiting" | "ready"; + +/** A model request in a server-side line before it runs. */ export interface ModelQueueState { - /** Place in line, when the server reported one. */ + /** `waiting` for its turn in line, or `ready`: the server admitted the place and the request is about to run. */ + readonly state: ModelQueuePhase; + /** Place in line, when the server reported one. A place that is `ready` has none left. */ readonly position?: number; } @@ -35,11 +40,12 @@ export interface ModelFetchRequest { */ readonly holdIdleWatchdog: () => () => void; /** - * Report that the request waits in a server-side line (`state`), or left it - * (`null`, with `exit.closedReason` when the server closed the place). The - * session publishes each report as a `model_queue` event. `queueId` is the - * wrapper's id for one place in line (an HTTP call it wraps); one model - * request may make several. + * Report that the request waits in a server-side line (`state`: waiting, with + * its place; or ready, once admitted and about to run), or left it (`null`, + * with `exit.closedReason` when the server closed the place). The session + * publishes each report as a `model_queue` event. `queueId` is the wrapper's + * id for one place in line (an HTTP call it wraps); one model request may + * make several. */ readonly reportQueue: ModelQueueListener; /** diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts index 5472eb30f..be312ec06 100644 --- a/packages/coding-agent/src/index.ts +++ b/packages/coding-agent/src/index.ts @@ -264,6 +264,7 @@ export { ModelQueueChannel, type ModelQueueExit, type ModelQueueListener, + type ModelQueuePhase, type ModelQueueState, } from "./core/model-fetch.ts"; export { ModelRegistry } from "./core/model-registry.ts"; diff --git a/packages/coding-agent/src/step/model-queue.ts b/packages/coding-agent/src/step/model-queue.ts index 56e3eea47..e525be0ee 100644 --- a/packages/coding-agent/src/step/model-queue.ts +++ b/packages/coding-agent/src/step/model-queue.ts @@ -25,7 +25,7 @@ import type { ModelFetch, ModelFetchFactory, ModelFetchRequest, ModelQueueState * * POST .../chat/completions -> 429 queued (position 3) * GET (X-StepCode-Queue-ID) -> waiting (position 1) - * GET (X-StepCode-Queue-ID) -> ready + * GET (X-StepCode-Queue-ID) -> ready (reported as `ready`: admitted) * POST .../chat/completions -> 200 stream (same id, same body) * * A request to any other host (an endpoint override) is sent as it is, without @@ -109,8 +109,9 @@ export function stepModelQueueClosedMessage(reason?: StepQueueClosedReason): str return reason ? `${CLOSED_REASON_TEXT[reason]} (${reason})` : CLOSED_GENERIC_TEXT; } -/** The status line for a request waiting in line: its position, never a wait estimate. */ +/** The status line for a request in line: its place while it waits, never a wait estimate; a request the server admitted is starting. */ export function stepModelQueueStatusText(state: ModelQueueState): string { + if (state.state === "ready") return "Starting..."; return state.position !== undefined && state.position > 0 ? `Queued: position ${state.position}` : "Queued"; } @@ -369,25 +370,27 @@ export function createStepModelQueueFetch( let position = nonNegativeInteger(first.headers.get(POSITION_HEADER)); let delay = pollInterval(first.headers.get(RETRY_AFTER_HEADER)); await first.body?.cancel().catch(() => {}); - // Reports go out only when the place in line or being in line changes. - let reported: { readonly queued: boolean; readonly position?: number } = { queued: false }; - const publish = (queued: boolean, closedReason?: StepQueueClosedReason) => { - const next: { readonly queued: boolean; readonly position?: number } = queued - ? { queued, ...(position === undefined ? {} : { position }) } - : { queued }; - if (next.queued === reported.queued && next.position === reported.position) return; + // Reports go out only when what a reader sees changes: being in line, the + // phase (waiting or admitted), and the place in line. + let reported: ModelQueueState | null = null; + const publish = (next: ModelQueueState | null, closedReason?: StepQueueClosedReason) => { + if (next?.state === reported?.state && next?.position === reported?.position) return; reported = next; try { - request.reportQueue( - queueId, - queued ? (position === undefined ? {} : { position }) : null, - ...(closedReason === undefined ? [] : [{ closedReason }]), - ); + request.reportQueue(queueId, next, ...(closedReason === undefined ? [] : [{ closedReason }])); } catch { // Presentation must not change the request. } }; - publish(true); + // Still in line: its place, when the server named one. + const publishWaiting = () => + publish(position === undefined ? { state: "waiting" } : { state: "waiting", position }); + // Admitted: the place in line is gone and the request is about to run. + const publishReady = () => { + position = undefined; + publish({ state: "ready" }); + }; + publishWaiting(); let closedReason: StepQueueClosedReason | undefined; // This side stops waiting: release the place, then end the call like a closed one. const giveUp = async (reason?: StepQueueClosedReason, message?: string): Promise => { @@ -451,9 +454,12 @@ export function createStepModelQueueFetch( } if (status.state === "waiting") { position = status.position ?? position; - publish(true); + publishWaiting(); continue; } + // Admitted: say so before the resend goes out, so a reader sees the + // place turn into a starting request instead of vanishing. + publishReady(); // The SDK's per-attempt signal joins the resend only while it is live: an // abort it already carries is its request timeout expiring in line. unhold(); @@ -468,7 +474,7 @@ export function createStepModelQueueFetch( position = nonNegativeInteger(response.headers.get(POSITION_HEADER)) ?? position; delay = pollInterval(response.headers.get(RETRY_AFTER_HEADER)); void response.body?.cancel().catch(() => {}); - publish(true); + publishWaiting(); } } catch (error) { if (caller.aborted) { @@ -477,7 +483,7 @@ export function createStepModelQueueFetch( } throw error; } finally { - publish(false, closedReason); + publish(null, closedReason); unhold(); settled(); } diff --git a/packages/coding-agent/test/json-event-projection.test.ts b/packages/coding-agent/test/json-event-projection.test.ts index a94a6fe1a..f327d00a2 100644 --- a/packages/coding-agent/test/json-event-projection.test.ts +++ b/packages/coding-agent/test/json-event-projection.test.ts @@ -233,7 +233,7 @@ test("the record is bounded per line even with a large payload", async () => { }); test("a queued model request is a live frame: kept out of records, sent to live-event consumers", () => { - const waiting: AgentSessionEvent = { type: "model_queue", queueId: "r1", queue: { position: 2 } }; + const waiting: AgentSessionEvent = { type: "model_queue", queueId: "r1", queue: { state: "waiting", position: 2 } }; const left: AgentSessionEvent = { type: "model_queue", queueId: "r1", queue: null, closedReason: "queue_full" }; expect(sessionEventDurability(waiting)).toBe("ephemeral"); expect(toJsonEvent(waiting, { includeLiveEvents: false })).toBeUndefined(); diff --git a/packages/coding-agent/test/model-fetch-hook.test.ts b/packages/coding-agent/test/model-fetch-hook.test.ts index 5304eb1fa..db32d8f42 100644 --- a/packages/coding-agent/test/model-fetch-hook.test.ts +++ b/packages/coding-agent/test/model-fetch-hook.test.ts @@ -197,8 +197,9 @@ describe("model fetch hook", () => { const events: AgentSessionEvent[] = []; const last = await runPrompt( (request) => async () => { - request.reportQueue("call-1", { position: 2 }); - request.reportQueue("call-1", {}); + request.reportQueue("call-1", { state: "waiting", position: 2 }); + request.reportQueue("call-1", { state: "waiting" }); + request.reportQueue("call-1", { state: "ready" }); request.reportQueue("call-1", null); return sse("reported"); }, @@ -206,8 +207,9 @@ describe("model fetch hook", () => { ); expect(last.stopReason).toBe("stop"); expect(events.filter((event) => event.type === "model_queue")).toEqual([ - { type: "model_queue", queueId: "call-1", queue: { position: 2 } }, - { type: "model_queue", queueId: "call-1", queue: {} }, + { type: "model_queue", queueId: "call-1", queue: { state: "waiting", position: 2 } }, + { type: "model_queue", queueId: "call-1", queue: { state: "waiting" } }, + { type: "model_queue", queueId: "call-1", queue: { state: "ready" } }, { type: "model_queue", queueId: "call-1", queue: null }, ]); }); diff --git a/packages/coding-agent/test/print-mode.test.ts b/packages/coding-agent/test/print-mode.test.ts index 5d3bd4b73..e31d2e082 100644 --- a/packages/coding-agent/test/print-mode.test.ts +++ b/packages/coding-agent/test/print-mode.test.ts @@ -160,14 +160,19 @@ describe("runPrintMode", () => { }); it("reports each queue report on stderr in text mode in the host's wording, keeping stdout for the answer", async () => { - const run = async (formatModelQueue?: (queue: { position?: number }) => string) => { + const run = async (formatModelQueue?: (queue: { state: "waiting" | "ready"; position?: number }) => string) => { const runtimeHost = createRuntimeHost(createAssistantMessage({ text: "done" })); const { session } = runtimeHost; const stderr = vi.spyOn(console, "error").mockImplementation(() => {}); const stdout = vi.spyOn(process.stdout, "write").mockImplementation(capturedWrite); session.prompt.mockImplementation(async () => { // The wrapper reports changes only, so every report is a line. - for (const queue of [{ position: 2 }, { position: 1 }, null]) { + for (const queue of [ + { state: "waiting" as const, position: 2 }, + { state: "waiting" as const, position: 1 }, + { state: "ready" as const }, + null, + ]) { session.emitToListeners({ type: "model_queue", queueId: "q1", queue }); } }); @@ -186,9 +191,10 @@ describe("runPrintMode", () => { return lines; }; - const formatted = await run((queue) => `waiting at ${queue.position}`); + const formatted = await run((queue) => (queue.state === "ready" ? "starting" : `waiting at ${queue.position}`)); expect(formatted.exitCode).toBe(0); - expect(formatted.stderr).toEqual([["waiting at 2"], ["waiting at 1"]]); + // Each phase is a line: the admitted place starts instead of naming a place it no longer has. + expect(formatted.stderr).toEqual([["waiting at 2"], ["waiting at 1"], ["starting"]]); expect(formatted.stdout).not.toContain("waiting at"); // A host that supplies no wording gets no queue lines. expect((await run()).stderr).toEqual([]); @@ -200,7 +206,8 @@ describe("runPrintMode", () => { const { session } = runtimeHost; const stdout = vi.spyOn(process.stdout, "write").mockImplementation(capturedWrite); session.prompt.mockImplementation(async () => { - session.emitToListeners({ type: "model_queue", queueId: "r1", queue: { position: 3 } }); + session.emitToListeners({ type: "model_queue", queueId: "r1", queue: { state: "waiting", position: 3 } }); + session.emitToListeners({ type: "model_queue", queueId: "r1", queue: { state: "ready" } }); session.emitToListeners({ type: "model_queue", queueId: "r1", queue: null }); }); await runPrintMode(runtimeHost as unknown as Parameters[0], { @@ -219,7 +226,8 @@ describe("runPrintMode", () => { }; expect(await run(false)).toEqual([]); expect(await run(true)).toEqual([ - { type: "model_queue", queueId: "r1", queue: { position: 3 } }, + { type: "model_queue", queueId: "r1", queue: { state: "waiting", position: 3 } }, + { type: "model_queue", queueId: "r1", queue: { state: "ready" } }, { type: "model_queue", queueId: "r1", queue: null }, ]); }); diff --git a/packages/coding-agent/test/step-model-queue-session.test.ts b/packages/coding-agent/test/step-model-queue-session.test.ts index 49fcf2c8f..0a710bdb1 100644 --- a/packages/coding-agent/test/step-model-queue-session.test.ts +++ b/packages/coding-agent/test/step-model-queue-session.test.ts @@ -129,7 +129,8 @@ describe("Step sessions install the queue", () => { expect(calls[1]?.id).toBe(calls[0]?.id); expect(calls[2]?.id).toBe(calls[0]?.id); expect(events.filter((event) => event.type === "model_queue").map((event) => event.queue)).toEqual([ - { position: 2 }, + { state: "waiting", position: 2 }, + { state: "ready" }, null, ]); }); diff --git a/packages/coding-agent/test/step-model-queue.test.ts b/packages/coding-agent/test/step-model-queue.test.ts index b036223d3..cd843e9ca 100644 --- a/packages/coding-agent/test/step-model-queue.test.ts +++ b/packages/coding-agent/test/step-model-queue.test.ts @@ -411,7 +411,14 @@ test("waits in line, then resends the same bytes under the same id", async () => assert.deepEqual(resend?.body, first?.body); assert.equal(text(resend?.body), BODY); assert.deepEqual(h.sleeps, [1500, 1000, 2000]); - assert.deepEqual(h.states, [{ position: 3 }, { position: 2 }, { position: 1 }, null]); + assert.deepEqual(h.states, [ + { state: "waiting", position: 3 }, + { state: "waiting", position: 2 }, + { state: "waiting", position: 1 }, + // The place stopped waiting and the request is about to run: a phase of its own, not a vanished row. + { state: "ready" }, + null, + ]); assert.deepEqual(h.exits, [undefined]); assert.deepEqual([h.holds(), h.released()], [1, 1]); // Held only while polling; the resend is back under the idle bound. @@ -457,7 +464,15 @@ test("keeps polling when the resend is queued again", async () => { assert.equal(posts.length, 3); assert.deepEqual(new Set(posts.map((call) => call.headers.get("X-StepCode-Queue-ID"))), new Set(["q-1"])); assert.deepEqual(new Set(posts.map((call) => text(call.body))), new Set([BODY])); - assert.deepEqual(h.states, [{ position: 2 }, { position: 4 }, { position: 1 }, null]); + assert.deepEqual(h.states, [ + { state: "waiting", position: 2 }, + { state: "ready" }, + // Queued again by the resend: back in line with its new place. + { state: "waiting", position: 4 }, + { state: "waiting", position: 1 }, + { state: "ready" }, + null, + ]); assert.deepEqual(h.sleeps, [5000, 500, 2000]); // Released before each resend, held again when the resend is queued. assert.deepEqual( @@ -546,7 +561,12 @@ test("reports only changes of place or of being in line", async () => { ok(), ]); await h.post(); - assert.deepEqual(h.states, [{ position: 2 }, { position: 1 }, null]); + assert.deepEqual(h.states, [ + { state: "waiting", position: 2 }, + { state: "waiting", position: 1 }, + { state: "ready" }, + null, + ]); }); test("names every reason the server names in readable text, generic without one", () => { @@ -783,10 +803,12 @@ test("the request host decides, not the provider: a custom provider at Step's ho ]); }); -test("status text names the position, never a wait estimate", () => { - assert.equal(stepModelQueueStatusText({ position: 3 }), "Queued: position 3"); - assert.equal(stepModelQueueStatusText({}), "Queued"); - assert.equal(stepModelQueueStatusText({ position: 0 }), "Queued"); +test("status text names the position while waiting, and the admitted place as starting", () => { + assert.equal(stepModelQueueStatusText({ state: "waiting", position: 3 }), "Queued: position 3"); + assert.equal(stepModelQueueStatusText({ state: "waiting" }), "Queued"); + assert.equal(stepModelQueueStatusText({ state: "waiting", position: 0 }), "Queued"); + // The server admitted the place: the request is about to run, so the line no longer has a place to name. + assert.equal(stepModelQueueStatusText({ state: "ready" }), "Starting..."); }); test("a stop waits for the cancel request, and the call stays a registered teardown until it settles", async () => { From 5ccc3486cab798352d636c7836c7b61b06f43331 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:50:10 +0800 Subject: [PATCH 5/5] feat(subagent): show a child's own place in the model request queue - A child runs as an rpc process started with --include-live-events, so its model_queue frames already reach the parent, but the event projection ignored them: a child waiting in line looked like a child doing nothing. - The projection now folds each child's frames by queue id and keeps the call updated last as `queue` on its live record (state and position only). One call leaving the line keeps another's place; two children never share a fold. - The live roster carries `queue` field by field, and the lane snapshot validation accepts it (and refuses a malformed one whole), so a host that reads lane snapshots can show it. A settled turn drops it: a final result never carries a live field. --- .../src/features/step-subagent.ts | 40 +++++- .../src/features/subagent/lane-events.ts | 4 + .../src/features/subagent/projection.ts | 9 ++ .../src/features/subagent/rpc-adapter.ts | 2 + .../test/subagent-child-queue.test.ts | 134 ++++++++++++++++++ 5 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 packages/coding-agent/test/subagent-child-queue.test.ts diff --git a/packages/coding-agent/src/features/step-subagent.ts b/packages/coding-agent/src/features/step-subagent.ts index 53a241148..e9537f9bb 100644 --- a/packages/coding-agent/src/features/step-subagent.ts +++ b/packages/coding-agent/src/features/step-subagent.ts @@ -16,6 +16,7 @@ import { type Static, Type } from "typebox"; import { CONFIG_DIR_NAME } from "../config.ts"; import { CHILD_SESSION_ORIGIN } from "../core/child-session.ts"; import type { ExtensionAPI, ExtensionContext, ExtensionFactory, InlineExtension } from "../core/extensions/types.ts"; +import type { ModelQueueState } from "../core/model-fetch.ts"; import type { NewSessionOptions } from "../core/session-manager.ts"; import { resolveStepAgentDir, resolveStepConfigDir } from "../step/environment.ts"; import { @@ -136,6 +137,11 @@ export interface StepSubagentRunResult { activeToolArgs?: string; activeToolOutput?: string; lastEvent?: string; + /** + * Where the child's model request stands in the server-side queue: the call updated last when the child + * has several in flight, absent once none waits. Live only; never part of a final result. + */ + queue?: import("../core/model-fetch.ts").ModelQueueState; startedAt?: number; updatedAt?: number; /** True when a keep-alive rpc child is still running and can accept replies. */ @@ -541,6 +547,36 @@ function appendMessage(messages: Message[], message: Message): void { if (messages.length > MAX_MESSAGES) messages.splice(0, messages.length - MAX_MESSAGES); } +/** + * A child may have several model calls in line at once (its own parallel tools, compaction beside a turn), each + * reported by queue id. They are folded here, off the result: a live frame is copied whole on every event, so the + * per-call map must not ride along. The result shows the call updated last, like the host does for its own session. + */ +const childQueueCalls = new WeakMap>(); + +function foldModelQueue(current: StepSubagentRunResult, event: Record): void { + const queueId = typeof event.queueId === "string" ? event.queueId : ""; + if (!queueId) return; + let calls = childQueueCalls.get(current); + if (!calls) { + calls = new Map(); + childQueueCalls.set(current, calls); + } + // Re-inserted so the map's last entry is the call updated last. + calls.delete(queueId); + const queue = event.queue; + if (isRecordValue(queue) && (queue.state === "waiting" || queue.state === "ready")) { + const position = queue.position; + calls.set(queueId, { + state: queue.state, + ...(typeof position === "number" && Number.isSafeInteger(position) && position >= 0 ? { position } : {}), + }); + } + const newest = [...calls.values()].at(-1); + if (newest) current.queue = newest; + else delete current.queue; +} + export function parseJsonEvent( line: string, current: StepSubagentRunResult, @@ -562,7 +598,9 @@ export function parseJsonEvent( // JSON mode emits deltas without the cumulative assistant snapshot. Keep a // small live projection for the parent renderer while retaining final // messages as the authoritative result. - if (type === "message_start") { + if (type === "model_queue") { + foldModelQueue(current, candidate); + } else if (type === "message_start") { current.activeText = ""; current.activeTool = undefined; current.activeToolArgs = undefined; diff --git a/packages/coding-agent/src/features/subagent/lane-events.ts b/packages/coding-agent/src/features/subagent/lane-events.ts index 6f3261491..f05a026c4 100644 --- a/packages/coding-agent/src/features/subagent/lane-events.ts +++ b/packages/coding-agent/src/features/subagent/lane-events.ts @@ -123,6 +123,10 @@ function validLaneSnapshot(value: unknown): value is SubagentLaneSnapshot { (field) => field === undefined || nonnegativeNumber(field), ) && (record.pendingReply === undefined || typeof record.pendingReply === "boolean") && + (record.queue === undefined || + (isRecordValue(record.queue) && + (record.queue.state === "waiting" || record.queue.state === "ready") && + (record.queue.position === undefined || nonnegativeNumber(record.queue.position)))) && (record.cancelledPrompts === undefined || (Array.isArray(record.cancelledPrompts) && record.cancelledPrompts.every((field) => typeof field === "string"))) diff --git a/packages/coding-agent/src/features/subagent/projection.ts b/packages/coding-agent/src/features/subagent/projection.ts index d034b23c4..b5b4a2b8a 100644 --- a/packages/coding-agent/src/features/subagent/projection.ts +++ b/packages/coding-agent/src/features/subagent/projection.ts @@ -143,6 +143,15 @@ export function liveRecord(record: StepSubagentResultRecord): StepSubagentResult ...(record.sessionId === undefined ? {} : { sessionId: clipMiddle(record.sessionId, LIVE_IDENTIFIER_CHARS) }), ...(record.sessionFile === undefined ? {} : { sessionFile: clipMiddle(record.sessionFile, LIVE_PATH_CHARS) }), ...(record.pendingReply === undefined ? {} : { pendingReply: record.pendingReply }), + // Only the known fields cross: the queue is a live frame, copied field by field like the rest. + ...(record.queue === undefined + ? {} + : { + queue: { + state: record.queue.state, + ...(record.queue.position === undefined ? {} : { position: record.queue.position }), + }, + }), ...(prompts === undefined ? {} : { cancelledPrompts: prompts }), }; } diff --git a/packages/coding-agent/src/features/subagent/rpc-adapter.ts b/packages/coding-agent/src/features/subagent/rpc-adapter.ts index c186b4dd1..7d528a336 100644 --- a/packages/coding-agent/src/features/subagent/rpc-adapter.ts +++ b/packages/coding-agent/src/features/subagent/rpc-adapter.ts @@ -468,6 +468,8 @@ export async function createSubagentRpcSession( clearRouteCheck(); active.cleanup?.(); finalize(active.current, active.aborted); + // A turn that ended is out of every line, whatever its last report said; a final result never carries it. + delete active.current.queue; active.current.updatedAt = Date.now(); if (sessionFile) active.current.sessionFile = sessionFile; active.current.sessionId = sessionId; diff --git a/packages/coding-agent/test/subagent-child-queue.test.ts b/packages/coding-agent/test/subagent-child-queue.test.ts new file mode 100644 index 000000000..309fcea56 --- /dev/null +++ b/packages/coding-agent/test/subagent-child-queue.test.ts @@ -0,0 +1,134 @@ +import { expect, test } from "vitest"; +import type { StepSubagentResultRecord, StepSubagentRunResult } from "../src/features/step-subagent.ts"; +import { parseJsonEvent } from "../src/features/step-subagent.ts"; +import { emptyUsage } from "../src/features/subagent/helpers.ts"; +import { readSubagentLaneSnapshot } from "../src/features/subagent/lane-events.ts"; +import { liveRecord, liveRoster } from "../src/features/subagent/projection.ts"; + +/** + * A child's model calls wait in Step's queue on their own. The parent sees them as `model_queue` frames of the + * child's rpc stream (the runner starts it with `--include-live-events`); they fold into one `queue` on the live + * record, shown by the call updated last, and never reach a final result. + */ + +function emptyResult(): StepSubagentRunResult { + return { messages: [], stderr: "", exitCode: 0, usage: emptyUsage() }; +} + +const frame = (queueId: string, queue: unknown) => JSON.stringify({ type: "model_queue", queueId, queue }); + +function record(queue?: StepSubagentRunResult["queue"]): StepSubagentResultRecord { + return { + ...emptyResult(), + agent: "general", + agentSource: "builtin", + task: "inspect", + status: "running", + ...(queue ? { queue } : {}), + }; +} + +test("a child's queue frame sets its live queue, and leaving the line clears it", () => { + const current = emptyResult(); + parseJsonEvent(frame("a", { state: "waiting", position: 3 }), current, undefined); + expect(current.queue).toEqual({ state: "waiting", position: 3 }); + parseJsonEvent(frame("a", { state: "ready" }), current, undefined); + expect(current.queue).toEqual({ state: "ready" }); + parseJsonEvent(frame("a", null), current, undefined); + expect(current.queue).toBeUndefined(); + expect("queue" in current).toBe(false); +}); + +test("several calls in line fold into the one updated last, and one leaving keeps the others", () => { + const current = emptyResult(); + parseJsonEvent(frame("a", { state: "waiting", position: 3 }), current, undefined); + parseJsonEvent(frame("b", { state: "waiting", position: 7 }), current, undefined); + expect(current.queue).toEqual({ state: "waiting", position: 7 }); + // A moved up the line, so it is the one updated last even though it started first. + parseJsonEvent(frame("a", { state: "waiting", position: 1 }), current, undefined); + expect(current.queue).toEqual({ state: "waiting", position: 1 }); + parseJsonEvent(frame("a", null), current, undefined); + expect(current.queue).toEqual({ state: "waiting", position: 7 }); + parseJsonEvent(frame("b", null), current, undefined); + expect(current.queue).toBeUndefined(); +}); + +test("two children never share a fold", () => { + const one = emptyResult(); + const other = emptyResult(); + parseJsonEvent(frame("a", { state: "waiting", position: 2 }), one, undefined); + parseJsonEvent(frame("a", null), other, undefined); + expect(one.queue).toEqual({ state: "waiting", position: 2 }); + expect(other.queue).toBeUndefined(); +}); + +test("malformed queue frames never invent a place in line", () => { + const current = emptyResult(); + // No queue id: nothing to fold. + parseJsonEvent( + JSON.stringify({ type: "model_queue", queue: { state: "waiting", position: 1 } }), + current, + undefined, + ); + expect(current.queue).toBeUndefined(); + // An unknown phase is not a place in line. + parseJsonEvent(frame("a", { state: "something_new", position: 1 }), current, undefined); + expect(current.queue).toBeUndefined(); + // A position that is not a place is dropped; the phase still shows. + parseJsonEvent(frame("a", { state: "waiting", position: -1 }), current, undefined); + expect(current.queue).toEqual({ state: "waiting" }); + parseJsonEvent(frame("a", { state: "waiting", position: 1.5 }), current, undefined); + expect(current.queue).toEqual({ state: "waiting" }); + parseJsonEvent(frame("a", "waiting"), current, undefined); + expect(current.queue).toBeUndefined(); +}); + +test("a queue frame reaches the parent's update callback as a live frame", () => { + const current = emptyResult(); + const seen: Array = []; + parseJsonEvent(frame("a", { state: "waiting", position: 2 }), current, (result) => seen.push(result.queue)); + expect(seen).toEqual([{ state: "waiting", position: 2 }]); +}); + +test("the live projection carries the queue field by field, and omits it when there is none", () => { + expect(liveRecord(record()).queue).toBeUndefined(); + expect("queue" in liveRecord(record())).toBe(false); + expect(liveRecord(record({ state: "waiting", position: 4 })).queue).toEqual({ state: "waiting", position: 4 }); + expect(liveRecord(record({ state: "ready" })).queue).toEqual({ state: "ready" }); + // Anything beyond the known fields stays behind. + const wide = record({ state: "waiting", position: 1, eta: 30 } as unknown as StepSubagentRunResult["queue"]); + expect(liveRecord(wide).queue).toEqual({ state: "waiting", position: 1 }); + expect(liveRoster([record({ state: "ready" })]).results[0]?.queue).toEqual({ state: "ready" }); +}); + +function lane(queue: unknown) { + const row = { ...liveRecord(record()), ...(queue === undefined ? {} : { queue }) }; + return { + laneId: "lane_1", + status: "running", + details: { + mode: "single", + agentScope: "user", + userAgentsDir: "/tmp/agents", + projectAgentsDir: null, + agentId: "lane_1", + status: "running", + results: [row], + }, + }; +} + +test("a lane snapshot keeps the child's queue across the validation boundary", () => { + expect(readSubagentLaneSnapshot(lane(undefined))?.details.results[0]?.queue).toBeUndefined(); + expect(readSubagentLaneSnapshot(lane({ state: "waiting", position: 2 }))?.details.results[0]?.queue).toEqual({ + state: "waiting", + position: 2, + }); + expect(readSubagentLaneSnapshot(lane({ state: "ready" }))?.details.results[0]?.queue).toEqual({ state: "ready" }); +}); + +test("a lane snapshot with a malformed queue is refused whole, never half trusted", () => { + expect(readSubagentLaneSnapshot(lane({ state: "bogus" }))).toBeUndefined(); + expect(readSubagentLaneSnapshot(lane({ state: "waiting", position: -1 }))).toBeUndefined(); + expect(readSubagentLaneSnapshot(lane("waiting"))).toBeUndefined(); +});