From bee796f746f04db50111ae6aa1b1a9d8dbcdbc7b Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 20 Nov 2026 06:13:29 +0900 Subject: [PATCH 01/57] test(windows): cover the snapshot refresh-read owner cutoff (#8967) Follow-up to #8965: the cap-reached case only exercised the cutoff before each owner read. The new cap-during-owner case moves the cutoff into the past during the first owner read and requires no refresh read. --- tests/windows/windows-process-evidence.test.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/windows/windows-process-evidence.test.ts b/tests/windows/windows-process-evidence.test.ts index 00d603841d8..4091cb8f4bf 100644 --- a/tests/windows/windows-process-evidence.test.ts +++ b/tests/windows/windows-process-evidence.test.ts @@ -240,19 +240,21 @@ const liveX64 = process.platform !== "win32" || process.arch !== "x64"; const portablePowerShell = Bun.which("pwsh"); -// The three budgets run in one test that shares one 60 s window: a slow first PowerShell start may use +// The budgets run in one test that shares one 60 s window: a slow first PowerShell start may use // most of it, but a hang still fails inside the 120 s Linux batch deadline, naming the active budget. // "cap-reached" is the hosted-runner regression: the loop's own 1.5 s budget is fresh, but the // helper has already used the snapshot cap's owner window, so no owner read may start. +// "cap-during-owner" passes the cap's owner cutoff while the first owner read is in flight, so its +// refresh read must not start either. test.skipIf(process.platform !== "win32" && !portablePowerShell)("owner enrichment prioritizes this home and retains every row", async () => { const deadline = Date.now() + 60_000; - for (const budget of ["available", "expired", "expires-during-owner", "cap-reached"] as const) { + for (const budget of ["available", "expired", "expires-during-owner", "cap-reached", "cap-during-owner"] as const) { try { await ownerEnrichmentCase(budget, deadline); } catch (error) { throw new Error("budget=" + budget + ": " + (error instanceof Error ? error.message : String(error)), { cause: error }); } } }, 65_000); -async function ownerEnrichmentCase(budget: "available" | "expired" | "expires-during-owner" | "cap-reached", deadline: number): Promise { +async function ownerEnrichmentCase(budget: "available" | "expired" | "expires-during-owner" | "cap-reached" | "cap-during-owner", deadline: number): Promise { const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!; const launcher = Buffer.from(windowsLauncherVbsPath(), "utf8").toString("base64"); // A cap equal to the reserve puts the owner cutoff at the helper's own start. @@ -268,6 +270,7 @@ async function ownerEnrichmentCase(budget: "available" | "expired" | "expires-du " CreationDate = [datetime]'2026-11-12T01:02:03Z' } } };", "function Invoke-CimMethod { param($InputObject, $MethodName, $ErrorAction, $OperationTimeoutSec)", " $script:ownerReads++; " + (budget === "expires-during-owner" ? "$ownerBudget.Clock.ElapsedMilliseconds = 1500; " : "") + + (budget === "cap-during-owner" ? "$ownerBudget.Until = [DateTime]::UtcNow.AddMinutes(-1); " : "") + "@{ Sid = $currentSid; ReturnValue = 0 } };", "$rows = & { " + script + " };", "[pscustomobject]@{ Snapshot = $rows; OwnerReads = $script:ownerReads; RefreshReads = $script:refreshReads } | ConvertTo-Json -Compress", @@ -286,7 +289,7 @@ async function ownerEnrichmentCase(budget: "available" | "expired" | "expires-du const rows = parseWindowsProcessSnapshot(result.Snapshot)!; expect(rows).toHaveLength(40); expect(rows.map(row => row.pid)).toEqual(Array.from({ length: 40 }, (_, index) => index + 1)); - expect(result.OwnerReads).toBe(budget === "available" ? 32 : budget === "expires-during-owner" ? 1 : 0); + expect(result.OwnerReads).toBe(budget === "available" ? 32 : budget === "expires-during-owner" || budget === "cap-during-owner" ? 1 : 0); const refreshed = budget === "available" ? 32 : 0; expect(result.RefreshReads).toBe(refreshed); expect(rows[39]!.foreignOwner).toBe(budget === "available" ? false : null); From d61cca122d00899b0a917162875c7c2c659f4952 Mon Sep 17 00:00:00 2001 From: Hong Liu <88263959+Hylouis233@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:13:52 +0800 Subject: [PATCH 02/57] feat(step-cli): run StepCode as a Step Plan transport (#7267) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(step-cli): run StepCode as a Step Plan transport Adds a `step-cli` preset that spends a Step Plan subscription through StepCode's own harness instead of calling api.stepfun.com/step_plan directly. The StepCode CLI exposes `step --sdk-stdio`, a length-prefixed framed protocol with `sdk-tools` and `permission-callback` capabilities. That surface fits this repository's tool-ownership contract better than the capture-only MCP server the sibling CLI routes stage: the client's catalog is declared as inline-schema SDK tools, a call returns as a `sdk_tool.invoke` reverse request, and no MCP server is written and no tool ever executes inside StepCode. Three contract decisions differ from the other CLI families and are documented in structure/providers/step-cli-transport.md: - Its own wire, which is not `--mode rpc`'s newline-delimited JSONL. A peer that mixes the two is answered with silence, so the envelope guard and the decoder are strict. - One process per conversation. `query.input` reduces every message to text and images, so an assistant turn, a declared tool call and its result cannot be replayed through the wire. Sessions are keyed by the handle the client echoes back through `providerState`, and a process that dies is reported rather than restarted, because tool results already delivered are not replayable here. - A bounded tool-result window. StepCode's `SDK_TOOL_TIMEOUT_MS` is 120s and a late answer produces a `permission_denied` message inside the model's context, so the hold timer is shorter and reports `step_cli_tool_result_too_late`. No credential is injected: the CLI resolves its own `step login`, so the child environment adds only `USER` and a redirected session directory. Handshake rejects a runtime that does not advertise `sdk-tools`, because such a runtime answers text only while looking healthy. Verified against a signed-in Step Plan account and a real `step` process: initialize, query.start with inline tool schemas, permission.request, sdk_tool.invoke, and a final assistant message that used the tool result. * fix(step-cli): keep conversations alive across requests and deliver tool results The first live run against a real `step` process surfaced four defects that no unit test could have found, each fixed here with the evidence that located it: - `runTurn` returned right after `query.input` was acknowledged, so the response reached the client with no terminal event (`incomplete_details.reason = adapter_eof`). It now awaits the turn's own completion, raced against the client's abort. - The framed protocol nests the projected message as `{queryId, message: {...}}`, unlike `step --mode json` which prints `type` at the top level. Reading `payload.type` made every turn look idle until it timed out. - `sdk_tool.invoke` carries the descriptor's BARE `toolName` alongside `serverName`, not the registered `__` name. The miss fell into a denial, and a denial carrying only `{message}` is not a denial to StepCode: it renders an EMPTY tool result, which the model reports as a command that ran and produced nothing. `refuseToolCall` now answers with an error frame. - Nothing owned state across a request boundary. `createStepCliAdapter` runs once per request, so the session pool and the active turn lived in a closure that was already gone when the next request arrived: every continuation started a fresh process and orphaned the tool call it was supposed to release. Both moved to module scope, following `devin/trajectory.ts`, and the conversation is keyed by the thread identity Codex sends on every request rather than by persisted provider state, which is what `devin`, `zed`, `cursor` and `google` all do. A turn that answers a captured call now delivers the result and does not re-prompt: the model already has the instruction and is mid-query. Verified end to end against a signed-in Step Plan account and the installed CLI: turn 1 returns `function_call shell {"cmd":"echo LIVE_BRIDGE_OK"}`, the client runs it, and turn 2 returns the command's real output. * fix(step-cli): keep registry bookkeeping files within their budgets Three bookkeeping files were rewritten with a JSON pretty-printer instead of surgical edits, so registering five test files reformatted the whole document: scripts/test-layout/layout.json 1965 -> 2317 lines tests/fixtures/test-layout-expected.json 1349 -> 2442 lines structure/manifest.json 979 -> 1029 lines The first two crossed the ratchet's 2000-line ceiling for an unlisted file, which is why `file-size ratchet: repository` failed on this branch and passed at the baseline. Restored each from 2a3fd00 and re-applied the additions as anchored insertions, so the only delta is the five registrations (1970 / 1352 / 988 lines). The preset totals in the docs were the other honest gate: the registry gained one preset, so all eight locales' guides and quickstarts and the structure ops record now state 106 presets and 86 key-based. * fix(step-cli): address every CodeRabbit finding on #7267 Ten findings, all verified against the code rather than dismissed. Three were Major and two of those were cross-client data leaks that the existing suite could not see — which is the point: a green suite said the old `default` conversation handle was fine, because nothing tested what happens when two clients have no identity at all. Security / data integrity: - `conversationHandle` returned the shared string `"default"` when a request carried no thread, session or previous-response identity. Claude Code, Grok Build and generic Chat clients all send such requests, so unrelated clients shared one StepCode process: one could read another's context, and a held tool result from one could be delivered into another's query. It now returns undefined and the caller mints a private ref, so an identity-less request gets its own process. Verified live against two identity-less requests carrying different tokens: neither saw the other. - A held tool result was matched by POSITION in the transcript instead of by call id, so a client that followed a tool call with a user message instead of a result had an older result delivered as the answer to the current call. The pool now remembers the call id beside the frame id, delivery requires `toolCallId` to match, and a mismatch refuses the call. - A client abort left the query running inside StepCode. Since it serves one query at a time, the next request for that conversation would be rejected or blocked. The abort path now interrupts the query and closes the session when the interrupt cannot be confirmed. Stability: - Concurrent `open()` calls for one conversation each spawned a process; the second `#entries.set` orphaned the first with an unreleasable held tool call. Opens are now coalesced on an in-flight promise keyed by handle. - When a held call expired, no turn received the expiry and no answer reached the runtime, so StepCode waited out its own 120s window and a later turn could re-emit a duplicate tool call. The expiry is now answered with a refusal and never re-dispatched. - stderr was decoded per chunk with `toString("utf8")`, so a CJK character split across chunks became U+FFFD and the not-signed-in detection that matches 未登录 could stop firing. The stream is now `setEncoding("utf8")`. - A spawn `error` (e.g. ENOENT) closed the session without stopping the idle sweep. Diagnostics / maintenance: - An undersized length prefix reported "exceeds max frame size" with FRAME_TOO_LARGE, pointing at the ceiling when the real fault is a truncated stream. It now has FRAME_TOO_SMALL and its own text. - `STEP_CLI_TOOL_SERVER` was defined twice; the bridge now re-exports the single definition. - The expiry test slept 560ms of wall clock and went flaky on slow runners. It now injects timers. Every finding has a regression test (tests/adapters/step-cli-conversation.test.ts plus additions to step-cli-session.test.ts and step-cli-tool-result.test.ts): 60 step-cli tests, and the full focused set of 130 across layout, ratchet, preset counts, conformance and registry parity. Live re-verified after the fixes: turn 1 returns the client's `function_call`, turn 2 returns the command's real output. * fix(step-cli): release the runtime's query slot, serialise concurrent turns Two more defects, both found by driving the real CLI rather than the suite. Neither was reachable from the previous round's tests, which is the point: the suite exercised tool continuations and identity-less requests, and both defects lived one layer below that. A multi-turn conversation could not exist. StepCode's `#maybeFinish` refuses to finish a query whose input has not ended, and this adapter never sent `query.input_end` — so the runtime's single query slot was never released and the second turn on a conversation failed with SESSION_BUSY. The missing call also explains why the tool path worked: a captured call keeps its query open on purpose, and every earlier live test went through that path. Only a plain text conversation reaches the broken branch. `query.input_end` is now sent when a turn settles with a completion, and deliberately NOT when a tool call is captured, because that query is still owed the client's result. Concurrent turns on one conversation corrupted each other. This proxy's turn state is keyed by the single process StepCode serves one query from, so two overlapping turns overwrote each other's runtime, interrupted each other's query and closed each other's session. Measured before the fix: two concurrent requests on one `thread-id` both failed, one with SESSION_NOT_FOUND and the other with step_cli_session_closed. Turns are now queued per conversation, with a small cap so a pile-up is refused rather than grown. The queue made a second, subtler failure visible — a turn that waits for a terminal event with neither a client abort nor a CLI event would hold that queue for the life of the process, so waiting now has a hard deadline far above StepCode's own 120s tool window. A third fix falls out of the measurement: a turn settles when the CLI reports `turn_complete`, which can precede the runtime freeing its slot, so `query.start` retries while the runtime reports itself busy. The retry is message-based rather than `instanceof StepSessionError`, so a change of error class cannot silently turn a handover race back into a hard failure. Verified against the real CLI after the fixes: three consecutive text turns on one thread all complete with the right answers (TURN1/2/3_DONE), and two concurrent requests on one thread both complete with distinct answers and no cross-talk. step-cli is now 80 tests; the broader focused set (layout, ratchet, preset counts, conformance, registry parity) is 130. * fix(step-cli): make the tool-catalog ceiling legible, verified against real Codex A stock Codex 0.162.0 client was pointed at this route for the first time, and it failed immediately: "Invalid StepCode tool catalog: tool catalog exceeds tool count limit". Measured rather than guessed: Codex declared 1749 tools / 2.5 MB, because it flattens every MCP server's tools into the function catalog. The shared CLI-family ceiling is 128 tools / 2 MiB — the same bound `qoder`, `codebuddy` and `claude-cli` enforce from the same `buildCodingAgentToolCatalog` — so this is a family constraint, not a step-cli defect, and raising it is a maintainer decision rather than something to slip into this PR. What this changes is the refusal. "exceeds tool count limit" cannot distinguish an oversized catalog from a malformed one, so an operator reading it had no way to know 1749 tools were involved or that the bound is family-wide. It now names the declared count, the ceiling, and the operator action (disable or narrow MCP servers for this provider). Failing closed is deliberate: a tool the client believes exists but that never reaches the model is worse than a refusal. Same client, with MCP servers stripped, drives the route end to end: text turn -> codex replies CLEAN_CODEX_OK tool turn -> codex runs /bin/zsh -lc 'echo CLEAN_TOOL_OK' (succeeded in 0ms) and reports the output verbatim So the tool really is executed by the client, which is the whole point of the route. The constraint is now stated in the registry note, the structure contract and the docs-site section with the measured numbers, so nobody has to rediscover it by hitting it. step-cli is 81 tests; the broader focused set stays at 130. * fix(step-cli): close live StepCode processes when the proxy stops A 14-turn conversation on one thread held up: 0 failures, and exactly one `step` process for all 14 turns, which is the reuse this route is built on. The same run also surfaced a leak — a `step` process from an earlier probe was still alive after its proxy had been stopped. The sibling CLI routes cannot leak this way: they spawn a child per request and kill it in a `finally`, so it cannot outlive a turn. This route deliberately keeps a process alive for a whole conversation, so nothing was killing it on shutdown, and an orphaned `step` holds the user's subscription session open. Sessions now register through `registerOptionalShutdownHook`, which `server/lifecycle.ts` runs on stop. Measured after the change: one `step` process during a turn, zero after the proxy is stopped (previously one survived). Tests: 82 step-cli tests, the broader focused set unchanged at 130. * fix(step-cli): forward non-text tool results instead of collapsing them A tool result is not necessarily text. `latestToolResult` concatenated only the text parts and dropped everything else, which for a result carrying an image meant an empty text block reached the model — the same misleading-"the tool returned nothing" failure the wrong-call path already had, in a second place. Content is now projected onto the blocks StepCode's SDK tool accepts (`text`, and `image` as base64 + media type). Block boundaries are preserved rather than concatenated, because StepCode maps each block 1:1 and joining would erase the difference between e.g. a tool's stdout and its stderr. An inline `data:` image is forwarded; a remote URL cannot be, so it becomes a note the model can act on instead of vanishing; a result with nothing readable says so rather than looking empty. Scope note: on the standard Codex path this layer is upstream of the adapter — `src/vision/image-rewrite.ts` already rewrites image tool results to an explanatory `[image omitted: this model is text-only ...]` placeholder for a text-only row. A live run confirmed the model receives that explanation rather than an empty result, so this change is the residual path (clients outside the vision rewrite, or a disabled sidecar), not the fix for that case. Live checks this round, against the real CLI: real client abort mid-turn -> 0 step processes left, and the same thread's next request completes normally three threads concurrently -> all completed, each with its own answer, no cross-talk four conversations -> four processes, all reclaimed on proxy stop * fix(step-cli): refuse a busy conversation with an explained, retryable error The per-conversation queue added last round caps how many turns may wait, and the refusal threw straight out of `runTurn` — an unhandled rejection, not an event on the stream. Every other failure on this route becomes an error event, so this one path handed the caller a generic failure instead of saying what happened. It now emits a retryable 409 (`step_cli_conversation_busy`) naming the conversation and the queue depth, then closes the session it had just opened. That refusal is the only thing standing between a retry storm and an unbounded wait, so it now has its own coverage: turns on one conversation run in arrival order, separate conversations never wait on each other, and a pile-up past the cap is refused instead of queued. Also verified this round, against the real CLI: a compaction turn arriving WHILE a tool call is held -> produces the synthetic `compaction` item with no error, and the same conversation's next ordinary turn still completes. The concern that a compaction turn would park state on the parent conversation (a bug cursor hit in the same area) does not apply here. step-cli is 90 tests; the broader focused set stays at 130. * fix(step-cli): register the turn before delivering a held tool result Answering a held `sdk_tool.invoke` unblocks the CLI, and the CLI may answer with frames the moment it does. The turn was registered AFTER that delivery, so any frame arriving in between found no runtime to route it to, was dropped, and the turn then waited out its deadline on a model that had already answered. The turn is now registered first and the result delivered second. The decision about what this turn IS (answer to the held call, abandoned call, or a fresh user message) was also hoisted above the delivery so nothing inspects the transcript after a side effect. The regression test makes the race deterministic rather than timing-dependent: the fake emits `turn_complete` synchronously INSIDE `resolveHeldToolResult`. Reverting the order turns that test red and restoring it turns it green, which is how the fix was confirmed to be the thing the test is actually pinning. step-cli is 91 tests; the broader focused set stays at 130. * refactor(step-cli): split the adapter into five modules with a one-way graph `adapter.ts` had grown to 957 lines carrying eight unrelated concerns: process lifetime, turn runtime state, conversation serialisation, pool registry, shutdown wiring, frame mapping, request projection and error wording. Everything about this route is now readable in one place per concern, and the turn loop is the only thing left in the file that decides anything. adapter.ts orchestration only: what one turn is, in what order, when it is terminal conversation.ts conversation identity (which thread owns which process) and turn ordering events.ts what the CLI says and what this peer owes it back projection.ts pure request/response conversions, testable without a session registry.ts the state that must outlive a request, plus shutdown wiring errors.ts failure text and the status a client can retry on The dependency graph is one-way: adapter → {conversation, events, projection, registry, errors}, events → {projection, registry, registry → pool, and nothing imports adapter. Two edges had to be cut to keep it that way — `poolFor` now takes the session handlers as an argument instead of importing `events`, and the idle timeout moved to `registry` where the pool that uses it lives. `adapter.ts` went 957 → 394 lines. Behaviour is unchanged: 91 step-cli tests and the broader focused set (121) pass, and the gates are green. The tests now import each symbol from the module that owns it, so a move shows up as an import error rather than a silently relocated export. Also removed a stray block left in `driveTurn` by an earlier patch. * refactor(step-cli): keep modules from reaching into each other's state Post-split review found the split was only half done: `events` and `adapter` were still reading and writing `registry`'s WeakMaps directly (`turnRuntimes.get/delete`, `lastAssistantUsage.set`, `lastQueryId.get/set`). That is exactly the coupling the split was meant to remove, and it would have pinned the storage shape into three call sites. `registry` now exposes semantic accessors — `beginTurn`, `currentTurn`, `endTurn`, `recordAssistantUsage`, `assistantUsage`, `rememberQuery`, `currentQuery`, `forgetQuery` — and the maps stay private to it. "Who owns this session's turn" is answered in one module. Behaviour unchanged: 91 step-cli tests, the 130-test focused set, and the gates all pass, and the full suite was compared against the clean baseline worktree in an interleaved window (mine 160/0 and 160/0; baseline 159/1 and 160/0) after an un-interleaved comparison had produced 66 phantom differences under load. The structure contract now records the module layout and why the two dependency edges are cut the way they are. * docs(step-cli): name the remaining modules in the contract's layout table The table listed six modules and then jumped to 'the framed transport itself', so `env.ts`, `profiles.ts` and `constants.ts` were undocumented even though `session.ts` depends on all three. Found while checking the refactor's dependency graph: the layering only holds if those edges are written down. * fix(step-cli): recover a turn that ends without a terminal event The guard deciding "nothing terminated this turn" read `if (!currentTurn(session) !== undefined) return;`. `currentTurn` returns a turn or `undefined`, so `!currentTurn(...)` is always a boolean, and a boolean is never `undefined` — the comparison was therefore always true and every statement after it was dead code. Introduced by the `refactor(step-cli): keep modules from reaching into each other's state` commit, which mechanically rewrote the correct `if (!turnRuntimes.has(session)) return;` while introducing the semantic accessors: the opposite of that commit's stated goal. Impact: on a client abort or the ten-minute terminal deadline, the recovery never ran — no `step_cli_turn_abandoned`, no settle, no interrupt, no close. The turn kept its registration and its query kept running inside StepCode, which serves one query per process, so the next request on that conversation collided with the abandoned one. A stream that simply stops is also indistinguishable from a hung proxy. The suite could not have caught it: on every tested path a terminal event ends the turn first, which makes the guard's wrong branch indistinguishable from the right one. Added coverage for the two paths that reach it — the client abort and the deadline, the latter driven by an injected timer rather than a ten-minute sleep — plus the normal-completion case that must NOT recover, so the fix cannot be a blunt always-recover. Also drops four orphaned doc comments the same refactor left behind. * chore(repo): keep Bun's build cache out of history Two 59.8 MB copies of Bun's on-disk build cache reached this branch's history through a broad `git add -A`. Bun writes `-00000000.bun-build` into whichever directory it runs in — here, the repository root — and the same file reappears under a new hash on the next run, so a committed copy is pure weight that nothing in the build, typecheck, or test path ever reads. An ignore rule is necessary but not sufficient, for the same reason this repo already guards `go/` and `.codexclaw/`: once a path is tracked, `.gitignore` stops applying to it entirely. So the assertion belongs next to those, against the real index. This is the same shape as the mistakes this file already documents — `go/`'s config_parity.go committed three times, the root `docs/` folder at 4.9 MB — which is why the guard is an index assertion rather than another comment. * chore(step-cli): drop a write-only turn field and duplicated doc blocks `StepTurnRuntime.done` was assigned in `beginTurn` and never read by anything: `driveTurn` awaits the local promise it created, and the runtime needed only `settle` for the other callers. A field nothing consumes reads as if it were part of the contract, so the next reader has to prove it unused before trusting the surrounding code. Also collapses the duplicated doc comment on `lastQueryId` and the orphaned one-shot line that lost its declaration when `MAX_QUEUED_TURNS` moved to `conversation.ts`. Both are leftovers of the module split. * fix(step-cli): keep queue refusals off the owner's session and guard a held call with no result Addresses review at 17ce58e: a turn refused at MAX_QUEUED_TURNS never owned the conversation, so it no longer closes the session serving the accepted turn and its queue. A held call followed by user text with no toolResult no longer dereferences an undefined result; the held frame is refused and the new text runs. Both covered through runTurn with an injected session. * test(layout): register step-cli tests in their own explicit shard Adding the seven step-cli entries to layout.json took it to 2006 lines, past the file-size ratchet's 2000-line threshold. Move them into layout-step-cli.json and list it in explicitShards, as the other feature shards do, which brings layout.json back to its 1999 lines on dev. * docs(structure): fold the StepCode transport pointer into the coding-agent paragraph Keeps structure/providers-and-adapters.md within its 600-line budget after merging dev. * fix(step-cli): bind caller and query ownership through shutdown Namespace sessions and held calls by the admitted principal and physical provider. Keep keyless requests private and close failed handshakes. Correlate runtime callbacks and declared permissions with the exact query, retain the held call's catalog, and drain an abandoned query before its replacement acquires a turn. Latch pool shutdown and drain outstanding opens. Reuse the coding-agent Windows process-tree terminator with a deadline and verify OS exit before releasing handles. Preserve bounded POSIX group cleanup. Port the independent review probes into registered adapter regressions. Baseline b833c1f0d5: 1 pass / 13 fail. Fixed focused run: 325 pass / 0 fail. Typecheck, structure, privacy and documentation build passed. Co-authored-by: Hong Liu <88263959+Hylouis233@users.noreply.github.com> * fix(step-cli): retain cleanup ownership through termination failures Reserve closing and quarantined handles, bound termination to two attempts, and drain cleanup receipts started before pool shutdown. Retain failed pools through registry clears so they cannot admit replacement processes. Co-authored-by: Hong Liu <88263959+Hylouis233@users.noreply.github.com> * test(step-cli): bound registry fixture lifetime and spawn deadlines Flush the isolated registry observations and exit the fake-only helper when they are complete. Await its subprocess asynchronously with the named internal deadline below the spawn test budget. Preserve quarantine assertions. Publish native fixture PIDs atomically after reproducing a partial JSON read. Co-authored-by: Hong Liu <88263959+Hylouis233@users.noreply.github.com> * test(step-cli): warm the registry fixture and wait for native reaping * docs(step-cli): publish English and Spanish guides and recount presets * docs(structure): record shared Windows taskkill deadline * fix(gui): classify StepCode as a paid subscription CLI * fix(gui): use adapter-specific subscription details in classic setup * fix(step-cli): correlate official SDK callbacks to the active query * fix(step-cli): classify child failures before publishing errors * fix(step-cli): await shutdown and confirm POSIX process-group exit * fix(step-cli): resolve executable and workspace before spawn * fix(step-cli): keep tree cleanup within the proxy stop window Await an asynchronous Windows taskkill receipt and cap concurrent session cleanups across pools. Preserve cleanup retries, quarantine, and the synchronous process-tree helper used by other CLI adapters. Use the configured drain deadline and the controller's exit grace for the optional teardown join, leaving time for listener cleanup and exit. * fix(step-cli): use the proxy stop deadline for tree cleanup Share the stop deadline with active and queued session closes, and escalate before the deadline to leave time for exit confirmation. Sweep remaining owned POSIX groups synchronously on incomplete shutdown and start queued Windows tree kills even if slots are busy. * fix(step-cli): require ownership for process group cleanup Keep POSIX group disappearance sticky across probes, retries, and emergency teardown. Revalidate through the unreaped leader after a failed attempt, and report unverified cleanup without signalling the group. Exercise the emergency sweep with an inert process table and wait for actual fake-child cleanup in the run-turn shutdown test. * fix(step-cli): limit process group signals to live leaders Use the detached child handle to gate every POSIX group signal and to confirm exit after escalation. Quarantine the session if its leader exits before group termination, including during an emergency sweep. * test(gui): verify shared subscription CLI warning copy * docs(step-cli): record accepted POSIX cleanup risk * chore(step-cli): reconcile preset counts and layout with dev * fix(step-cli): guard process cleanup and cancelled dispatch * docs(step-cli): record the accepted Windows cleanup risk * docs(providers): recount presets after rebasing StepCode * test(step-cli): cover cleanup rejection after terminal event * fix(step-cli): handle terminal cleanup rejection --------- Co-authored-by: mavis Co-authored-by: Hylouis233 Co-authored-by: JUN <243035832+lidge-jun@users.noreply.github.com> Co-authored-by: JUN --- .gitignore | 6 + docs-site/astro.config.mjs | 1 + .../docs/es/getting-started/quickstart.md | 2 +- .../content/docs/es/guides/api-key-catalog.md | 2 +- .../src/content/docs/es/guides/providers.md | 1 + .../src/content/docs/es/guides/step-cli.md | 75 ++ .../es/reference/configuration/providers.md | 2 +- .../docs/fr/getting-started/quickstart.md | 2 +- .../src/content/docs/fr/guides/providers.md | 2 +- .../docs/getting-started/quickstart.md | 2 +- .../content/docs/guides/api-key-catalog.md | 2 +- .../src/content/docs/guides/providers.md | 1 + docs-site/src/content/docs/guides/step-cli.md | 79 ++ .../docs/ja/getting-started/quickstart.md | 2 +- .../src/content/docs/ja/guides/providers.md | 2 +- .../docs/ko/getting-started/quickstart.md | 2 +- .../src/content/docs/ko/guides/providers.md | 2 +- .../docs/reference/configuration/providers.md | 2 +- .../docs/ru/getting-started/quickstart.md | 2 +- .../src/content/docs/ru/guides/providers.md | 2 +- .../docs/tr/getting-started/quickstart.md | 2 +- .../src/content/docs/tr/guides/providers.md | 2 +- .../docs/zh-cn/getting-started/quickstart.md | 2 +- .../content/docs/zh-cn/guides/providers.md | 2 +- .../docs/zh-tw/getting-started/quickstart.md | 2 +- .../content/docs/zh-tw/guides/providers.md | 2 +- .../src/components/add-provider-form-pane.tsx | 2 +- gui/src/components/add-provider-form-pane.tsx | 2 +- gui/src/i18n/de.ts | 2 +- gui/src/i18n/en.ts | 2 +- gui/src/i18n/fr.ts | 2 +- gui/src/i18n/ja.ts | 2 +- gui/src/i18n/ko.ts | 2 +- gui/src/i18n/pt.ts | 2 +- gui/src/i18n/ru.ts | 2 +- gui/src/i18n/tr.ts | 2 +- gui/src/i18n/vi.ts | 2 +- gui/src/i18n/zh-TW.ts | 2 +- gui/src/i18n/zh.ts | 2 +- .../provider-workspace/subscription-cli.ts | 12 +- .../add-provider-subscription-cli.test.tsx | 36 +- scripts/test-layout/layout-step-cli.json | 13 + scripts/test-layout/layout.json | 2 +- src/adapters/coding-agent/process-tree.ts | 30 + src/adapters/coding-agent/profile.ts | 2 +- src/adapters/coding-agent/turn.ts | 11 +- src/adapters/registry.ts | 11 + src/adapters/step-cli/adapter.ts | 401 +++++++ src/adapters/step-cli/constants.ts | 11 + src/adapters/step-cli/conversation.ts | 159 +++ src/adapters/step-cli/env.ts | 49 + src/adapters/step-cli/errors.ts | 76 ++ src/adapters/step-cli/events.ts | 227 ++++ src/adapters/step-cli/profiles.ts | 134 +++ src/adapters/step-cli/projection.ts | 242 ++++ src/adapters/step-cli/registry.ts | 181 +++ src/adapters/step-cli/session-pool.ts | 225 ++++ src/adapters/step-cli/session.ts | 842 ++++++++++++++ src/adapters/step-cli/stdio-frames.ts | 330 ++++++ src/adapters/step-cli/tool-bridge.ts | 92 ++ src/lib/optional-shutdown-hooks.ts | 60 +- src/lib/process-control.ts | 5 +- src/lib/shutdown-budget.ts | 5 + src/providers/registry/entries-extended.ts | 38 + src/providers/registry/model-seeds.ts | 42 + src/server/lifecycle.ts | 3 +- structure/INDEX.md | 2 + structure/manifest.json | 9 + structure/ops/docs-and-release.md | 2 +- structure/ops/service-and-sidecars.md | 2 +- structure/providers-and-adapters.md | 4 +- structure/providers/step-cli-transport.md | 176 +++ structure/runtime.md | 2 +- .../adapter-registry-authority.test.ts | 1 + .../adapters/adapter-tool-conformance.test.ts | 9 +- .../step-cli-cleanup-ownership.test.ts | 409 +++++++ tests/adapters/step-cli-conversation.test.ts | 251 +++++ tests/adapters/step-cli-frames.test.ts | 119 ++ tests/adapters/step-cli-ownership.test.ts | 148 +++ .../step-cli-process-lifecycle.test.ts | 438 ++++++++ tests/adapters/step-cli-query-race.test.ts | 103 ++ tests/adapters/step-cli-run-turn.test.ts | 1000 +++++++++++++++++ tests/adapters/step-cli-session.test.ts | 438 ++++++++ tests/adapters/step-cli-tool-bridge.test.ts | 72 ++ tests/adapters/step-cli-tool-result.test.ts | 70 ++ tests/ci-workflows/cold-spawn-warmup.test.ts | 4 + tests/ci-workflows/repo-hygiene.test.ts | 21 + tests/fixtures/step-cli-cleanup-registry.ts | 28 + tests/fixtures/test-layout-expected.json | 9 + tests/gui/provider-subscription-cli.test.ts | 8 +- tests/helpers/step-cli-ownership.ts | 72 ++ tests/lib/optional-shutdown-hooks.test.ts | 32 + .../provider-registry-parity.test.ts | 2 +- tests/providers/step-cli-provider.test.ts | 153 +++ tests/service/shutdown-drain.test.ts | 25 +- 95 files changed, 7007 insertions(+), 70 deletions(-) create mode 100644 docs-site/src/content/docs/es/guides/step-cli.md create mode 100644 docs-site/src/content/docs/guides/step-cli.md create mode 100644 scripts/test-layout/layout-step-cli.json create mode 100644 src/adapters/coding-agent/process-tree.ts create mode 100644 src/adapters/step-cli/adapter.ts create mode 100644 src/adapters/step-cli/constants.ts create mode 100644 src/adapters/step-cli/conversation.ts create mode 100644 src/adapters/step-cli/env.ts create mode 100644 src/adapters/step-cli/errors.ts create mode 100644 src/adapters/step-cli/events.ts create mode 100644 src/adapters/step-cli/profiles.ts create mode 100644 src/adapters/step-cli/projection.ts create mode 100644 src/adapters/step-cli/registry.ts create mode 100644 src/adapters/step-cli/session-pool.ts create mode 100644 src/adapters/step-cli/session.ts create mode 100644 src/adapters/step-cli/stdio-frames.ts create mode 100644 src/adapters/step-cli/tool-bridge.ts create mode 100644 src/lib/shutdown-budget.ts create mode 100644 structure/providers/step-cli-transport.md create mode 100644 tests/adapters/step-cli-cleanup-ownership.test.ts create mode 100644 tests/adapters/step-cli-conversation.test.ts create mode 100644 tests/adapters/step-cli-frames.test.ts create mode 100644 tests/adapters/step-cli-ownership.test.ts create mode 100644 tests/adapters/step-cli-process-lifecycle.test.ts create mode 100644 tests/adapters/step-cli-query-race.test.ts create mode 100644 tests/adapters/step-cli-run-turn.test.ts create mode 100644 tests/adapters/step-cli-session.test.ts create mode 100644 tests/adapters/step-cli-tool-bridge.test.ts create mode 100644 tests/adapters/step-cli-tool-result.test.ts create mode 100644 tests/fixtures/step-cli-cleanup-registry.ts create mode 100644 tests/helpers/step-cli-ownership.ts create mode 100644 tests/providers/step-cli-provider.test.ts diff --git a/.gitignore b/.gitignore index b07c5979db3..ec63a4f047b 100644 --- a/.gitignore +++ b/.gitignore @@ -49,6 +49,12 @@ devlog/**/security-advisory-draft* .omo/ **/.omo/ +# Bun's on-disk build cache. Bun writes it into whichever directory it runs in, and +# `git add -A` has swept two 59 MB copies of it into this history — see +# tests/ci-workflows/repo-hygiene.test.ts, which fails if any path here becomes +# tracked again. +*.bun-build + # Local development worktrees .worktrees/ diff --git a/docs-site/astro.config.mjs b/docs-site/astro.config.mjs index 5278833b7c2..366a16b1fbb 100644 --- a/docs-site/astro.config.mjs +++ b/docs-site/astro.config.mjs @@ -102,6 +102,7 @@ export default defineConfig({ { label: "Providers", translations: { es: "Proveedores", fr: "Fournisseurs", ko: "프로바이더", "zh-CN": "提供商", "zh-TW": "供應商", ru: "Провайдеры", ja: "プロバイダー", tr: "Sağlayıcılar" }, slug: "guides/providers" }, { label: "Kiro request credits", translations: { es: "Créditos por solicitud de Kiro", fr: "Crédits de requête Kiro", ko: "Kiro 요청 크레딧", "zh-CN": "Kiro 请求额度", "zh-TW": "Kiro 請求額度", ru: "Кредиты запросов Kiro", ja: "Kiro リクエストクレジット", tr: "Kiro istek kredileri" }, slug: "guides/kiro-request-credits" }, { label: "API-key catalog", translations: { es: "Catálogo de proveedores con clave API", fr: "Catalogue des clés API", ko: "API 키 카탈로그", "zh-CN": "API 密钥目录", "zh-TW": "API 金鑰目錄", ru: "Каталог API-ключей", ja: "API キーカタログ", tr: "API Anahtarı Kataloğu" }, slug: "guides/api-key-catalog" }, + { label: "StepCode CLI (subscription)", translations: { es: "StepCode CLI (suscripción)" }, slug: "guides/step-cli" }, { label: "Google Vertex AI", translations: { es: "Google Vertex AI" }, slug: "guides/google-vertex" }, { label: "Factory Droid Bridge", translations: { es: "Puente Factory Droid", fr: "Pont Factory Droid", ko: "Factory Droid 브리지", "zh-CN": "Factory Droid 桥接", "zh-TW": "Factory Droid 橋接", ru: "Мост Factory Droid", ja: "Factory Droid ブリッジ", tr: "Factory Droid köprüsü" }, slug: "guides/factory-droid" }, { label: "Ollama-Compatible Clients", translations: { es: "Clientes compatibles con Ollama", fr: "Clients compatibles Ollama", ko: "Ollama 호환 클라이언트", "zh-CN": "Ollama 兼容客户端", "zh-TW": "Ollama 相容用戶端", ru: "Клиенты, совместимые с Ollama", ja: "Ollama 互換クライアント", tr: "Ollama uyumlu istemciler" }, slug: "guides/ollama-clients" }, diff --git a/docs-site/src/content/docs/es/getting-started/quickstart.md b/docs-site/src/content/docs/es/getting-started/quickstart.md index 08429c4cc5f..478f662906d 100644 --- a/docs-site/src/content/docs/es/getting-started/quickstart.md +++ b/docs-site/src/content/docs/es/getting-started/quickstart.md @@ -23,7 +23,7 @@ ocx init `ocx init` te guía por estos pasos: -1. **Elegir un proveedor**: selecciona uno de los 111 preajustes del registro integrado o `custom` para introducir una URL base y un adaptador. +1. **Elegir un proveedor**: selecciona uno de los 112 preajustes del registro integrado o `custom` para introducir una URL base y un adaptador. 2. **Clave API**: pega una clave o indica una variable de entorno como `${ANTHROPIC_API_KEY}`. 3. **Modelo predeterminado**: para proveedores con clave, locales o personalizados, acepta el preajuste o introduce un identificador de modelo. 4. **Puerto del proxy**: `10100` de forma predeterminada. diff --git a/docs-site/src/content/docs/es/guides/api-key-catalog.md b/docs-site/src/content/docs/es/guides/api-key-catalog.md index 43121649296..312a06e9809 100644 --- a/docs-site/src/content/docs/es/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/es/guides/api-key-catalog.md @@ -9,7 +9,7 @@ de cuentas y los proveedores locales siguen en esa página. Para rotar cuentas de suscripción, consulta [`reset-near-weighted`](/es/reference/configuration/providers/#reset-near-weighted) en los grupos OAuth de Codex y Anthropic. Los grupos de claves API usan sus propios [ajustes de selección de claves](/es/reference/configuration/providers/). -opencodex incluye 111 preajustes integrados: 89 con clave, 18 OAuth, tres locales y uno predeterminado de reenvío a ChatGPT. El selector **Añadir proveedor** abre el formulario del proveedor con clave, valida la credencial cuando el proveedor permite comprobarla y la guarda; cada proveedor tiene su propia validación. Entre ellos: +opencodex incluye 112 preajustes integrados: 90 con clave, 18 OAuth, tres locales y uno predeterminado de reenvío a ChatGPT. El selector **Añadir proveedor** abre el formulario del proveedor con clave, valida la credencial cuando el proveedor permite comprobarla y la guarda; cada proveedor tiene su propia validación. Entre ellos: **ClinePass** utiliza una clave API de Cline con el [catálogo oficial de suscripción](https://docs.cline.bot/getting-started/clinepass) y el [punto final de Chat Completions](https://docs.cline.bot/api/chat-completions), operados por Cline Bot Inc. bajo [los términos de Cline](https://cline.bot/tos). Un id enrutado como `cline-pass/cline-pass/kimi-k3` es intencional: el primer segmento selecciona el proveedor de opencodex, mientras que `cline-pass/kimi-k3` es el identificador de modelo completo que se envía aguas arriba. La cuota de ClinePass se comparte por cuenta entre límites rotativos de 5 horas, semanales y mensuales. Una sonda en vivo del 2026-08-13 verificó que todos los modelos estáticos de ClinePass aceptan `low`, `medium`, `high`, `xhigh` y `max` en el límite de entrada de la pasarela. opencodex conserva los niveles solicitados; cualquier normalización específica del backend sigue siendo responsabilidad de ClinePass. diff --git a/docs-site/src/content/docs/es/guides/providers.md b/docs-site/src/content/docs/es/guides/providers.md index 7ad16fd0631..a189038af9a 100644 --- a/docs-site/src/content/docs/es/guides/providers.md +++ b/docs-site/src/content/docs/es/guides/providers.md @@ -460,6 +460,7 @@ están en la página [Catálogo de proveedores con clave API](/es/guides/api-key - [CodeBuddy Code CLI oficial (Global y CN)](/es/guides/api-key-catalog/#official-codebuddy-code-cli-global--cn) - [Oficial Qoder CLI (Global y CN)](/es/guides/api-key-catalog/#official-qoder-cli-global--cn) - [Claude Code CLI (suscripción)](/es/guides/api-key-catalog/#claude-code-cli-subscription) +- [StepCode CLI (suscripción)](/es/guides/step-cli/) - [Antigravity CLI (ACP, local)](/es/guides/api-key-catalog/#antigravity-cli-acp-local) - [Cuota de crédito A6API](/es/guides/api-key-catalog/#a6api-credit-quota) - [Plan de codificación BigModel sobre Responses](/es/guides/api-key-catalog/#bigmodel-coding-plan-over-responses) diff --git a/docs-site/src/content/docs/es/guides/step-cli.md b/docs-site/src/content/docs/es/guides/step-cli.md new file mode 100644 index 00000000000..838bde97a84 --- /dev/null +++ b/docs-site/src/content/docs/es/guides/step-cli.md @@ -0,0 +1,75 @@ +--- +title: StepCode CLI (suscripción) +description: Envíe solicitudes de Codex a través de StepCode CLI con una suscripción Step Plan. +--- + +OpenCodex puede usar una suscripción Step Plan mediante StepCode sin llamar directamente a +`api.stepfun.com/step_plan`. El preajuste `step-cli` ejecuta la CLI oficial de StepCode +(`step --sdk-stdio`) y le declara las herramientas de cada solicitud para que el cliente pueda +aprobarlas y ejecutarlas: + +```json +{ + "providers": { + "step-cli": { + "adapter": "step-cli", + "baseUrl": "https://api.stepfun.com/step_plan" + } + } +} +``` + +- **Requisitos.** Instale StepCode CLI en `~/.stepcode/bin/step` e inicie sesión con `step login`. + La CLI obtiene su credencial de `auth.json`. +- **Credenciales.** OpenCodex no lee, copia ni reenvía el token de Step. Este preajuste tiene el + campo `keyOptional`, al igual que `claude-cli`. Para facturación directa por API, use `stepfun`. +- **Una cuenta para el proxy.** Todas las solicitudes enviadas por esta ruta consumen la cuota de + la cuenta Step Plan del usuario que ejecuta OpenCodex. El plan mide el consumo por solicitud y + aplica límites de cinco horas y semanales. Codex comparte la cuota con las sesiones de `step`. +- **Herramientas.** Las herramientas se declaran a través del SDK de StepCode. El adaptador recibe + sus llamadas por stdio y el cliente se encarga de aprobarlas y ejecutarlas. OpenCodex no monta un + servidor MCP para esta ruta ni guarda los resultados de herramientas por su cuenta. +- **Un proceso por conversación.** StepCode conserva el contexto dentro de su proceso. OpenCodex + asocia ese proceso a la identidad autenticada, el proveedor y el hilo. Si la solicitud carece de + credenciales, se abre un proceso por solicitud y las llamadas a herramientas no se pueden + continuar entre solicitudes. Mantenga el catálogo de herramientas al devolver un resultado + pendiente. Si el proceso termina, OpenCodex informa del error. Los resultados ya entregados no + se pueden reproducir por esta ruta. +- **Apagado ordenado.** El proxy espera a que terminen los procesos de StepCode dentro de su plazo + de apagado e informa de un error si no puede confirmarlo. En macOS y Linux, esto puede ocurrir si + el líder del grupo de procesos sale antes de que termine el grupo. Algunos procesos descendientes + pueden seguir ejecutándose. En POSIX, la limpieza solo envía señales al grupo mientras el líder + original se observa con vida. Bun 1.4.4 puede recoger el estado de salida del hijo antes de que + JavaScript reciba el evento de salida. En Linux, el hilo de espera nativo se usa como alternativa + cuando no está disponible la supervisión mediante pidfd. Una señal enviada al grupo entre la + recogida y la notificación de salida podría alcanzar un PGID reutilizado. Bun no expone a + JavaScript un `pidfd` ni otro identificador que acredite la pertenencia del proceso a nivel de + llamada al sistema. Para eliminar ese intervalo hace falta un supervisor nativo o un cambio en + Bun. El responsable del proyecto aceptó este riesgo residual el 2026-11-19. + En Windows, StepCode comprueba que el proceso lanzador original sigue en ejecución antes de + iniciar `taskkill /T /F`. La utilidad busca el PID numérico después de iniciarse. Si el lanzador + termina y Windows reutiliza su PID entre la comprobación y esa búsqueda, la señal podría + alcanzar un árbol de procesos ajeno. Para cerrar ese intervalo hay que establecer la pertenencia + del proceso desde el arranque, por ejemplo con un objeto de trabajo que finalice los procesos al + cerrarse, y usar su identificador de objeto para terminarlos. El responsable del proyecto aceptó + este riesgo residual el 2026-11-19 junto con el riesgo de POSIX relativo al orden de recogida y + notificación de salida. Si el lanzador ya ha salido o la limpieza sigue sin confirmarse después + de que la utilidad haya podido ejecutarse, OpenCodex pone la sesión en cuarentena, registra una + advertencia fija e informa de que la limpieza quedó incompleta. +- **Límites de sesión.** Si una herramienta tarda más de dos minutos en devolver un resultado, + el turno informa del error `step_cli_tool_result_too_late`. El protocolo no permite reemplazar + el mensaje de sistema de la sesión. OpenCodex antepone las instrucciones del cliente al turno. +- **Catálogo de herramientas.** El límite es de **128 herramientas / 2 MiB**, igual que en + `qoder`, `codebuddy` y `claude-cli`. Codex incorpora todas las herramientas MCP a su catálogo. + En Codex 0.162.0 se midieron 1749 herramientas y 2,5 MB. Si supera el límite, el error indica + ambos valores. Desactive o restrinja los servidores MCP de este proveedor. +- **Imágenes.** Los modelos se anuncian como compatibles con texto. Aunque `step-5-preview` y + `step-3.7-flash` pueden aceptar imágenes en el servicio, esta ruta las rechaza con + `unsupported_input_modality`. Si hay un servicio de visión auxiliar, convierte las imágenes en + descripciones de texto antes de reenviarlas. +- **Verificación.** Ejecute `ocx provider test step-cli`. + +> **Condiciones.** Este preajuste usa su suscripción Step Plan mediante la CLI oficial. La +> documentación del plan describe los endpoints para herramientas de programación de terceros. +> StepCode publica `--sdk-stdio` para clientes externos con licencia MIT. Consulte con 阶跃星辰 +> si las condiciones de su plan permiten usar esa interfaz a través de un proxy. diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index 2d00cb004e3..70739f6919d 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -213,7 +213,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo | Campo | Tipo | Descripción | | --- | --- | --- | -| `adapter` | `string` | Uno de `openai-chat`, `openai-responses`, `anthropic`, `claude-cli`, `google`, `kiro`, `cursor`, `ollama-native`, `azure-openai` (o alias `azure`), `codebuddy`, `qoder`. | +| `adapter` | `string` | Uno de `openai-chat`, `openai-responses`, `anthropic`, `claude-cli`, `step-cli`, `google`, `kiro`, `cursor`, `ollama-native`, `azure-openai` (o alias `azure`), `codebuddy`, `qoder`. | | `baseUrl` | `string` | URL de base ascendente API. La mayoría de los puntos finales fijos incorporados ignoran una falta de coincidencia; los ajustes preestablecidos de clave seguros contra colisiones conservan un destino personalizado con el mismo nombre más antiguo. | | `proxy?` | `string \| null` | Ruta de salida por proveedor. Omita que herede la decisión de proxy global; use `"direct"` o `null` para forzar la salida directa; o proporcione una URL proxy absoluta `http://`, `https://`, `socks5://` o `socks5h://`. Se rechaza una cadena vacía. | | `noProxy?` | `string \| string[]` | Destinos a los que este proveedor llega directamente, utilizando la sintaxis de patrón de host `NO_PROXY`. Una coincidencia pasa por alto tanto el propio proxy de este proveedor como un proxy global heredado. | diff --git a/docs-site/src/content/docs/fr/getting-started/quickstart.md b/docs-site/src/content/docs/fr/getting-started/quickstart.md index b8d6d413f72..ab2f8598d00 100644 --- a/docs-site/src/content/docs/fr/getting-started/quickstart.md +++ b/docs-site/src/content/docs/fr/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` vous accompagne dans les étapes suivantes : -1. **Choix d’un fournisseur** — sélectionnez l’un des 111 préréglages intégrés au registre, ou `custom` pour saisir une +1. **Choix d’un fournisseur** — sélectionnez l’un des 112 préréglages intégrés au registre, ou `custom` pour saisir une URL de base et un adaptateur. 2. **Clé API** — collez une clé ou référencez une variable d’environnement telle que `${ANTHROPIC_API_KEY}`. 3. **Modèle par défaut** — pour les fournisseurs clés, locaux et personnalisés, acceptez le préréglage ou saisissez un identifiant de modèle. diff --git a/docs-site/src/content/docs/fr/guides/providers.md b/docs-site/src/content/docs/fr/guides/providers.md index 400994e490f..dc03db40597 100644 --- a/docs-site/src/content/docs/fr/guides/providers.md +++ b/docs-site/src/content/docs/fr/guides/providers.md @@ -310,7 +310,7 @@ existante n'est pas concernée. ## 3. Catalogue des clés API -opencodex fournit 111 préréglages intégrés : 89 à clé, 18 OAuth, trois locaux et un préréglage par défaut de +opencodex fournit 112 préréglages intégrés : 90 à clé, 18 OAuth, trois locaux et un préréglage par défaut de transfert ChatGPT. Dans le tableau de bord, le sélecteur **Ajouter un fournisseur** ouvre le tableau de bord du fournisseur à clé, valide la clé et l'enregistre ; la validation dépend du fournisseur. Parmi les entrées notables : diff --git a/docs-site/src/content/docs/getting-started/quickstart.md b/docs-site/src/content/docs/getting-started/quickstart.md index 7305bd426e0..f215bec79b6 100644 --- a/docs-site/src/content/docs/getting-started/quickstart.md +++ b/docs-site/src/content/docs/getting-started/quickstart.md @@ -21,7 +21,7 @@ ocx init `ocx init` walks you through: -1. **Pick a provider** — choose one of the 111 built-in registry presets or `custom` to type a base +1. **Pick a provider** — choose one of the 112 built-in registry presets or `custom` to type a base URL and adapter. 2. **API key** — paste a key, or reference an environment variable like `${ANTHROPIC_API_KEY}`. 3. **Default model** — for key, local, and custom providers, accept the preset or enter a model id. diff --git a/docs-site/src/content/docs/guides/api-key-catalog.md b/docs-site/src/content/docs/guides/api-key-catalog.md index 1f138e57bc5..7939caf8112 100644 --- a/docs-site/src/content/docs/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/guides/api-key-catalog.md @@ -9,7 +9,7 @@ stay on that page. For subscription account rotation, see [`reset-near-weighted`](/reference/configuration/providers/#reset-near-weighted) for the Codex and Anthropic OAuth pools. API-key pools use their own [key selection settings](/reference/configuration/providers/). -opencodex ships 111 built-in presets: 89 key-based, 18 OAuth, three local, and one default +opencodex ships 112 built-in presets: 90 key-based, 18 OAuth, three local, and one default ChatGPT-forward preset. The dashboard's **Add provider** picker opens a key provider's dashboard, validates the key where the provider can check one, and stores it. Notable entries: diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index fd74cb812cb..5fa69322b57 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -794,6 +794,7 @@ are on the [API-key catalog](/guides/api-key-catalog/) page. Its sections: - [Official CodeBuddy Code CLI (Global & CN)](/guides/api-key-catalog/#official-codebuddy-code-cli-global--cn) - [Official Qoder CLI (Global & CN)](/guides/api-key-catalog/#official-qoder-cli-global--cn) - [Claude Code CLI (subscription)](/guides/api-key-catalog/#claude-code-cli-subscription) +- [StepCode CLI (subscription)](/guides/step-cli/) - [Antigravity CLI (ACP, local)](/guides/api-key-catalog/#antigravity-cli-acp-local) - [A6API credit quota](/guides/api-key-catalog/#a6api-credit-quota) - [BigModel Coding Plan over Responses](/guides/api-key-catalog/#bigmodel-coding-plan-over-responses) diff --git a/docs-site/src/content/docs/guides/step-cli.md b/docs-site/src/content/docs/guides/step-cli.md new file mode 100644 index 00000000000..ab55701c8e6 --- /dev/null +++ b/docs-site/src/content/docs/guides/step-cli.md @@ -0,0 +1,79 @@ +--- +title: StepCode CLI (subscription) +description: Route Codex requests through the StepCode CLI with a Step Plan subscription. +--- + +OpenCodex can spend a Step Plan subscription through StepCode's own harness instead of calling +`api.stepfun.com/step_plan` directly. The `step-cli` preset runs the official StepCode CLI +(`step --sdk-stdio`) and declares your request's tools to it, so no tool ever executes inside +StepCode: + +```json +{ + "providers": { + "step-cli": { + "adapter": "step-cli", + "baseUrl": "https://api.stepfun.com/step_plan" + } + } +} +``` + +- **Prerequisites:** install the StepCode CLI (it self-installs to `~/.stepcode/bin/step`) and sign + in once with `step login`. The CLI resolves its own credential from its `auth.json`. +- **No credential stored:** this row holds no Step API key, and OpenCodex never reads, copies or + forwards a Step token. It is a keyless key row (`keyOptional`) for the same reason the + `claude-cli` preset is. Use `stepfun` if you want direct API billing instead. +- **One sign-in serves the whole proxy:** the CLI reads the Step Plan login of the user OpenCodex + runs as, so every request routed through this row spends that one account. Step Plan is + prompt-metered with a five-hour and a weekly limit, and a Codex session's traffic spends the same + quota your interactive `step` sessions do. +- **Tools stay with the client:** the request's tool catalog is declared to StepCode as SDK tools, + and a call comes back over stdio as a reverse request the adapter captures. Approval and execution + stay in your client; OpenCodex stages no MCP server and holds no tool results itself. +- **One process per conversation:** StepCode carries conversation context only inside its own + process — its input channel reduces every message to text and images — so a conversation maps onto + one long-lived process that OpenCodex keys to your authenticated caller identity, provider and + thread. Keyless callers receive a separate process per request and cannot continue tool calls + across requests. Keep the tool catalog unchanged when returning a held result. A process that dies is reported, + not silently restarted, because tool results already delivered cannot be replayed through this + route. +- **Graceful stop** waits for StepCode process cleanup within the proxy's shutdown window and + reports a shutdown failure if it cannot confirm cleanup. On macOS and Linux, this can happen + if the process group leader exits before group termination. Descendants may still be running. + On POSIX, cleanup signals the group only while the original leader is observed alive. Bun 1.4.4 + can reap the child before JavaScript receives the exit event. On Linux, the native waiter thread + is a fallback when pidfd monitoring is unavailable. A group signal between reap and exit + notification could reach a reused PGID. Bun exposes no `pidfd` or other syscall-level ownership + handle to JavaScript. Closing this window requires a native supervisor or a Bun change. The owner + accepted this residual risk on 2026-11-19. + On Windows, StepCode checks that the original wrapper is still alive before launching + `taskkill /T /F`. The helper resolves the numeric PID after launch. If the wrapper exits and + Windows reuses its PID between the liveness check and that lookup, the signal could reach an + unrelated process tree. Closing this window requires establishing ownership at launch, for + example with a kill-on-close Job Object, and terminating through that handle. The owner + accepted this residual risk on 2026-11-19 alongside the POSIX reap-ordering risk. + If the wrapper has already exited or cleanup is unconfirmed after the helper may have run, + OpenCodex quarantines the session, logs a fixed warning and reports incomplete cleanup. +- **Two documented limits:** a tool that takes longer than two minutes to come back exceeds the + CLI's own tool-result window and the turn reports `step_cli_tool_result_too_late`; and the CLI's + session system prompt cannot be replaced through this protocol, so your instructions are prepended + to the turn rather than installed as the system prompt. +- **Tool-catalog ceiling:** this row shares the CLI family's **128-tool / 2 MiB** limit. A real Codex + client can exceed it, because Codex flattens every MCP server's tools into the function catalog — + measured on Codex 0.162.0 at 1749 tools / 2.5 MB. The turn is refused rather than silently trimmed + (a tool the client thinks exists but that never reaches the model is worse), and the error names both + numbers. A stock Codex install without MCP servers carries roughly ten built-in tools and works; if you + hit the ceiling, disable or narrow MCP servers for this provider. `qoder`, `codebuddy` and + `claude-cli` enforce the same bound. +- **Input media:** the row publishes text-only models. `step-5-preview` and `step-3.7-flash` accept + images upstream, but no headless StepCode turn has been shown to hand image bytes to the model, so + an image sent straight to this provider is refused (`unsupported_input_modality`). With the vision + sidecar on the request path images are captioned into text first. +- **Verify:** `ocx provider test step-cli`. + +> **Terms:** this preset spends your Step Plan subscription through StepCode's own CLI. Step's +> Step Plan documentation lists third-party coding tools against the same endpoints, and +> `--sdk-stdio` is StepCode's published, MIT-licensed external-client surface, but whether driving +> that harness from a proxy fits your plan's terms is a question between you and 阶跃星辰. +> OpenCodex does not convert the login into an API key. diff --git a/docs-site/src/content/docs/ja/getting-started/quickstart.md b/docs-site/src/content/docs/ja/getting-started/quickstart.md index 69946eb41b2..0664f063d62 100644 --- a/docs-site/src/content/docs/ja/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ja/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` では次の手順を説明します。 -1. **プロバイダーを選択してください** — 111 個の組み込みレジストリプリセットのいずれか、または `custom` を選択してベース URL とアダプターを入力します。 +1. **プロバイダーを選択してください** — 112 個の組み込みレジストリプリセットのいずれか、または `custom` を選択してベース URL とアダプターを入力します。 2. **API キー** — キーを貼り付けるか、`${ANTHROPIC_API_KEY}` のような環境変数を参照します。 3. **デフォルト モデル** — キー、ローカル、カスタム プロバイダーの場合は、プリセットを受け入れるか、モデル ID を入力します。 4. **プロキシ ポート** — デフォルトは `10100` です。 diff --git a/docs-site/src/content/docs/ja/guides/providers.md b/docs-site/src/content/docs/ja/guides/providers.md index 6f7c79d935e..e587a01d379 100644 --- a/docs-site/src/content/docs/ja/guides/providers.md +++ b/docs-site/src/content/docs/ja/guides/providers.md @@ -210,7 +210,7 @@ Kiro のログインには Kiro CLI が必要です。Unix では `curl -fsSL ht ## 3. API キーカタログ -opencodex には組み込みプリセットが 111 個含まれています。キー方式 89、OAuth 18、ローカル 3、 +opencodex には組み込みプリセットが 112 個含まれています。キー方式 90、OAuth 18、ローカル 3、 デフォルト ChatGPT 転送プリセット 1 です。ダッシュボードの **Add provider** ピッカーはキー発行ページを開き、 入力したキーを検証した後保存します(検証はプロバイダー固有です)。主な項目は以下のとおりです: diff --git a/docs-site/src/content/docs/ko/getting-started/quickstart.md b/docs-site/src/content/docs/ko/getting-started/quickstart.md index 8e6e743868a..54a0229caf7 100644 --- a/docs-site/src/content/docs/ko/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ko/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init`은 다음 과정을 안내합니다: -1. **프로바이더 선택** — 내장 레지스트리 프리셋 111개 중 하나를 고르거나 `custom`을 선택해 base URL과 adapter를 직접 입력합니다. +1. **프로바이더 선택** — 내장 레지스트리 프리셋 112개 중 하나를 고르거나 `custom`을 선택해 base URL과 adapter를 직접 입력합니다. 2. **API 키** — 키를 붙여넣거나 `${ANTHROPIC_API_KEY}` 같은 환경 변수를 참조합니다. 3. **기본 모델** — 키, 로컬, custom 프로바이더에서는 프리셋을 그대로 쓰거나 모델 ID를 직접 입력합니다. 4. **프록시 포트** — 기본값은 `10100`입니다. diff --git a/docs-site/src/content/docs/ko/guides/providers.md b/docs-site/src/content/docs/ko/guides/providers.md index b187921bba2..95ab3cd7d79 100644 --- a/docs-site/src/content/docs/ko/guides/providers.md +++ b/docs-site/src/content/docs/ko/guides/providers.md @@ -212,7 +212,7 @@ Kiro 로그인에는 Kiro CLI가 필요합니다. Unix에서는 `curl -fsSL http ## 3. API 키 카탈로그 -opencodex에는 빌트인 프리셋이 111개 들어 있습니다. 키 방식 89개, OAuth 18개, 로컬 3개, +opencodex에는 빌트인 프리셋이 112개 들어 있습니다. 키 방식 90개, OAuth 18개, 로컬 3개, 기본 ChatGPT 포워드 프리셋 1개입니다. 대시보드의 **Add provider** 선택기는 키 발급 페이지를 열고, 입력한 키를 검증한 뒤 저장합니다(검증은 프로바이더별로 다릅니다). 주요 항목은 다음과 같습니다: diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 4a56333e14c..b123d0b65ba 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -336,7 +336,7 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | Field | Type | Meaning | | --- | --- | --- | -| `adapter` | `string` | One of `openai-chat`, `openai-responses`, `anthropic`, `claude-cli`, `google`, `kiro`, `cursor`, `ollama-native`, `azure-openai` (or alias `azure`), `codebuddy`, `qoder`. | +| `adapter` | `string` | One of `openai-chat`, `openai-responses`, `anthropic`, `claude-cli`, `step-cli`, `google`, `kiro`, `cursor`, `ollama-native`, `azure-openai` (or alias `azure`), `codebuddy`, `qoder`. | | `baseUrl` | `string` | Upstream API base URL. Most built-in fixed endpoints ignore a mismatch; collision-safe key presets preserve an older same-named custom destination. | | `proxy?` | `string \| null` | Per-provider egress route. Omit it to inherit the global proxy decision; use `"direct"` or `null` to force direct egress; or provide an absolute `http://`, `https://`, `socks5://`, or `socks5h://` proxy URL. An empty string is rejected. | | `noProxy?` | `string \| string[]` | Destinations this provider reaches directly, using `NO_PROXY` host-pattern syntax. A match bypasses both this provider's own proxy and an inherited global proxy. | diff --git a/docs-site/src/content/docs/ru/getting-started/quickstart.md b/docs-site/src/content/docs/ru/getting-started/quickstart.md index 32cd2800844..3c7a9f180b2 100644 --- a/docs-site/src/content/docs/ru/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ru/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` проведёт вас по следующим шагам: -1. **Выбор провайдера** — выберите один из 111 встроенных пресетов реестра или `custom`, чтобы +1. **Выбор провайдера** — выберите один из 112 встроенных пресетов реестра или `custom`, чтобы ввести базовый URL и адаптер вручную. 2. **API-ключ** — вставьте ключ или сошлитесь на переменную окружения вида `${ANTHROPIC_API_KEY}`. 3. **Модель по умолчанию** — для провайдеров с ключом, локальных и `custom` примите значение из diff --git a/docs-site/src/content/docs/ru/guides/providers.md b/docs-site/src/content/docs/ru/guides/providers.md index 772b7992c54..1bf3f7a7145 100644 --- a/docs-site/src/content/docs/ru/guides/providers.md +++ b/docs-site/src/content/docs/ru/guides/providers.md @@ -222,7 +222,7 @@ Inline JSON и лишние позиционные аргументы откло ## 3. Каталог API-ключей -opencodex поставляется с 111 встроенными пресетами: 89 на основе ключей, 18 OAuth, три локальных и +opencodex поставляется с 112 встроенными пресетами: 90 на основе ключей, 18 OAuth, три локальных и один пресет ChatGPT-форварда по умолчанию. Селектор **Add provider** в дашборде открывает страницу выдачи ключей провайдера, проверяет ключ и сохраняет его; проверка зависит от провайдера. Наиболее заметные записи: diff --git a/docs-site/src/content/docs/tr/getting-started/quickstart.md b/docs-site/src/content/docs/tr/getting-started/quickstart.md index 99ba7d3851f..c10f65b30ea 100644 --- a/docs-site/src/content/docs/tr/getting-started/quickstart.md +++ b/docs-site/src/content/docs/tr/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` adım adım size rehberlik eder: -1. **Bir sağlayıcı seçin** — yerleşik kayıt defterindeki 111 önayardan birini +1. **Bir sağlayıcı seçin** — yerleşik kayıt defterindeki 112 önayardan birini veya bir temel URL ile adaptör yazmak için `custom` seçeneğini belirleyin. 2. **API anahtarı** — bir anahtar yapıştırın veya `${ANTHROPIC_API_KEY}` gibi bir ortam değişkenine başvurun. diff --git a/docs-site/src/content/docs/tr/guides/providers.md b/docs-site/src/content/docs/tr/guides/providers.md index 47b195d3632..03317bed745 100644 --- a/docs-site/src/content/docs/tr/guides/providers.md +++ b/docs-site/src/content/docs/tr/guides/providers.md @@ -342,7 +342,7 @@ olmayan bir makineden oturum açmak bundan etkilenmez. ## 3. API anahtarı kataloğu -opencodex 111 yerleşik önayar ile birlikte gelir: 89 anahtar tabanlı, 18 +opencodex 112 yerleşik önayar ile birlikte gelir: 90 anahtar tabanlı, 18 OAuth, üç yerel ve bir varsayılan ChatGPT iletme önayarı. Kontrol panelinin **Sağlayıcı ekle** seçicisi bir anahtar sağlayıcısının kontrol panelini açar, anahtarı doğrular ve saklar; doğrulama sağlayıcıya özgüdür. Dikkate değer diff --git a/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md b/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md index 81796822e10..4d93d4dd8ff 100644 --- a/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md +++ b/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` 会引导你完成: -1. **选择 provider** — 从内置 registry 的 111 个预设中选择一个,或选择 `custom` 手动输入 base URL 和 adapter。 +1. **选择 provider** — 从内置 registry 的 112 个预设中选择一个,或选择 `custom` 手动输入 base URL 和 adapter。 2. **API key** — 粘贴一个 key,或引用一个环境变量,例如 `${ANTHROPIC_API_KEY}`。 3. **默认模型** — 对于 key、本地和 custom provider,接受预设值或输入模型 id。 4. **代理端口** — 默认为 `10100`。 diff --git a/docs-site/src/content/docs/zh-cn/guides/providers.md b/docs-site/src/content/docs/zh-cn/guides/providers.md index 791b46ba2b7..ffbe65d2206 100644 --- a/docs-site/src/content/docs/zh-cn/guides/providers.md +++ b/docs-site/src/content/docs/zh-cn/guides/providers.md @@ -222,7 +222,7 @@ API Key 提供商,也不负责让 WorkBuddy 桌面客户端使用 OpenCodex ## 3. API 密钥目录 -opencodex 内置 111 个预设:89 个密钥预设、18 个 OAuth 预设、3 个本地预设,以及 1 个默认的 +opencodex 内置 112 个预设:90 个密钥预设、18 个 OAuth 预设、3 个本地预设,以及 1 个默认的 ChatGPT 转发预设。仪表盘的 **Add provider** 选择器会打开密钥提供商的控制台,验证并保存密钥。 验证因提供商而异。主要条目包括: diff --git a/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md b/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md index b2196e4e7a0..0c163353f4d 100644 --- a/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md +++ b/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` 會引導你完成: -1. **選擇 provider** —— 從內建 registry 的 111 個預設中選擇一個,或選擇 `custom` 手動輸入 +1. **選擇 provider** —— 從內建 registry 的 112 個預設中選擇一個,或選擇 `custom` 手動輸入 base URL 和 adapter。 2. **API key** —— 貼上一個 key,或引用一個環境變數,例如 `${ANTHROPIC_API_KEY}`。 3. **預設模型** —— 對於 API key、本機和 custom provider,可接受預設值或輸入模型 id。 diff --git a/docs-site/src/content/docs/zh-tw/guides/providers.md b/docs-site/src/content/docs/zh-tw/guides/providers.md index 348135b753d..a33b7a71825 100644 --- a/docs-site/src/content/docs/zh-tw/guides/providers.md +++ b/docs-site/src/content/docs/zh-tw/guides/providers.md @@ -264,7 +264,7 @@ database 並移除目前的 WAL、SHM 與 journal sidecar,再發布先前的 s ## 3. API 金鑰目錄 -opencodex 內建 111 個 preset:89 個 key-based、18 個 OAuth、3 個 local,以及 1 個預設 ChatGPT-forward +opencodex 內建 112 個 preset:90 個 key-based、18 個 OAuth、3 個 local,以及 1 個預設 ChatGPT-forward preset。儀表板的 **Add provider** picker 會開啟 key provider 的 dashboard、驗證金鑰並儲存;驗證方式 依 provider 而異。主要條目如下。 diff --git a/gui/classic/src/components/add-provider-form-pane.tsx b/gui/classic/src/components/add-provider-form-pane.tsx index 37c98a76545..886b012a17b 100644 --- a/gui/classic/src/components/add-provider-form-pane.tsx +++ b/gui/classic/src/components/add-provider-form-pane.tsx @@ -151,7 +151,7 @@ export function AddProviderFormPane({
{t("modal.subscriptionCliTitle")}
- +
) : preset.keyOptional ? ( diff --git a/gui/src/components/add-provider-form-pane.tsx b/gui/src/components/add-provider-form-pane.tsx index 25d67c5e9f5..a936cb29828 100644 --- a/gui/src/components/add-provider-form-pane.tsx +++ b/gui/src/components/add-provider-form-pane.tsx @@ -150,7 +150,7 @@ export function AddProviderFormPane({
{t("modal.subscriptionCliTitle")}
- +
) : preset.keyOptional ? ( diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index f0ec07f24fc..6a981960719 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -3044,7 +3044,7 @@ export const de: Record = { "modal.invalidPreset": "Diese integrierte Anbietervorlage ist unvollständig. Starten Sie den Proxy neu und versuchen Sie es erneut.", "modal.freeTierTitle": "Kostenloser Tarif", "modal.subscriptionCliTitle": "Abo-CLI, kein API-Schlüssel", - "modal.subscriptionCliWarning": "Dieser Anbieter verwendet keinen API-Schlüssel. Er steuert die offizielle, auf diesem Rechner angemeldete Claude Code CLI ({cmd}) und rechnet über dieses Claude-Abonnement ab. OpenCodex speichert dafür keinen Schlüssel, und ein hier eingegebener Schlüssel wird nie verwendet. Für die Abrechnung per API-Schlüssel füge stattdessen {apiProvider} hinzu.", + "modal.subscriptionCliWarning": "Dieser Anbieter verwendet keinen API-Schlüssel. Er steuert die offizielle, auf diesem Rechner angemeldete {cli} ({cmd}) und rechnet über dieses {plan}-Abonnement ab. OpenCodex speichert dafür keinen Schlüssel, und ein hier eingegebener Schlüssel wird nie verwendet. Für die Abrechnung per API-Schlüssel füge stattdessen {apiProvider} hinzu.", "modal.subscriptionCliWarningAgy": "Dieser Anbieter nutzt die offizielle Antigravity CLI, die auf dem Proxy-Host angemeldet ist ({cmd}). Die Nutzung wird über dieses Google-Antigravity-Konto abgerechnet. Google erlaubt nur interaktive, vom Nutzer gesteuerte Nutzung. OpenCodex lehnt Subagenten-Turns, Kombinationen und Subagenten-Fallback-Routing ab und prüft anhand der beobachteten Verbindung, ob Anfragen lokal sind. Eine nicht deklarierte Loopback-Weiterleitung kann entfernte Anfragen lokal erscheinen lassen, wenn sie keine Weiterleitungsheader übermittelt. Tragen Sie den Reverse-Proxy für den öffentlichen Listener in dashboardTrustedProxy ein oder leiten Sie diesen Port nicht weiter. Ein API-Schlüssel ist weder erforderlich noch wird einer gespeichert. Für programmatische oder geteilte Arbeitslasten fügen Sie stattdessen {apiProvider} hinzu.", "modal.freeTierDefault": "Kein API-Schlüssel nötig. Funktioniert sofort.", "modal.tab.accounts": "Konten", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index bc79c0e65d7..ee195119520 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -1877,7 +1877,7 @@ export const en = { "modal.invalidPreset": "This built-in provider preset is incomplete. Restart the proxy and try again.", "modal.freeTierTitle": "Free tier", "modal.subscriptionCliTitle": "Subscription CLI, not an API key", - "modal.subscriptionCliWarning": "This provider does not use an API key. It drives the official Claude Code CLI signed in on this machine ({cmd}) and bills that Claude subscription account. OpenCodex stores no key for it, and a key entered here is never used. For API-key billing, add {apiProvider} instead.", + "modal.subscriptionCliWarning": "This provider does not use an API key. It drives the official {cli} signed in on this machine ({cmd}) and bills that {plan} subscription account. OpenCodex stores no key for it, and a key entered here is never used. For API-key billing, add {apiProvider} instead.", "modal.subscriptionCliWarningAgy": "This provider uses the official Antigravity CLI signed in on the proxy host ({cmd}). Usage bills that Google Antigravity account. Google permits interactive, user-directed use only. OpenCodex refuses subagent turns, combos and subagent fallback routing, and checks locality from the connection it sees. An undeclared loopback relay can make remote requests appear local if it passes no forwarding headers. For the public listener, declare the reverse proxy in dashboardTrustedProxy or keep this port out of the relay. No API key is needed or stored. For programmatic or shared workloads, add {apiProvider} instead.", "modal.freeTierDefault": "No API key required. Works out of the box.", "modal.tab.accounts": "Accounts", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 74f9deb3d30..40c8dcc9c2a 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -1850,7 +1850,7 @@ export const fr: Record = { "modal.invalidPreset": "Ce préréglage de fournisseur intégré est incomplet. Redémarrez le proxy et réessayez.", "modal.freeTierTitle": "Offre gratuite", "modal.subscriptionCliTitle": "CLI d'abonnement, pas une clé API", - "modal.subscriptionCliWarning": "Ce fournisseur n'utilise pas de clé API. Il pilote la CLI officielle Claude Code connectée sur cette machine ({cmd}) et facture ce compte d'abonnement Claude. OpenCodex ne stocke aucune clé pour lui, et une clé saisie ici n'est jamais utilisée. Pour une facturation par clé API, ajoutez plutôt {apiProvider}.", + "modal.subscriptionCliWarning": "Ce fournisseur n'utilise pas de clé API. Il pilote la {cli} officielle connectée sur cette machine ({cmd}) et facture ce compte d'abonnement {plan}. OpenCodex ne stocke aucune clé pour lui, et une clé saisie ici n'est jamais utilisée. Pour une facturation par clé API, ajoutez plutôt {apiProvider}.", "modal.subscriptionCliWarningAgy": "Ce fournisseur utilise la CLI officielle Antigravity connectée sur l’hôte du proxy ({cmd}). L’utilisation est facturée à ce compte Google Antigravity. Google autorise uniquement un usage interactif dirigé par l’utilisateur. OpenCodex refuse les tours de sous-agent, les combos et le routage de repli des sous-agents. Il juge si une requête est locale d’après la connexion observée. Un relais local non déclaré peut faire passer des requêtes distantes pour des requêtes locales s’il ne transmet aucun en-tête de transfert. Pour le port d’écoute public, déclarez le proxy inverse dans dashboardTrustedProxy ou ne relayez pas ce port. Aucune clé API n’est nécessaire ni stockée. Pour des tâches effectuées par programme ou des usages partagés, ajoutez plutôt {apiProvider}.", "modal.freeTierDefault": "Aucune clé API requise. Fonctionne immédiatement.", "modal.tab.accounts": "Comptes", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index a1572c72e40..da575530c86 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -1760,7 +1760,7 @@ export const ja: Record = { "modal.invalidPreset": "この組み込みプロバイダープリセットは不完全です。プロキシを再起動してもう一度お試しください。", "modal.freeTierTitle": "無料枠", "modal.subscriptionCliTitle": "サブスクリプション CLI(API キーではありません)", - "modal.subscriptionCliWarning": "このプロバイダーは API キーを使用しません。このマシンでサインイン済みの公式 Claude Code CLI({cmd})を実行し、その Claude サブスクリプションアカウントに課金されます。OpenCodex はキーを保存せず、ここに入力したキーが使われることもありません。API キーで課金する場合は、代わりに {apiProvider} を追加してください。", + "modal.subscriptionCliWarning": "このプロバイダーは API キーを使用しません。このマシンでサインイン済みの公式 {cli}({cmd})を実行し、その {plan} サブスクリプションアカウントに課金されます。OpenCodex はキーを保存せず、ここに入力したキーが使われることもありません。API キーで課金する場合は、代わりに {apiProvider} を追加してください。", "modal.subscriptionCliWarningAgy": "このプロバイダーは、プロキシホストでサインイン済みの公式 Antigravity CLI({cmd})を使用します。利用料金はその Google Antigravity アカウントに請求されます。Google が認めるのは、ユーザーが指示する対話的な利用のみです。OpenCodex はサブエージェントのターン、コンボ、サブエージェントのフォールバックルーティングを拒否し、観測した接続からローカルかどうかを判定します。未登録のループバック中継が転送ヘッダーを一切渡さない場合、リモートのリクエストがローカルに見えることがあります。公開リスナーでは、リバースプロキシを dashboardTrustedProxy に登録するか、このポートを中継しないでください。API キーは不要で、保存もされません。プログラムによる利用や共有ワークロードには、代わりに {apiProvider} を追加してください。", "modal.freeTierDefault": "API キー不要です。そのまま利用できます。", "modal.tab.accounts": "アカウント", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 3040814015b..b2e55a81d97 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -3091,7 +3091,7 @@ export const ko: Record = { "modal.invalidPreset": "내장 프로바이더 설정이 완전하지 않습니다. 프록시를 다시 시작한 뒤 재시도하세요.", "modal.freeTierTitle": "무료 티어", "modal.subscriptionCliTitle": "API 키가 아닌 구독 CLI 방식", - "modal.subscriptionCliWarning": "이 프로바이더는 API 키를 쓰지 않습니다. 이 컴퓨터에 로그인된 공식 Claude Code CLI({cmd})를 실행하고, 요금은 그 Claude 구독 계정에 청구됩니다. OpenCodex는 이 프로바이더의 키를 저장하지 않으며, 여기에 입력한 키는 쓰이지 않습니다. API 키로 과금하려면 대신 {apiProvider}를 추가하세요.", + "modal.subscriptionCliWarning": "이 프로바이더는 API 키를 쓰지 않습니다. 이 컴퓨터에 로그인된 공식 {cli}({cmd})를 실행하고, 요금은 그 {plan} 구독 계정에 청구됩니다. OpenCodex는 이 프로바이더의 키를 저장하지 않으며, 여기에 입력한 키는 쓰이지 않습니다. API 키로 과금하려면 대신 {apiProvider}를 추가하세요.", "modal.subscriptionCliWarningAgy": "이 프로바이더는 프록시 호스트에 로그인된 공식 Antigravity CLI({cmd})를 사용합니다. 사용 요금은 해당 Google Antigravity 계정에 청구됩니다. Google은 사용자가 직접 지시하는 대화형 사용만 허용합니다. OpenCodex는 서브에이전트 턴, 콤보, 서브에이전트 폴백 라우팅을 거부하고, 실제 연결을 기준으로 로컬 요청인지 판단합니다. 등록되지 않은 루프백 중계가 전달 헤더를 보내지 않으면 원격 요청이 로컬로 보일 수 있습니다. 공개 리스너에서는 역방향 프록시를 dashboardTrustedProxy에 등록하거나 이 포트를 중계하지 마세요. API 키는 필요하지 않으며 저장되지 않습니다. 프로그램으로 실행하는 작업이나 공유 작업에는 대신 {apiProvider}를 추가하세요.", "modal.freeTierDefault": "API 키가 필요 없습니다. 바로 사용할 수 있습니다.", "modal.tab.accounts": "계정", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 5a625bd0eaa..38249454476 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -1861,7 +1861,7 @@ export const pt: Record = { "modal.invalidPreset": "Este preset de provedor integrado está incompleto. Reinicie o proxy e tente novamente.", "modal.freeTierTitle": "Plano gratuito", "modal.subscriptionCliTitle": "CLI por assinatura, não chave de API", - "modal.subscriptionCliWarning": "Este provedor não usa chave de API. Ele aciona a CLI oficial do Claude Code autenticada nesta máquina ({cmd}) e cobra da conta de assinatura do Claude. O OpenCodex não armazena nenhuma chave para ele, e uma chave informada aqui nunca é usada. Para cobrança por chave de API, adicione {apiProvider}.", + "modal.subscriptionCliWarning": "Este provedor não usa chave de API. Ele aciona a {cli} oficial autenticada nesta máquina ({cmd}) e cobra da conta de assinatura {plan}. O OpenCodex não armazena nenhuma chave para ele, e uma chave informada aqui nunca é usada. Para cobrança por chave de API, adicione {apiProvider}.", "modal.subscriptionCliWarningAgy": "Este provedor usa a CLI oficial do Antigravity com sessão iniciada no host do proxy ({cmd}). O uso é cobrado dessa conta do Google Antigravity. O Google permite apenas o uso interativo conduzido pelo usuário. O OpenCodex recusa turnos de subagentes, combos e roteamento de fallback de subagentes e verifica se a solicitação é local pela conexão observada. Um intermediário de loopback não declarado pode fazer solicitações remotas parecerem locais se não repassar cabeçalhos de encaminhamento. Para o listener público, declare o proxy reverso em dashboardTrustedProxy ou não encaminhe essa porta. Nenhuma chave de API é necessária ou armazenada. Para tarefas executadas por programas ou uso compartilhado, adicione {apiProvider}.", "modal.freeTierDefault": "Não requer chave de API. Funciona de imediato.", "modal.tab.accounts": "Contas", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index b37f75f522d..c08fcdfe96e 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -1836,7 +1836,7 @@ export const ru: Record = { "modal.invalidPreset": "Этот встроенный пресет провайдера неполный. Перезапустите прокси и попробуйте ещё раз.", "modal.freeTierTitle": "Бесплатный тариф", "modal.subscriptionCliTitle": "CLI по подписке, а не API-ключ", - "modal.subscriptionCliWarning": "Этот провайдер не использует API-ключ. Он запускает официальный Claude Code CLI, в котором выполнен вход на этом компьютере ({cmd}), и списывает оплату с этой подписки Claude. OpenCodex не хранит для него ключ, а введённый здесь ключ никогда не используется. Для оплаты по API-ключу добавьте вместо него {apiProvider}.", + "modal.subscriptionCliWarning": "Этот провайдер не использует API-ключ. Он запускает официальный {cli}, в котором выполнен вход на этом компьютере ({cmd}), и списывает оплату с этой подписки {plan}. OpenCodex не хранит для него ключ, а введённый здесь ключ никогда не используется. Для оплаты по API-ключу добавьте вместо него {apiProvider}.", "modal.subscriptionCliWarningAgy": "Этот провайдер использует официальный Antigravity CLI, в котором выполнен вход на хосте прокси ({cmd}). Оплата за использование списывается с этого аккаунта Google Antigravity. Google разрешает только интерактивное использование под управлением пользователя. OpenCodex отклоняет ходы субагентов, комбо и резервную маршрутизацию субагентов и определяет локальность по наблюдаемому соединению. Если незаявленный ретранслятор на loopback не передаёт заголовки переадресации, удалённый запрос может выглядеть локальным. Для публичного слушателя укажите обратный прокси в dashboardTrustedProxy или не перенаправляйте этот порт. API-ключ не требуется и не хранится. Для задач, выполняемых программно, или общего доступа добавьте {apiProvider}.", "modal.freeTierDefault": "API-ключ не нужен. Работает из коробки.", "modal.tab.accounts": "Аккаунты", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 5c5207b2f2c..11a09f24f0a 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -1863,7 +1863,7 @@ export const tr: Record = { "modal.invalidPreset": "Bu yerleşik sağlayıcı ayarı eksik.", "modal.freeTierTitle": "Ücretsiz katman", "modal.subscriptionCliTitle": "Abonelik CLI'si, API anahtarı değil", - "modal.subscriptionCliWarning": "Bu sağlayıcı API anahtarı kullanmaz. Bu makinede oturum açılmış resmi Claude Code CLI'sini ({cmd}) çalıştırır ve ücreti o Claude abonelik hesabına yansıtır. OpenCodex bunun için anahtar saklamaz ve buraya girilen bir anahtar asla kullanılmaz. API anahtarıyla faturalandırma için bunun yerine {apiProvider} ekleyin.", + "modal.subscriptionCliWarning": "Bu sağlayıcı API anahtarı kullanmaz. Bu makinede oturum açılmış resmi {cli} aracını ({cmd}) çalıştırır ve ücreti o {plan} abonelik hesabına yansıtır. OpenCodex bunun için anahtar saklamaz ve buraya girilen bir anahtar asla kullanılmaz. API anahtarıyla faturalandırma için bunun yerine {apiProvider} ekleyin.", "modal.subscriptionCliWarningAgy": "Bu sağlayıcı, proxy sunucusunda oturum açılmış resmi Antigravity CLI’yi ({cmd}) kullanır. Kullanım ücreti bu Google Antigravity hesabına yansıtılır. Google yalnızca kullanıcının yönlendirdiği etkileşimli kullanıma izin verir. OpenCodex alt ajan turlarını, kombinasyonları ve alt ajan yedek yönlendirmesini reddeder ve isteğin yerel olup olmadığını gözlemlediği bağlantıdan belirler. Tanımlanmamış bir loopback aktarıcısı, yönlendirme başlıklarını iletmezse uzak istekler yerel görünebilir. Genel dinleyici için ters proxy’yi dashboardTrustedProxy içinde tanımlayın veya bu bağlantı noktasını aktarmayın. API anahtarı gerekmez ve saklanmaz. Program aracılığıyla yürütülen işler veya paylaşımlı kullanım için {apiProvider} ekleyin.", "modal.freeTierDefault": "API anahtarı gerekmez. Doğrudan çalışır.", "modal.tab.accounts": "Hesaplar", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index fbaa64d77b0..d03d70f37ab 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -1849,7 +1849,7 @@ export const vi: Record = { "modal.invalidPreset": "Preset của provider tích hợp này bị thiếu. Hãy khởi động lại proxy và thử lại.", "modal.freeTierTitle": "Gói miễn phí", "modal.subscriptionCliTitle": "CLI theo gói đăng ký, không phải API key", - "modal.subscriptionCliWarning": "Nhà cung cấp này không dùng API key. Nó chạy Claude Code CLI chính thức đã đăng nhập trên máy này ({cmd}) và tính phí vào tài khoản gói đăng ký Claude đó. OpenCodex không lưu key nào cho nó, và key nhập ở đây sẽ không bao giờ được dùng. Để tính phí theo API key, hãy thêm {apiProvider} thay thế.", + "modal.subscriptionCliWarning": "Nhà cung cấp này không dùng API key. Nó chạy {cli} chính thức đã đăng nhập trên máy này ({cmd}) và tính phí vào tài khoản gói đăng ký {plan} đó. OpenCodex không lưu key nào cho nó, và key nhập ở đây sẽ không bao giờ được dùng. Để tính phí theo API key, hãy thêm {apiProvider} thay thế.", "modal.subscriptionCliWarningAgy": "Nhà cung cấp này dùng Antigravity CLI chính thức đã đăng nhập trên máy chủ proxy ({cmd}). Chi phí sử dụng được tính vào tài khoản Google Antigravity đó. Google chỉ cho phép sử dụng tương tác do người dùng trực tiếp điều khiển. OpenCodex từ chối lượt của tác tử con, combo và định tuyến dự phòng cho tác tử con, đồng thời xác định yêu cầu có phải cục bộ hay không dựa trên kết nối quan sát được. Một bộ chuyển tiếp qua loopback chưa được khai báo có thể khiến yêu cầu từ xa trông như yêu cầu cục bộ nếu không chuyển tiếp các tiêu đề chuyển tiếp. Với cổng lắng nghe công khai, hãy khai báo proxy ngược trong dashboardTrustedProxy hoặc không chuyển tiếp cổng này. Không cần và không lưu khóa API. Với các tác vụ được thực hiện bằng chương trình hoặc dùng chung, hãy thêm {apiProvider}.", "modal.freeTierDefault": "Không cần API key. Có thể sử dụng ngay.", "modal.tab.accounts": "Tài khoản", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 02cf8c4be4c..6132f762027 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -1539,7 +1539,7 @@ export const zhTW: Record = { "modal.invalidPreset": "此內建供應商預設不完整。請重新啟動代理後重試。", "modal.freeTierTitle": "免費層級", "modal.subscriptionCliTitle": "訂閱 CLI,而非 API 金鑰", - "modal.subscriptionCliWarning": "此供應商不使用 API 金鑰。它會呼叫本機已登入的官方 Claude Code CLI({cmd}),並向該 Claude 訂閱帳戶計費。OpenCodex 不會為其儲存任何金鑰,在此輸入的金鑰也永遠不會被使用。如需以 API 金鑰計費,請改為新增 {apiProvider}。", + "modal.subscriptionCliWarning": "此供應商不使用 API 金鑰。它會呼叫本機已登入的官方 {cli}({cmd}),並向該 {plan} 訂閱帳戶計費。OpenCodex 不會為其儲存任何金鑰,在此輸入的金鑰也永遠不會被使用。如需以 API 金鑰計費,請改為新增 {apiProvider}。", "modal.subscriptionCliWarningAgy": "此供應商使用已在代理伺服器主機上登入的官方 Antigravity CLI({cmd})。使用費用計入該 Google Antigravity 帳戶。Google 僅允許由使用者主導的互動式使用。OpenCodex 拒絕子代理回合、組合及子代理備援路由,並根據觀察到的連線判斷請求是否來自本機。若未宣告的回環中繼未傳送轉送標頭,遠端請求可能看起來像本機請求。對於公開監聽器,請在 dashboardTrustedProxy 中宣告反向代理,或避免轉送此連接埠。無須 API 金鑰,也不會儲存金鑰。如需以程式執行工作或供多人使用,請新增 {apiProvider}。", "modal.freeTierDefault": "無需 API 金鑰,開箱即用。", "modal.tab.accounts": "帳號", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index ae0f79fce9e..6f5f584a2e9 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -3064,7 +3064,7 @@ export const zh: Record = { "modal.invalidPreset": "此内置提供方预设不完整。请重启代理后重试。", "modal.freeTierTitle": "免费层级", "modal.subscriptionCliTitle": "订阅 CLI,而非 API 密钥", - "modal.subscriptionCliWarning": "此提供商不使用 API 密钥。它调用本机已登录的官方 Claude Code CLI({cmd}),并向该 Claude 订阅账户计费。OpenCodex 不为其存储任何密钥,在此输入的密钥也永远不会被使用。如需按 API 密钥计费,请改为添加 {apiProvider}。", + "modal.subscriptionCliWarning": "此提供商不使用 API 密钥。它调用本机已登录的官方 {cli}({cmd}),并向该 {plan} 订阅账户计费。OpenCodex 不为其存储任何密钥,在此输入的密钥也永远不会被使用。如需按 API 密钥计费,请改为添加 {apiProvider}。", "modal.subscriptionCliWarningAgy": "此提供商使用在代理主机上已登录的官方 Antigravity CLI({cmd})。使用费用计入对应的 Google Antigravity 账户。Google 仅允许由用户主导的交互式使用。OpenCodex 拒绝子代理轮次、组合和子代理回退路由,并根据观测到的连接判断请求是否来自本地。如果未声明的回环中继没有传递转发标头,远程请求可能看起来像本地请求。对于公开监听器,请在 dashboardTrustedProxy 中声明反向代理,或避免转发此端口。无需 API 密钥,也不会存储密钥。如需以编程方式执行任务或供多人使用,请添加 {apiProvider}。", "modal.freeTierDefault": "无需 API 密钥,开箱即用。", "modal.tab.accounts": "账户", diff --git a/gui/src/provider-workspace/subscription-cli.ts b/gui/src/provider-workspace/subscription-cli.ts index 90426d61572..47377979cb8 100644 --- a/gui/src/provider-workspace/subscription-cli.ts +++ b/gui/src/provider-workspace/subscription-cli.ts @@ -2,8 +2,7 @@ * provider-workspace/subscription-cli.ts * * A subscription CLI row drives a locally signed-in vendor CLI instead of calling an API with a - * key: the `claude-cli` adapter runs the official Claude Code CLI headlessly (`claude -p`), and - * the `agy-acp` adapter runs the official Antigravity CLI over ACP (`agy acp`). The CLI signs in + * key. The CLI signs in * and bills the user's subscription, and the proxy stores, reads and injects no key. The registry * marks the row `keyOptional` because no key is required, which is also the flag the dashboard * reads as "free" — so every surface that groups or labels by pricing asks this helper first. @@ -14,9 +13,12 @@ */ import type { TKey } from "../i18n/shared"; +type SubscriptionCliWarning = { key: TKey; cmd: string; apiProvider: string; vars?: { cli: string; plan: string } }; + /** Per adapter: the warning shown in place of a key field, its CLI command, and the key-billed preset to use instead. */ -const SUBSCRIPTION_CLI_WARNINGS: Readonly> = { - "claude-cli": { key: "modal.subscriptionCliWarning", cmd: "claude -p", apiProvider: "anthropic-apikey" }, +const SUBSCRIPTION_CLI_WARNINGS: Readonly> = { + "claude-cli": { key: "modal.subscriptionCliWarning", cmd: "claude -p", apiProvider: "anthropic-apikey", vars: { cli: "Claude Code CLI", plan: "Claude" } }, + "step-cli": { key: "modal.subscriptionCliWarning", cmd: "step --sdk-stdio", apiProvider: "stepfun", vars: { cli: "StepCode CLI", plan: "Step Plan" } }, "agy-acp": { key: "modal.subscriptionCliWarningAgy", cmd: "agy acp", apiProvider: "google" }, }; @@ -25,7 +27,7 @@ export function isSubscriptionCliProvider(provider: { adapter?: string | null }) } /** The add-provider warning for a subscription CLI row, or undefined for any other row. */ -export function subscriptionCliWarning(provider: { adapter?: string | null }): { key: TKey; cmd: string; apiProvider: string } | undefined { +export function subscriptionCliWarning(provider: { adapter?: string | null }): SubscriptionCliWarning | undefined { const adapter = (provider.adapter ?? "").trim(); return Object.hasOwn(SUBSCRIPTION_CLI_WARNINGS, adapter) ? SUBSCRIPTION_CLI_WARNINGS[adapter] : undefined; } diff --git a/gui/tests/add-provider-subscription-cli.test.tsx b/gui/tests/add-provider-subscription-cli.test.tsx index a3089c38993..29a9ce117cf 100644 --- a/gui/tests/add-provider-subscription-cli.test.tsx +++ b/gui/tests/add-provider-subscription-cli.test.tsx @@ -16,6 +16,7 @@ import { selectValue } from "./helpers/custom-select"; const PRESETS = [ { id: "claude-cli", label: "Claude Code CLI (subscription)", adapter: "claude-cli", baseUrl: "https://api.anthropic.com", auth: "key", keyOptional: true, defaultModel: "claude-sonnet-5", note: "Runs Claude subscription traffic through the official CLI." }, { id: "antigravity-acp", label: "Antigravity CLI (ACP, local)", adapter: "agy-acp", baseUrl: "https://antigravity.google/docs/cli/acp", auth: "key", keyOptional: true, defaultModel: "gemini-3.8-flash", note: "Drives the official Antigravity CLI." }, + { id: "step-cli", label: "StepCode CLI (subscription)", adapter: "step-cli", baseUrl: "https://api.stepfun.com/step_plan", auth: "key", keyOptional: true, defaultModel: "step-5-preview" }, { id: "keyless", label: "Keyless Free", adapter: "openai-chat", baseUrl: "https://api.example.com/v1", auth: "key", keyOptional: true }, { id: "google-vertex", label: "Google Vertex AI", adapter: "google", baseUrl: "https://aiplatform.googleapis.com", auth: "key", defaultModel: "gemini-3-pro" }, ]; @@ -111,6 +112,38 @@ test("claude-cli is listed under Paid, not Free", async () => { expect(rowsText()).not.toContain("Keyless Free"); }); +test("step-cli has a subscription badge under Paid and is absent from Free", async () => { + await mount("free"); + expect(rowsText()).not.toContain("StepCode CLI"); + + await mount("paid"); + const row = [...win.document.querySelectorAll(".provider-catalog-row-wrap > button")] + .find(el => el.textContent?.includes("StepCode CLI")); + expect(row?.textContent).toContain("Subscription CLI"); +}); + +test("StepCode setup names its own CLI and API-key alternative and saves without a key", async () => { + await mount("paid"); + const row = [...win.document.querySelectorAll(".provider-catalog-row-wrap > button")] + .find(el => el.textContent?.includes("StepCode CLI")); + expect(row).toBeDefined(); + await act(async () => { (row as unknown as HTMLButtonElement).click(); }); + expect(warning()?.textContent).toContain("StepCode"); + expect(warning()?.textContent).toContain("Step Plan"); + expect(warning()?.textContent).toContain("step --sdk-stdio"); + expect(warning()?.textContent).toContain("stepfun"); + expect(warning()?.textContent).not.toContain("anthropic-apikey"); + expect(win.document.querySelector('input[type="password"]')).toBeNull(); + + const addButton = [...win.document.querySelectorAll("button.btn-primary")] + .find(el => el.textContent === "Add provider") as unknown as HTMLButtonElement; + await act(async () => { addButton.click(); await new Promise(r => setTimeout(r, 20)); }); + expect(posted).toHaveLength(1); + expect(posted[0]).toMatchObject({ name: "step-cli", provider: { adapter: "step-cli" } }); + expect(posted[0]?.provider).not.toHaveProperty("apiKey"); + expect(added).toEqual(["step-cli"]); +}); + test("selecting claude-cli shows the subscription warning above Add, and Add still saves", async () => { await mount("paid"); expect(warning()).toBeNull(); @@ -122,7 +155,8 @@ test("selecting claude-cli shows the subscription warning above Add, and Add sti expect(note).not.toBeNull(); expect(note?.getAttribute("role")).toBe("note"); expect(note?.textContent).toContain("Subscription CLI, not an API key"); - expect(note?.textContent).toContain("claude -p"); + expect(note?.textContent).toContain("Claude Code CLI"); + expect(note?.querySelector("code.chip")?.textContent).toBe("claude -p"); expect(note?.textContent).toContain("anthropic-apikey"); // The green free-tier box and the key field are replaced, not shown beside the warning. expect(win.document.body.textContent).not.toContain("Free tier"); diff --git a/scripts/test-layout/layout-step-cli.json b/scripts/test-layout/layout-step-cli.json new file mode 100644 index 00000000000..77b7ca09be7 --- /dev/null +++ b/scripts/test-layout/layout-step-cli.json @@ -0,0 +1,13 @@ +{ + "step-cli-cleanup-ownership.test.ts": "adapters", + "step-cli-ownership.test.ts": "adapters", + "step-cli-process-lifecycle.test.ts": "adapters", + "step-cli-query-race.test.ts": "adapters", + "step-cli-frames.test.ts": "adapters", + "step-cli-conversation.test.ts": "adapters", + "step-cli-run-turn.test.ts": "adapters", + "step-cli-session.test.ts": "adapters", + "step-cli-tool-bridge.test.ts": "adapters", + "step-cli-tool-result.test.ts": "adapters", + "step-cli-provider.test.ts": "providers" +} diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 38be0f6b60a..06e8ccc676f 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1,7 +1,7 @@ { "version": 1, "root": "tests", - "explicitShards": ["layout-route-intent.json", "layout-release-signing.json", "layout-file-identity.json", "layout-clients.json", "layout-codex-collision.json", "layout-native-profiles.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json", "layout-config.json", "layout-kiro-usage.json", "layout-usage.json", "layout-docs-guides.json", "layout-docs.json", "layout-claude-keychain.json", "layout-test-hygiene.json", "layout-codex-journal.json", "layout-upload-reduction.json"], + "explicitShards": ["layout-route-intent.json", "layout-release-signing.json", "layout-file-identity.json", "layout-clients.json", "layout-codex-collision.json", "layout-native-profiles.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json", "layout-config.json", "layout-kiro-usage.json", "layout-usage.json", "layout-docs-guides.json", "layout-docs.json", "layout-claude-keychain.json", "layout-test-hygiene.json", "layout-codex-journal.json", "layout-upload-reduction.json", "layout-step-cli.json"], "explicit": { "gui-account-quota-table.test.ts": "gui", "account-probe-routes.test.ts": "server", "web-search-local-deadline-provenance.test.ts": "web-search", "kimi-monthly-quota.test.ts": "providers", "vertex-adc-verified.test.ts": "adapters/google", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "pr-gates-workflow.test.ts": "ci-workflows", "stop-restore-history-ownership.test.ts": "service", "cli-stop-refusal-transport.test.ts": "cli", diff --git a/src/adapters/coding-agent/process-tree.ts b/src/adapters/coding-agent/process-tree.ts new file mode 100644 index 00000000000..0d456435b13 --- /dev/null +++ b/src/adapters/coding-agent/process-tree.ts @@ -0,0 +1,30 @@ +import { execFile, execFileSync } from "node:child_process"; + +const TASKKILL_TIMEOUT_MS = 5_000; + +function taskkillPath(): string { + return `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`; +} + +/** Terminate the owned CLI and its descendants; never resolve on an unconfirmed tree kill. */ +export function killWindowsProcessTree(pid: number): void { + execFileSync(taskkillPath(), ["/PID", String(pid), "/T", "/F"], { + stdio: "pipe", + windowsHide: true, + timeout: TASKKILL_TIMEOUT_MS, + }); +} + +/** StepCode needs a tree-kill receipt without blocking the shutdown clock. */ +export function killWindowsProcessTreeAsync(pid: number): Promise { + return new Promise((resolve, reject) => { + execFile(taskkillPath(), ["/PID", String(pid), "/T", "/F"], { + windowsHide: true, + timeout: TASKKILL_TIMEOUT_MS, + killSignal: "SIGKILL", + }, error => { + if (error) reject(error); + else resolve(); + }); + }); +} diff --git a/src/adapters/coding-agent/profile.ts b/src/adapters/coding-agent/profile.ts index c799ceada3e..529e5ef6988 100644 --- a/src/adapters/coding-agent/profile.ts +++ b/src/adapters/coding-agent/profile.ts @@ -13,7 +13,7 @@ export interface CodingAgentProviderProfile { /** Canonical OpenCodex provider id this profile serves. */ providerId: string; /** Vendor family; selects the arg/env builder in the family adapter. */ - family: "claude" | "codebuddy" | "qoder"; + family: "claude" | "codebuddy" | "qoder" | "step"; /** * Region; drives the vendor's own region switch and keeps credentials deterministic. * A family with a single destination carries `global`. diff --git a/src/adapters/coding-agent/turn.ts b/src/adapters/coding-agent/turn.ts index 061a748cdd2..126258f02a3 100644 --- a/src/adapters/coding-agent/turn.ts +++ b/src/adapters/coding-agent/turn.ts @@ -1,4 +1,4 @@ -import { execFileSync, spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from "node:child_process"; +import { spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from "node:child_process"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, win32 } from "node:path"; @@ -23,6 +23,7 @@ import { } from "./protocol"; import { isBatchDispatcher, resolveCodingAgentBinary, resolveProfileByBaseUrl, type CodingAgentProviderProfile, type WhichFn } from "./profile"; import { inspectBatchDispatcher, type ReadDispatcherFn } from "./batch-dispatcher"; +import { killWindowsProcessTree } from "./process-tree"; /** Injectable spawn for tests; production uses node:child_process. */ export type SpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess; @@ -58,14 +59,6 @@ const DEFAULT_KILL_GRACE_MS = 2_000; /** Bound captured stderr so an error message can never carry an unbounded (or secret) payload. */ const MAX_STDERR_BYTES = 8 * 1024; -function killWindowsProcessTree(pid: number): void { - const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`; - execFileSync(taskkill, ["/PID", String(pid), "/T", "/F"], { - stdio: "pipe", - windowsHide: true, - }); -} - /** Env keys a CLI needs to run; everything else is dropped so the child env is scoped and deterministic. */ const INHERITED_ENV_KEYS = [ "PATH", "HOME", "USERPROFILE", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TEMP", "TMP", diff --git a/src/adapters/registry.ts b/src/adapters/registry.ts index 6436c355144..071182ff6d7 100644 --- a/src/adapters/registry.ts +++ b/src/adapters/registry.ts @@ -9,6 +9,7 @@ import { withClinePassDeepSeekV4ToolReplayCompatibility } from "./cline-pass-dee import { withUniqueToolCallIds } from "./unique-tool-call-ids"; import { createCodeBuddyAdapter } from "./codebuddy/adapter"; import { createQoderAdapter } from "./qoder/adapter"; +import { createStepCliAdapter } from "./step-cli/adapter"; import { createCommandCodeAdapter } from "./command-code"; import { createCursorAdapter } from "./cursor"; import { createDevinAdapter } from "./devin"; @@ -42,6 +43,7 @@ export interface AdapterFactoryContext { export type AdapterWire = | "codebuddy" + | "step-cli" | "command-code" | "openai-chat" | "ollama-native" @@ -174,6 +176,15 @@ export const ADAPTER_REGISTRY = { contractParent: "codebuddy", create: (provider: OcxProviderConfig, _context: AdapterFactoryContext) => createClaudeCliAdapter(provider), }, + "step-cli": { + // StepCode's SDK stdio host speaks its own length-prefixed envelope rather than the Anthropic + // stream-json this repo parses for CodeBuddy, Qoder and Claude Code, so it states its own wire + // contract. The family owns its args, env and framing, and the CLI owns the credential: the + // adapter stores and injects none. + wire: "step-cli", + mutation: "codex-owned", + create: (provider: OcxProviderConfig, _context: AdapterFactoryContext) => createStepCliAdapter(provider), + }, "dsh-account": { contractParent: "anthropic", create: (provider: OcxProviderConfig, context: AdapterFactoryContext) => createDshAccountAdapter(provider, context), diff --git a/src/adapters/step-cli/adapter.ts b/src/adapters/step-cli/adapter.ts new file mode 100644 index 00000000000..11bfd85def7 --- /dev/null +++ b/src/adapters/step-cli/adapter.ts @@ -0,0 +1,401 @@ +import type { AdapterEvent, OcxParsedRequest, OcxProviderConfig } from "../../types"; +import type { AdapterRequest, IncomingMeta, ProviderAdapter } from "../base"; +import { getConfigDir } from "../../config/paths"; +import { CODING_AGENT_TOOL_LIMITS } from "../coding-agent/tool-catalog"; +import { ConversationQueueFullError, ownedConversationHandle, withConversationLock } from "./conversation"; +import { STEP_CLI_HOST, STEP_CLI_TOOL_SERVER } from "./constants"; +import { sessionHandlers } from "./events"; +import { mapSessionFailure, refusal } from "./errors"; +import { + abortSignal, + composePrompt, + hasImageInput, + latestToolResult, + pendingUserText, + stepModelId, + stepThinkingTokens, + type StepProviderState, +} from "./projection"; +import { resolveStepCliProfile, STEP_CLI_PROFILE, type StepCliProfile } from "./profiles"; +import { + beginTurn, + clearStepCliSessions, + currentQuery, + currentTurn, + endTurn, + forgetQuery, + poolFor, + rememberQuery, +} from "./registry"; +import { StepSessionError, type StepSessionDeps } from "./session"; +import type { StepConversationHost, StepConversationRef, StepConversationSession } from "./session-pool"; +import { buildStepSdkTools, StepToolCatalogError } from "./tool-bridge"; +import type { StepFrame } from "./stdio-frames"; + +/** + * Codex turns against a Step Plan subscription. + * + * This module is the ORCHESTRATION layer and nothing else: it decides what one turn is, in what order + * it runs, and when it has produced a terminal event. Converting between the client's request shape + * and the CLI's is `projection`, mapping the CLI's frames back is `events`, conversation identity and + * turn ordering are `conversation`, and everything that must outlive a request is `registry`. + */ +export interface StepCliAdapterDeps extends StepSessionDeps { + /** Injection seam so tests drive the real `runTurn` path without a CLI. */ + openSession?: StepConversationHost; +} + +/** + * Per-request turn state, keyed by the process that owns it. + * + * `createStepCliAdapter` runs once per request, so nothing that has to survive a request boundary can + * live in its closure: a reverse request arriving during request N+1 would be routed to an instance + * that no longer exists, and the conversation would silently restart. `devin/trajectory.ts` keeps its + * conversation map at module scope for the same reason. + */ + +/** + * Hard ceiling on waiting for a terminal event from the CLI. + * + * The turn would otherwise wait for the client's abort, and a client that never aborts (or a CLI that + * went quiet) would hold the conversation lock for the life of the process. Set well above + * StepCode's own 120s tool window so a legitimate slow tool is never cut short. + */ +const STEP_CLI_TERMINAL_DEADLINE_MS = 10 * 60_000; + +/** + * Backoff for re-opening a query the runtime still considers busy. + * + * A turn settles when the CLI reports `turn_complete`, which can be a moment before the runtime frees + * its single query slot. Measured on the real CLI: the very next request on the same conversation then + * failed with `SESSION_BUSY`. The conversation lock means no other turn of ours is in flight while this + * runs, so retrying here cannot collide with our own work — it is only bridging the runtime's own + * handover delay. + */ +const STEP_CLI_QUERY_RETRY_DELAYS_MS = [200, 600, 1500] as const; + +/** + * Run Codex turns against a StepCode subscription. + * + * One StepCode process serves one conversation, and this adapter never executes a tool itself: it + * declares the client's catalog as StepCode SDK tools, allows the permission check the client's own + * request already implies, and holds the tool call open so the result the client computes on its next + * request is delivered back into the query the model is running. + */ +export function createStepCliAdapter( + provider: OcxProviderConfig, + deps: StepCliAdapterDeps = {}, +): ProviderAdapter { + const profile: StepCliProfile | undefined = resolveStepCliProfile(provider.baseUrl); + + return { + name: STEP_CLI_HOST, + + buildRequest(): AdapterRequest { + return { url: provider.baseUrl, method: "POST", headers: {}, body: "" }; + }, + async *parseStream(): AsyncGenerator { + yield { + type: "error", + message: "StepCode CLI adapter uses runTurn; the fetch/parseStream path is disabled.", + }; + }, + + async runTurn(parsed, incoming, emit): Promise { + if (!profile) { + emit( + refusal( + "This provider row is not pointed at StepCode's canonical destination, so the CLI's own account is never reached.", + 400, + "step_cli_profile_mismatch", + ), + ); + return; + } + if (incoming.abortSignal?.aborted) return emitPreDispatchAbort(emit); + if (hasImageInput(parsed)) { + emit( + refusal( + "StepCode image input is not enabled because this CLI route has no verified multimodal contract.", + 400, + "unsupported_input_modality", + ), + ); + return; + } + + let tools: ReturnType; + try { + tools = buildStepSdkTools(parsed, STEP_CLI_TOOL_SERVER); + } catch (error) { + if (!(error instanceof StepToolCatalogError)) throw error; + // Name the numbers. Codex with many MCP servers flattens every remote tool into the function + // catalog (measured on a real Codex 0.162.0 client: 1749 tools, 2.5 MB), and the shared + // CLI-family ceiling is 128 tools / 2 MiB — the same bound `qoder`, `codebuddy` and + // `claude-cli` enforce. An operator seeing only "exceeds tool count limit" cannot tell a + // malformed catalog from an oversized one. + const declared = parsed.context.tools?.length ?? 0; + emit( + refusal( + `This request declares ${declared} tools, over the ${CODING_AGENT_TOOL_LIMITS.maxTools}-tool ceiling ` + + `every CLI-backed provider shares. Codex flattens each MCP server's tools into this catalog, so an ` + + `MCP-heavy setup reaches the ceiling; drop or disable MCP servers for this provider, or narrow the ` + + `tool set in the request. Detail: ${error.message}`, + 400, + "tool_catalog_invalid", + ), + ); + return; + } + + let sessions: StepConversationHost; + try { sessions = deps.openSession ?? poolFor(getConfigDir(), deps, sessionHandlers); } + catch (error) { emit(mapSessionFailure(error)); return; } + // Admission owns the namespace; thread headers only select a conversation within it. + // Requests without caller ownership receive a private process. + const identified = ownedConversationHandle(parsed, incoming, provider); + const ref: StepConversationRef = identified + ? { handle: identified, sessionId: "" } + : sessions.nextRef(); + + let session!: StepConversationSession; + try { + session = await sessions.open(ref); + await session.handshake(); + } catch (error) { + await session?.close(); + emit(mapSessionFailure(error)); + return; + } + + // From here on this turn owns the conversation's process and its turn state, so anything else + // arriving for the same conversation waits rather than corrupting it. + try { + await withConversationLock(ref.handle, () => + driveTurn(parsed, incoming, emit, { + sessions, + session, + ref, + tools, + setTimer: deps.setTimeout ?? setTimeout, + clearTimer: deps.clearTimeout ?? clearTimeout, + }), + ); + } catch (error) { + if (error instanceof ConversationQueueFullError) { + // The queue cap is a refusal, not a crash, and this caller never owned the conversation: the + // session it was handed is the one serving the accepted turn and its queue. Closing it here + // would disconnect every one of them to turn away a single extra request. + emit( + refusal(error.message, 409, "step_cli_conversation_busy", "rate_limit_error", true), + ); + return; + } + // Anything else was raised by this turn after it owned the conversation, so the session state + // is no longer trustworthy and is closed. + emit(mapSessionFailure(error)); + await session.close(); + } finally { + // Keyless callers have no cross-request ownership proof. Their process is request-local. + if (!identified) await session.close(); + } + }, + }; +} + +/** + * Open a query, retrying only while the runtime reports its single slot is still busy. + * + * Every other failure propagates immediately: a capability or transport problem must not be turned + * into three silent attempts. + */ +async function startQueryWithBusyRetry( + session: StepConversationSession, + options: { model: string | undefined; maxThinkingTokens: number | undefined; sdkTools: readonly unknown[]; streamingInput: boolean }, + signal: AbortSignal | undefined, + delay: (ms: number) => Promise = ms => new Promise(resolve => setTimeout(resolve, ms)), +): Promise<{ queryId: string; sessionId: string } | undefined> { + let attempt = 0; + while (!signal?.aborted) { + try { + return await session.startQuery(options); + } catch (error) { + const busy = error instanceof StepSessionError && error.code === "step_cli_session_busy"; + if (!busy || attempt >= STEP_CLI_QUERY_RETRY_DELAYS_MS.length) throw error; + if (signal?.aborted) return; + await delay(STEP_CLI_QUERY_RETRY_DELAYS_MS[attempt]!); + attempt += 1; + } + } +} + +function emitPreDispatchAbort(emit: (event: AdapterEvent) => void): void { + emit({ type: "error", message: "StepCode turn was aborted before start.", retryable: false }); +} + +async function driveTurn( + parsed: OcxParsedRequest, + incoming: IncomingMeta, + emit: (event: AdapterEvent) => void, + context: { + sessions: StepConversationHost; + session: StepConversationSession; + ref: StepConversationRef; + tools: ReturnType; + setTimer: typeof setTimeout; + clearTimer: typeof clearTimeout; + }, +): Promise { + if (incoming.abortSignal?.aborted) return emitPreDispatchAbort(emit); + const { sessions, session, ref, tools, setTimer, clearTimer } = context; + // A matching held result resumes its original query. An abandoned call must finish + // unwinding without a turn before the replacement is registered. + const held = sessions.takeHeldTool(ref); + const heldResult = held ? latestToolResult(parsed) : undefined; + // Matched by CALL ID, never by position: a client may follow a tool call with a new user + // message instead of a result, in which case the newest result in the transcript belongs to an + // earlier call and delivering it would answer the wrong question. + // A client that cancels the call and sends only new user text has no tool result in its + // transcript at all, so `heldResult` can be undefined while `held` exists. + const heldMatches = held !== undefined && heldResult !== undefined && heldResult.toolCallId === held.callId; + // This turn IS the answer to a captured call: the model already has the instruction and is + // mid-query, so nothing is prompted again. + const continuedQuery = Boolean(held) && heldMatches; + // The client sent something other than the held call's result — typically a new user message. + // The query that owned the call is unwinding; leaving it running would make this request's own + // text unstartable, and swallowing that text would lose the user's turn entirely. + const abandonedQueryId = Boolean(held) && !heldMatches; + + const catalogKey = JSON.stringify(tools.sdkTools); + if (held && (held.queryId !== currentQuery(session) || held.catalogKey !== catalogKey)) { + emit(refusal("The held StepCode call belongs to a different query or tool catalog.", 409, "step_cli_tool_owner_mismatch")); + await session.close(); + return; + } + + // Text is suppressed ONLY when this turn really is the answer to the held call; a turn that + // abandoned the call still carries the user's message and must keep it. + const userText = continuedQuery ? undefined : pendingUserText(parsed); + if (!continuedQuery && !userText) { + emit( + refusal( + "StepCode carries conversation history inside its own process, so a turn must end with either user text or a tool result.", + 400, + "step_cli_no_user_text", + ), + ); + return; + } + + if (abandonedQueryId && held) { + // Detach the old owner before releasing its hold: completion can arrive synchronously. + endTurn(session); + forgetQuery(session); + session.resolveHeldToolResult( + { id: held.frameId, method: "sdk_tool.invoke" } as StepFrame, + { content: [{ type: "text", text: "" }], isError: true }, + ); + await session.interrupt(held.queryId); + await session.endInput(held.queryId); + } + + let settle!: () => void; + const done = new Promise(resolve => { + settle = resolve; + }); + beginTurn(session, { + ref, + pool: sessions, + emit, + settle, + emittedNames: tools.emittedNameMap, + catalogKey, + ...(continuedQuery && held ? { queryId: held.queryId } : {}), + }); + + // Registered FIRST, delivered second. See the comment above: the CLI can answer the moment it + // receives the result. + if (held && continuedQuery) { + const delivered = session.resolveHeldToolResult( + { id: held.frameId, method: "sdk_tool.invoke" } as StepFrame, + heldResult!, + ); + if (!delivered) { + endTurn(session); + emit( + refusal( + "The held StepCode tool call expired before the tool result arrived; StepCode only waits two minutes for one.", + 504, + "step_cli_tool_result_too_late", + "upstream_error", + ), + ); + await session.close(); + return; + } + } + + let queryId: string | undefined; + let deadlineTimer: unknown; + try { + if (!continuedQuery) { + const started = await startQueryWithBusyRetry(session, { + model: stepModelId(parsed.modelId), + maxThinkingTokens: stepThinkingTokens(parsed), + sdkTools: tools.sdkTools, + streamingInput: true, + }, incoming.abortSignal); + if (!started) { + endTurn(session); + settle(); + return emitPreDispatchAbort(emit); + } + queryId = started.queryId; + rememberQuery(session, queryId); + if (!incoming.abortSignal?.aborted) { + await session.sendInput(queryId, composePrompt(parsed, userText ?? "")); + } + } + } catch (error) { + endTurn(session); + settle(); + emit(mapSessionFailure(error)); + await session.close(); + return; + } + + // The turn owns the response until it settles: text, a captured tool call, a completion, the + // client's abort, or the hard deadline. Returning before that leaves the stream without a + // terminal event; never returning would hold the conversation lock forever. + await Promise.race([ + done, + abortSignal(incoming), + new Promise(resolve => { + deadlineTimer = setTimer(resolve, STEP_CLI_TERMINAL_DEADLINE_MS); + }), + ]); + clearTimer(deadlineTimer as never); + if (currentTurn(session) === undefined) return; + + // The turn is still registered, so nothing terminated it: either the client aborted, or the CLI + // went quiet. Either way the query is still running inside StepCode, and since it serves one + // query at a time the NEXT request for this conversation would be rejected or blocked by it. + // Interrupt it, and close the session when the interrupt cannot be confirmed. + endTurn(session); + emit({ + type: "error", + message: "The StepCode turn ended without a terminal event.", + status: 502, + errorType: "upstream_error", + code: "step_cli_turn_abandoned", + retryable: true, + }); + settle(); + if (queryId) { + await session.interrupt(queryId); + if (session.closed) return; + } + await session.close(); +} + +export { STEP_CLI_PROFILE, clearStepCliSessions }; diff --git a/src/adapters/step-cli/constants.ts b/src/adapters/step-cli/constants.ts new file mode 100644 index 00000000000..3a58e7e9dfc --- /dev/null +++ b/src/adapters/step-cli/constants.ts @@ -0,0 +1,11 @@ +/** Adapter identity used in telemetry and in `providerConfig.adapter`. */ +export const STEP_CLI_HOST = "step-cli"; + +/** Registry provider id. Kept separate from the adapter name so a future second adapter can coexist. */ +export const STEP_CLI_PROVIDER_ID = "step-cli"; + +/** Namespace StepCode registers this proxy's declared tools under. */ +export const STEP_CLI_TOOL_SERVER = "ocx"; + +/** `providerState` slot carrying the conversation handle between requests. */ +export const STEP_CLI_CONTINUATION_KEY = "step"; diff --git a/src/adapters/step-cli/conversation.ts b/src/adapters/step-cli/conversation.ts new file mode 100644 index 00000000000..443a00762ed --- /dev/null +++ b/src/adapters/step-cli/conversation.ts @@ -0,0 +1,159 @@ +import { createHash } from "node:crypto"; +import type { OcxParsedRequest, OcxProviderConfig } from "../../types"; +import type { IncomingMeta } from "../base"; + +/** + * Conversation identity and turn ordering. + * + * Both live together because they answer one question: which turn may run, and on whose state. A + * conversation is neither a model id nor a request — it is the thing that owns a StepCode process. + */ + +/** + * Identify the conversation this request belongs to. + * + * StepCode keeps a conversation only inside one process, so every request of a Codex thread has to + * land on the same session. The thread identity is what Codex already sends on EVERY request — + * `thread-id`, then the session-affinity headers — which is the resolution `devin`, `zed`, `cursor` + * and `google` use, and it works on the first request of a conversation. `previous_response_id` and + * the proxy's continuation store are only fallbacks: depending on persisted provider state would mean + * a conversation silently restarting whenever that store misses an entry. + */ +export function conversationHandle(parsed: OcxParsedRequest, incoming: IncomingMeta): string | undefined { + const own = incoming.headers.get("thread-id")?.trim() || parsed._codexOwnThreadId?.trim(); + if (own) return `own:${own}`; + const affinity = + incoming.headers.get("session_id")?.trim() || + incoming.headers.get("session-id")?.trim() || + incoming.headers.get("x-session-affinity")?.trim(); + if (affinity) return `session:${affinity}`; + // A parent thread id belongs to the SUB-agent it spawned, so it must not be read as this turn's own + // conversation; it is only consulted when no parent is present. + if (!incoming.headers.has("x-codex-parent-thread-id")) { + const client = parsed._clientThreadId?.trim(); + if (client) return `client:${client}`; + } + if (parsed.previousResponseId) return `response:${parsed.previousResponseId}`; + // Deliberately undefined rather than a shared "default": Claude Code, Grok Build and generic Chat + // clients all send requests with no identity, and collapsing them onto one handle would let one + // client read another's context and deliver its tool result into another's query. The caller mints + // a private ref instead, so an identity-less request gets its own process and forgets it. + return undefined; +} + +/** Headers select a conversation only inside the admission principal's provider namespace. */ +export function ownedConversationHandle( + parsed: OcxParsedRequest, + incoming: IncomingMeta, + provider: OcxProviderConfig, +): string | undefined { + const principal = parsed._reasoningReplayScope?.clientPrincipalId; + const conversation = conversationHandle(parsed, incoming); + if (!principal || !conversation) return undefined; + const identity = parsed._reasoningReplayScope?.current; + // Reuse the server-owned replay principal and physical provider identity. Never accept a + // principal, provider name or continuation handle from request headers/providerState. + return createHash("sha256").update(JSON.stringify([ + "step-cli", principal, incoming.providerName ?? identity?.providerName ?? "", + provider.adapter, provider.baseUrl, identity?.providerDestinationIdentity ?? "", + identity?.credentialIdentity ?? "", conversation, + ])).digest("hex"); +} + +/** How many turns may queue behind one conversation before a caller is told to retry. */ +export const MAX_QUEUED_TURNS = 2; + +/** + * Hard ceiling on waiting for a terminal event from the CLI. + * + * The turn would otherwise wait for the client's abort, and a client that never aborts (or a CLI that + * went quiet) would hold the conversation lock for the life of the process. Set well above + * StepCode's own 120s tool window so a legitimate slow tool is never cut short. + */ + +interface ConversationLock { + /** Settles when every queued turn ahead of this one has finished. */ + readonly chain: Promise; + /** Turns waiting or running; used to refuse an unbounded pile-up. */ + waiters: number; +} + +/** + * Per-conversation serialisation. + * + * StepCode serves ONE query per process, and this proxy's turn state is keyed by that process, so two + * overlapping turns on one conversation overwrite each other's runtime, interrupt each other's query + * and close each other's session — which is exactly what two clients sharing a `thread-id` produce, + * and it was measured as both requests failing with `SESSION_NOT_FOUND` and `step_cli_session_closed`. + * Turns are therefore queued in arrival order. + * + * Sequential traffic is unaffected: a turn that finishes before the next arrives takes an empty chain + * and completes without yielding. + */ + +/** + * Per-conversation serialisation. + * + * StepCode serves ONE query per process, and this proxy's turn state is keyed by that process, so two + * overlapping turns on one conversation overwrite each other's runtime, interrupt each other's query + * and close each other's session — which is exactly what two clients sharing a `thread-id` produce, + * and it was measured as both requests failing with `SESSION_NOT_FOUND` and `step_cli_session_closed`. + * Turns are therefore queued in arrival order. + * + * Sequential traffic is unaffected: a turn that finishes before the next arrives takes an empty chain + * and completes without yielding. + */ +const conversationLocks = new Map(); + +/** + * The caller was turned away at the queue cap and never owned the conversation. + * + * A distinct class so the adapter can tell an admission refusal (the current owner and its queue are + * untouched and must stay that way) from a failure raised by a turn that did own the conversation. + */ +export class ConversationQueueFullError extends Error { + override readonly name = "ConversationQueueFullError"; +} + +/** + * Exported for its regression test: the queue cap is the only path in this adapter that refuses + * rather than degrades, and it has to be observable to be trusted. + */ + +/** + * Exported for its regression test: the queue cap is the only path in this adapter that refuses + * rather than degrades, and it has to be observable to be trusted. + */ +export async function withConversationLock(handle: string, task: () => Promise): Promise { + const existing = conversationLocks.get(handle); + if (existing && existing.waiters >= MAX_QUEUED_TURNS + 1) { + throw new ConversationQueueFullError( + `StepCode serves one turn per conversation at a time and ${existing.waiters} are already queued for this one.`, + ); + } + const previous = existing?.chain ?? Promise.resolve(); + let release!: () => void; + const gate = new Promise(resolve => { + release = resolve; + }); + const chain = previous.then( + () => gate, + () => gate, + ); + const entry: ConversationLock = { chain, waiters: (existing?.waiters ?? 0) + 1 }; + conversationLocks.set(handle, entry); + void chain.finally(() => { + // Drop the entry once this turn's chain drains, unless a later turn already replaced it — otherwise + // the map would retain one settled promise per conversation handle for the life of the process. + if (conversationLocks.get(handle) === entry) conversationLocks.delete(handle); + }); + await previous.catch(() => undefined); + try { + return await task(); + } finally { + entry.waiters -= 1; + release(); + } +} + +/** One pool per OpenCodex home, so two homes in one process never share a StepCode session. */ diff --git a/src/adapters/step-cli/env.ts b/src/adapters/step-cli/env.ts new file mode 100644 index 00000000000..932f3360527 --- /dev/null +++ b/src/adapters/step-cli/env.ts @@ -0,0 +1,49 @@ +import { baseScopedEnv } from "../coding-agent/turn"; +import { stepCliSessionDir } from "./profiles"; + +/** + * Scoped child-process environment for one StepCode session (§六/§十四). + * + * `baseScopedEnv` already drops every inherited variable outside a short key allowlist, so the CLI + * cannot be steered by a stray `STEP_*` value in the operator's shell. Two StepCode-specific rules + * are layered on top: + * + * 1. `USER` is restored because StepCode resolves its own sign-in by account name. Measured with + * `env -i`: `USER` alone reports a signed-in machine, `LOGNAME` alone or neither does not. Without + * it a signed-in host answers "not logged in" and this provider has no account to spend. + * 2. The session directory is redirected into state this proxy owns, so a proxied conversation never + * lands in the operator's `~/.stepcode/agent/sessions` tree. + * + * No credential is layered here on purpose. StepCode reads its own `auth.json`, which is the + * property this provider exists for: the token never enters OpenCodex's config, key store, or any + * child environment. There is deliberately no `STEPCODE_AUTH_PATH` here for the same reason — an + * explicit auth path would be a second credential reference for this adapter to keep correct. + */ +export function buildStepCliEnv( + openCodexHome: string, + hostEnv: NodeJS.ProcessEnv = process.env, +): Record { + const env: Record = { ...baseScopedEnv() }; + const user = hostEnv.USER; + if (user) env.USER = user; + env.STEP_CODING_AGENT_SESSION_DIR = stepCliSessionDir(openCodexHome); + return env; +} + +/** + * Keep the operator's StepCode profile (`step_plan`, `step_plan_oversea`, …) intact. + * + * The profile lives in `auth.json` beside the credential and decides both the model endpoint and the + * region. It is never overridden here: a preset that picked a region for this adapter would be a + * second source of truth for exactly the thing the CLI already owns. + */ +export const STEP_CLI_FORBIDDEN_ENV_PREFIXES: readonly string[] = Object.freeze([ + "STEP_", + "STEPCODE_", + "OPENCODEX_", +]); + +/** Report any env key a caller is about to pass that the scoped builder must never forward. */ +export function forbiddenStepCliEnvKeys(keys: readonly string[]): string[] { + return keys.filter(key => STEP_CLI_FORBIDDEN_ENV_PREFIXES.some(prefix => key.startsWith(prefix))); +} diff --git a/src/adapters/step-cli/errors.ts b/src/adapters/step-cli/errors.ts new file mode 100644 index 00000000000..d9909e21a37 --- /dev/null +++ b/src/adapters/step-cli/errors.ts @@ -0,0 +1,76 @@ +import type { AdapterEvent } from "../../types"; +import type { StepProtocolErrorPayload } from "./stdio-frames"; + +type StepSessionErrorCode = + | "step_cli_session_failed" + | "step_cli_session_busy" + | "step_cli_binary_missing" + | "step_cli_capability_missing" + | "step_cli_protocol_violation" + | "step_cli_cleanup_failed" + | "step_cli_workspace_unavailable" + | "step_cli_not_logged_in" + | "step_cli_subscription_cooldown" + | "timeout"; + +export class StepSessionError extends Error { + constructor(message: string, readonly code: StepSessionErrorCode = "step_cli_session_failed") { + super(message); + this.name = "StepSessionError"; + } +} + +const SESSION_FAILURE = "StepCode could not complete the request."; + +/** Child diagnostics are classifier input only. The resulting error is safe to publish. */ +export function classifyStepChildError({ code, message }: StepProtocolErrorPayload): StepSessionError { + if (code === "SESSION_BUSY") { + return new StepSessionError("StepCode is still finishing its previous query.", "step_cli_session_busy"); + } + if (/not signed in|please run \/login|未登录/i.test(message)) { + return new StepSessionError("StepCode is not signed in. Run `step login` once and retry.", "step_cli_not_logged_in"); + } + if (/quota|credit|429|rate limit/i.test(message)) { + return new StepSessionError("StepCode subscription temporarily rate limited or out of quota.", "step_cli_subscription_cooldown"); + } + if (/did not answer .* in time|timed out/i.test(message)) { + return new StepSessionError("StepCode timed out while processing the request.", "timeout"); + } + return new StepSessionError(SESSION_FAILURE); +} + +/** + * Failure text for this route. + * + * Every other failure on a CLI-backed provider becomes an event on the client stream rather than a + * thrown error, so a refusal is what the operator actually reads. Keeping the mapping in one module + * means the wording and the status a client can retry on are decided in one place. + */ + +export function refusal( + message: string, + status: number, + code: string, + errorType = "invalid_request_error", + retryable = false, +): AdapterEvent { + return { type: "error", message, status, errorType, code, retryable }; +} + +/** Translate a transport failure into the actionable error an operator can act on. */ +export function mapSessionFailure(error: unknown): AdapterEvent { + const failure = error instanceof StepSessionError ? error : new StepSessionError(SESSION_FAILURE); + switch (failure.code) { + case "step_cli_binary_missing": + case "step_cli_capability_missing": + return refusal(failure.message, 400, failure.code); + case "step_cli_not_logged_in": + return refusal(failure.message, 401, failure.code, "authentication_error"); + case "step_cli_subscription_cooldown": + return refusal(failure.message, 429, failure.code, "rate_limit_error"); + case "timeout": + return refusal(failure.message, 504, failure.code, "upstream_error", true); + default: + return refusal(failure.message, 502, failure.code, "upstream_error", true); + } +} diff --git a/src/adapters/step-cli/events.ts b/src/adapters/step-cli/events.ts new file mode 100644 index 00000000000..cd3e57a68d2 --- /dev/null +++ b/src/adapters/step-cli/events.ts @@ -0,0 +1,227 @@ +import type { AdapterEvent } from "../../types"; +import type { StepSessionEvent } from "./session"; +import type { StepConversationSession } from "./session-pool"; +import { asRecord, continuationFor, toUsage } from "./projection"; +import { + assistantUsage, + currentQuery, + currentTurn, + endTurn, + forgetQuery, + recordAssistantUsage, +} from "./registry"; +import { resolveStepToolName } from "./tool-bridge"; +import type { StepFrame } from "./stdio-frames"; + +/** + * What the CLI says, and what this peer owes it in return. + * + * Every reverse request is ANSWERED, including when no turn is registered or the hold already + * expired: a dropped reverse request leaves the runtime waiting out its own 60s/120s window with no + * diagnostic and nothing for the client to act on. + */ + +/** + * A reverse request the CLI is waiting on this peer to answer. + * + * `permission.request` is allowed only for the owning query's declared catalog. A + * `sdk_tool.invoke` is deliberately NOT answered here: its result only exists once the + * client has executed the tool and sent its next request, and answering it is how that result reaches + * the model inside the query the model is already running. + */ +/** + * Exported for its regression tests: every reverse request must be ANSWERED, and the tests drive this + * exact function rather than a mirror of it. + */ +export function handleReverseRequest(session: StepConversationSession, frame: StepFrame): void { + const payload = asRecord(frame.payload); + const expired = payload.__expired === true; + const turn = currentTurn(session); + const queryId = turn?.queryId; + // The SDK host sends a sessionId and allocates req_ and q_ from the same counter. + // A callback from before this query cannot acquire it, even though SDK callbacks omit queryId. + const requestSerial = /^req_(\d+)$/.exec(frame.id)?.[1]; + const querySerial = queryId && /^q_(\d+)$/.exec(queryId)?.[1]; + const ownsQuery = queryId !== undefined && currentQuery(session) === queryId + && session.sessionId !== undefined && frame.sessionId === session.sessionId + && (payload.queryId === undefined || payload.queryId === queryId) + && requestSerial !== undefined && querySerial !== undefined + && Number.isSafeInteger(Number(requestSerial)) && Number.isSafeInteger(Number(querySerial)) + && Number(requestSerial) > Number(querySerial); + + if (expired) { + // The hold elapsed, so the client can never answer this call. Refuse it so StepCode stops waiting + // instead of burning its own window, and do NOT re-dispatch: the client already received this tool + // call, and a second `tool_call_start` for the same id would be a duplicate. + session.refuseToolCall( + frame, + "The client did not return a tool result inside the window this transport holds a call for.", + ); + return; + } + + // Even with no turn registered, a reverse request must be ANSWERED. Dropping it leaves the runtime + // waiting out its own 60s/120s window with nothing to show for it, and the client has no way to + // learn that the call was silently dropped. + if (frame.method === "permission.request") { + const toolName = typeof payload.toolName === "string" ? payload.toolName : ""; + if (ownsQuery && turn && resolveStepToolName(toolName, turn.emittedNames)) session.allowPermission(frame); + else session.denyPermission(frame, "No active query owns this declared tool permission."); + return; + } + + if (frame.method === "sdk_tool.invoke" && (!turn || !ownsQuery)) { + session.refuseToolCall( + frame, + "OpenCodex is not expecting a tool call for this conversation right now, so it was not executed.", + ); + return; + } + + if (!turn) { + session.denyPermission(frame, `OpenCodex cannot handle ${frame.method ?? "this request"} outside a turn.`); + return; + } + + if (frame.method === "sdk_tool.invoke") { + const payload = (frame.payload ?? {}) as { + input?: unknown; + toolUseId?: string; + serverName?: string; + toolName?: string; + }; + // The descriptor's `toolName` is BARE; the name StepCode registered is + // `${serverName}__${toolName}`. Recomposing the wire name from both fields is what makes the + // lookup work, and a lookup that misses has to refuse rather than guess. + const serverName = typeof payload.serverName === "string" ? payload.serverName : ""; + const bareName = typeof payload.toolName === "string" ? payload.toolName : ""; + const wireName = serverName && bareName ? `${serverName}__${bareName}` : bareName; + const resolved = resolveStepToolName(wireName, turn.emittedNames); + if (!resolved) { + session.refuseToolCall( + frame, + `OpenCodex did not declare ${wireName || "this tool"} for this turn, so the call was not executed.`, + ); + return; + } + const callId = + typeof payload.toolUseId === "string" && payload.toolUseId.length > 0 + ? payload.toolUseId + : `call_${frame.id}`; + turn.pool.rememberHeldTool(turn.ref, { frameId: frame.id, callId, queryId: queryId!, catalogKey: turn.catalogKey }); + turn.emit({ type: "tool_call_start", id: callId, name: resolved }); + turn.emit({ type: "tool_call_delta", arguments: JSON.stringify(asRecord(payload.input)) }); + turn.emit({ type: "tool_call_end" }); + turn.emit({ + type: "done", + stopReason: "tool_use", + providerState: continuationFor(turn.ref, session.sessionId), + }); + endTurn(session); + turn.settle(); + return; + } + + // An unrecognised reverse method still needs an answer rather than being left to expire inside the + // model's context. + session.denyPermission(frame, `OpenCodex does not handle ${frame.method ?? "this request"}.`); +} + +/** + * Map one runtime frame onto the client's event stream. + * + * The framed protocol nests the projected message: a frame is `{queryId, message: {...}}` and the + * event type lives at `message.type`, NOT at `payload.type` the way `step --mode json` prints it. + * Reading the wrong level makes every turn look idle until it times out, so the nesting is resolved + * once here and every branch below works off the inner message. + */ +/** + * Exported with `handleReverseRequest` for the same reason: the CLI's event vocabulary is the other + * half of this transport, and the terminal-event mapping had no test at all until the suite pointed + * out that it was the one thing a fake process must be able to deliver. + */ + +/** + * Map one runtime frame onto the client's event stream. + * + * The framed protocol nests the projected message: a frame is `{queryId, message: {...}}` and the + * event type lives at `message.type`, NOT at `payload.type` the way `step --mode json` prints it. + * Reading the wrong level makes every turn look idle until it times out, so the nesting is resolved + * once here and every branch below works off the inner message. + */ +/** + * Exported with `handleReverseRequest` for the same reason: the CLI's event vocabulary is the other + * half of this transport, and the terminal-event mapping had no test at all until the suite pointed + * out that it was the one thing a fake process must be able to deliver. + */ +export function handleRuntimeEvent(session: StepConversationSession, frame: StepFrame): void { + const turn = currentTurn(session); + if (!turn) return; + const payload = asRecord(frame.payload); + if (!turn.queryId || payload.queryId !== turn.queryId || currentQuery(session) !== turn.queryId) return; + const message = asRecord(payload.message ?? payload); + const type = typeof message.type === "string" ? message.type : undefined; + + if (type === "stream_event") { + const event = asRecord(message.event); + const delta = asRecord(event.delta); + if (delta.type === "text_delta" && typeof delta.text === "string") { + turn.emit({ type: "text_delta", text: delta.text }); + return; + } + if (delta.type === "thinking_delta" && typeof delta.thinking === "string") { + turn.emit({ type: "thinking_delta", thinking: delta.thinking }); + } + return; + } + + if (type === "assistant") { + const usage = toUsage(asRecord(asRecord(message.message).usage)); + if (usage) recordAssistantUsage(session, usage); + return; + } + + if (type === "status" && (message.status === "turn_complete" || message.status === "done")) { + const usage = assistantUsage(session); + turn.emit({ + type: "done", + ...(usage ? { usage } : {}), + stopReason: "stop", + providerState: continuationFor(turn.ref, session.sessionId), + }); + endTurn(session); + turn.settle(); + // Release the runtime's single query slot for this conversation's next turn. Skipped when a tool + // call was captured, which ends the turn earlier and keeps the query alive on purpose. + const queryId = currentQuery(session); + if (queryId) { + forgetQuery(session); + // Observe the derived rejection here. The pool can still await the session's cleanup receipt. + void session.endInput(queryId).catch(() => session.close()).catch(() => {}); + } + return; + } + + if (type === "permission_denied") { + turn.emit({ + type: "error", + message: "StepCode refused a tool call.", + status: 400, + errorType: "invalid_request_error", + code: "step_cli_permission_denied", + retryable: false, + }); + endTurn(session); + turn.settle(); + } +} + +export const sessionHandlers = { + onEvent(event: StepSessionEvent): void { + if (event.type === "reverse_request") { + handleReverseRequest(event.session, event.frame); + return; + } + handleRuntimeEvent(event.session, event.frame); + }, +}; diff --git a/src/adapters/step-cli/profiles.ts b/src/adapters/step-cli/profiles.ts new file mode 100644 index 00000000000..e25048c5b43 --- /dev/null +++ b/src/adapters/step-cli/profiles.ts @@ -0,0 +1,134 @@ +import { existsSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +import { + clearCodingAgentBinaryCache, + resolveProfileByBaseUrl, + whichFromPath, + type CodingAgentProviderProfile, + type WhichFn, +} from "../coding-agent/profile"; + +/** + * Official StepCode CLI (阶跃星辰) as a transport for a Step Plan subscription. + * + * StepCode has no region-scoped variants in this registry: `step login` records one profile + * (`step_plan`, `step_plan_oversea`, `platform_cn`, `platform_oversea`) inside the CLI's own + * `auth.json`, and the CLI is the only component that reads it. The registry therefore selects the + * profile by provider id, not by URL, and fails closed on any destination the CLI does not own. + */ +export interface StepCliProfile extends CodingAgentProviderProfile { + family: "step"; +} + +export const STEP_CLI_PROFILE: StepCliProfile = { + providerId: "step-cli", + family: "step", + region: "global", + label: "StepCode CLI (subscription)", + /** + * The destination the subscription's traffic actually reaches. OpenCodex never sends this host: + * the CLI performs every request, so the value exists to fail closed when a row is repointed at + * something this adapter cannot speak to. + */ + canonicalBaseUrl: "https://api.stepfun.com/step_plan", + /** + * StepCode installs itself to `~/.stepcode/bin/step` rather than onto PATH, so the PATH scan is + * only the first attempt — see {@link findStepCliBinary}. + */ + binaryCandidates: ["step"], + /** + * Deliberately absent: the CLI owns its sign-in (`step login`), so this provider neither requires + * nor injects a credential and has no secret to redact. Mirrors the `claude-cli` row. + */ + installHint: "install the StepCode CLI, then sign in once with `step login`", + documentationUrl: "https://platform.stepfun.com/docs/zh/step-plan/quick-start", +}; + +export const STEP_CLI_PROFILES: readonly StepCliProfile[] = [STEP_CLI_PROFILE]; + +export function resolveStepCliProfile(baseUrl: string | undefined): StepCliProfile | undefined { + return resolveProfileByBaseUrl(STEP_CLI_PROFILES, baseUrl) as StepCliProfile | undefined; +} + +export const clearStepCliBinaryCache = clearCodingAgentBinaryCache; + +/** + * Locate the StepCode executable before any request is dispatched. + * + * The self-install location is checked after PATH and only for the bare `step` candidate: a PATH + * entry an operator added by hand wins, while a service or GUI launch with a stale PATH still finds + * the install it owns. Mirrors {@link findClaudeCliBinary}'s ordering. + */ +export function findStepCliBinary( + candidate: string, + pathLookup: WhichFn = whichFromPath, + userHome = homedir(), + platform: NodeJS.Platform = process.platform, +): string | undefined { + const onPath = pathLookup(candidate); + if (onPath) return resolve(onPath); + if (candidate !== "step") return undefined; + const installed = join(userHome, ".stepcode", "bin", platform === "win32" ? "step.exe" : "step"); + return existsSync(installed) ? installed : undefined; +} + +/** + * Flags that make one headless turn independent of the operator's StepCode setup. + * + * The contract is deliberately total rather than selective. StepCode otherwise loads the user's + * extensions, skills, prompt templates, themes, `AGENTS.md`/`CLAUDE.md` context files and every MCP + * server in `~/.stepcode/config.toml` — a 40-server host config turns a proxied turn into a + * multi-second startup whose tools and prompts are not part of this provider's advertised contract. + * Tool ownership is the reason for the whole route, so `--no-tools` is not a limitation here: the + * client's catalog is declared over the SDK stdio protocol instead. + */ +export const STEP_CLI_ISOLATION_ARGS: readonly string[] = Object.freeze([ + "--no-tools", + "--no-extensions", + "--no-skills", + "--no-prompt-templates", + "--no-themes", + "--no-context-files", + "--no-session", + "--no-update-check", +]); + +/** Spawn arguments for one `step` process. Isolated by construction, not by post-hoc filtering. */ +export function buildStepCliArgs(model: string | undefined, thinkingLevel: string | undefined): string[] { + const args = ["--sdk-stdio", ...STEP_CLI_ISOLATION_ARGS]; + if (model) args.push("--model", model); + if (thinkingLevel) args.push("--thinking", thinkingLevel); + return args; +} + +/** + * Per-turn working directory for the state this proxy owns. + * + * Only session files are redirected. The CLI's own config directory — and with it `auth.json` — is + * deliberately left where StepCode put it: copying a credential into `~/.opencodex` to satisfy a + * convenience would put a second copy of a live subscription token on disk and hand this adapter a + * secret to redact, which is the exact posture the `claude-cli` row refuses (§三十一). Host MCP + * servers in the operator's config may therefore still initialize; `--no-tools` is what makes them + * unreachable, and permission mode and model are set per query regardless of what the file says. + */ +export function stepCliStateRoot(openCodexHome: string): string { + return join(openCodexHome, "step-cli"); +} + +/** + * Directory holding proxied session files. + * + * Redirecting this keeps proxied turns out of the operator's own `~/.stepcode/agent/sessions` + * tree, so a conversation driven through the proxy is never mistaken for a local `step` session and + * can be reaped without touching real history. + */ +export function stepCliSessionDir(openCodexHome: string): string { + return join(stepCliStateRoot(openCodexHome), "sessions"); +} + +/** Default state root when the proxy has not published one. */ +export function defaultStepCliStateRoot(): string { + return join(tmpdir(), "opencodex-step-cli"); +} diff --git a/src/adapters/step-cli/projection.ts b/src/adapters/step-cli/projection.ts new file mode 100644 index 00000000000..cc603199a47 --- /dev/null +++ b/src/adapters/step-cli/projection.ts @@ -0,0 +1,242 @@ +import type { OcxParsedRequest, OcxUsage } from "../../types"; +import type { IncomingMeta } from "../base"; +import { buildSystemPrompt } from "../coding-agent/protocol"; +import { CODING_AGENT_TOOL_LIMITS } from "../coding-agent/tool-catalog"; +import { STEP_CLI_CONTINUATION_KEY, STEP_CLI_TOOL_SERVER } from "./constants"; +import type { StepConversationRef } from "./session-pool"; + +/** + * Everything between "what the client sent" and "what the CLI is told". + * + * Kept apart from the transport on purpose: these are pure functions over a parsed request, so the + * awkward parts of this route — a tool result carrying an image, a model id with a namespace, an + * effort that has to become a token budget — can be read and tested without a session in the picture. + */ + +/** `providerState` slot carrying the conversation handle between requests. */ +export type StepProviderState = { [STEP_CLI_CONTINUATION_KEY]: { handle: string; sessionId: string } }; + +/** + * How long a conversation's process survives without traffic. + * + * Long enough that a Codex thread's pauses between turns do not tear the conversation down, short + * enough that an abandoned thread does not leave a StepCode process running. + */ + +export function continuationFor(ref: StepConversationRef, sessionId: string | undefined): StepProviderState | undefined { + if (!ref) return undefined; + return { [STEP_CLI_CONTINUATION_KEY]: { handle: ref.handle, sessionId: sessionId ?? ref.sessionId } }; +} + +/** The newest tool result in the request, with the call it answers. */ + +/** A `data:` URL split into the base64 payload and media type StepCode's image block expects. */ + +/** A `data:` URL split into the base64 payload and media type StepCode's image block expects. */ +export function parseInlineImageDataUrl(imageUrl: string): { data: string; mimeType: string } | undefined { + const match = /^data:([^;,]+);base64,(.+)$/s.exec(imageUrl); + if (!match) return undefined; + return { mimeType: match[1]!, data: match[2]! }; +} + +/** + * Project a client tool result into the content blocks StepCode's SDK tool accepts. + * + * A tool result is not necessarily text. Codex's `view_image` returns an image part, and collapsing + * that to an empty text block is the same misleading-empty-result failure the wrong-call path already + * had: the model reports a tool that "returned nothing" instead of saying it could not read the image. + * Inline `data:` images are forwarded; a remote URL cannot be, so it is replaced by a note the model can + * act on rather than dropped in silence. + */ + +/** + * Project a client tool result into the content blocks StepCode's SDK tool accepts. + * + * A tool result is not necessarily text. Codex's `view_image` returns an image part, and collapsing + * that to an empty text block is the same misleading-empty-result failure the wrong-call path already + * had: the model reports a tool that "returned nothing" instead of saying it could not read the image. + * Inline `data:` images are forwarded; a remote URL cannot be, so it is replaced by a note the model can + * act on rather than dropped in silence. + */ +export function projectToolResultContent( + raw: string | readonly unknown[], +): Array> { + if (typeof raw === "string") return raw.length > 0 ? [{ type: "text", text: raw }] : []; + const blocks: Array> = []; + const notes: string[] = []; + for (const part of raw) { + const block = asRecord(part); + if (block.type === "text" && typeof block.text === "string") { + blocks.push({ type: "text", text: block.text }); + continue; + } + if (block.type === "image" && typeof block.imageUrl === "string") { + const inline = parseInlineImageDataUrl(block.imageUrl); + if (inline) { + blocks.push({ type: "image", data: inline.data, mimeType: inline.mimeType }); + continue; + } + notes.push(`an image at ${block.imageUrl} could not be inlined; fetch it yourself if you need it`); + continue; + } + notes.push(`a ${typeof block.type === "string" ? block.type : "unknown"} result part was dropped`); + } + for (const note of notes) blocks.push({ type: "text", text: note }); + if (blocks.length === 0) { + return [{ type: "text", text: "the tool returned no readable content" }]; + } + return blocks; +} + +export function latestToolResult( + parsed: OcxParsedRequest, +): { content: readonly unknown[]; isError?: boolean; toolCallId: string } | undefined { + for (let index = parsed.context.messages.length - 1; index >= 0; index -= 1) { + const message = parsed.context.messages[index]; + if (!message || message.role !== "toolResult") continue; + return { + content: projectToolResultContent(message.content), + toolCallId: message.toolCallId, + ...(message.isError ? { isError: true } : {}), + }; + } + return undefined; +} + +export function toUsage(usage: Record): OcxUsage | undefined { + const input = typeof usage.input === "number" ? usage.input : undefined; + const output = typeof usage.output === "number" ? usage.output : undefined; + if (input === undefined && output === undefined) return undefined; + return { + inputTokens: input ?? 0, + outputTokens: output ?? 0, + ...(typeof usage.cacheRead === "number" ? { cachedInputTokens: usage.cacheRead } : {}), + }; +} + +/** + * StepCode model ids carry no provider prefix; the CLI owns its own default provider. + */ + +/** + * StepCode model ids carry no provider prefix; the CLI owns its own default provider. + */ +export function stepModelId(modelId: string): string { + return modelId.startsWith(`${STEP_CLI_TOOL_SERVER}/`) + ? modelId.slice(STEP_CLI_TOOL_SERVER.length + 1) + : modelId; +} + +/** + * StepCode's per-query thinking control is a token budget, so an effort has to be converted. + * + * The mapping is deliberately lossy and the registry only advertises the three rungs Step actually + * serves, so a client never believes it chose a depth it did not. + */ + +/** + * StepCode's per-query thinking control is a token budget, so an effort has to be converted. + * + * The mapping is deliberately lossy and the registry only advertises the three rungs Step actually + * serves, so a client never believes it chose a depth it did not. + */ +export function stepThinkingTokens(parsed: OcxParsedRequest): number | undefined { + const effort = parsed.options.reasoning; + if (typeof effort !== "string" || effort === "none") return undefined; + const table: Record = { + minimal: 1_024, + low: 4_096, + medium: 16_384, + high: 32_768, + xhigh: 65_536, + max: 65_536, + }; + return table[effort] ?? table.high!; +} + +/** + * Fold the caller's instructions into the one user message this hop can carry. + * + * StepCode cannot replace its session system prompt, so its own coding instructions stay in front of + * the model's answers. Prepending the client's own instructions keeps the turn answerable under the + * contract the client believes it set. + */ + +/** + * Fold the caller's instructions into the one user message this hop can carry. + * + * StepCode cannot replace its session system prompt, so its own coding instructions stay in front of + * the model's answers. Prepending the client's own instructions keeps the turn answerable under the + * contract the client believes it set. + */ +export function composePrompt(parsed: OcxParsedRequest, userText: string): string { + const system = buildSystemPrompt(parsed); + return system ? `${system}\n\n${userText}` : userText; +} + +/** Resolves when the client aborts, so a turn in flight does not outlive its request. */ +export function abortSignal(incoming: IncomingMeta): Promise { + const signal = incoming.abortSignal; + if (!signal) return new Promise(() => undefined); + if (signal.aborted) return Promise.resolve(); + return new Promise(resolve => { + signal.addEventListener("abort", () => resolve(), { once: true }); + }); +} + +export function asRecord(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; +} + +/** Translate a transport failure into the actionable error an operator can act on. */ + +/** + * The text StepCode should be asked for on this turn. + * + * Only the final user message crosses `query.input`; earlier turns live in the process' session, + * because the wire reduces every message to text and images. + */ +export function pendingUserText(parsed: OcxParsedRequest): string | undefined { + for (let index = parsed.context.messages.length - 1; index >= 0; index -= 1) { + const message = parsed.context.messages[index]; + if (!message || message.role !== "user") continue; + if (!Array.isArray(message.content)) { + return typeof message.content === "string" && message.content.length > 0 + ? message.content + : undefined; + } + const text = message.content + .filter(part => part.type === "text") + .map(part => (part as { text: string }).text) + .join("") + .trim(); + if (text.length > 0) return text; + } + return undefined; +} + +/** + * Refuse image input the way the Qoder and Claude Code rows do. + * + * `query.input` does carry an image block to the model, but this route publishes text-only models, + * and an image the harness silently drops produces a confident answer to the wrong question. An + * operator with the vision sidecar on the request path still gets pictures captioned into text. + */ +export function hasImageInput(parsed: OcxParsedRequest): boolean { + return parsed.context.messages.some(message => + Array.isArray(message.content) && message.content.some(part => part.type === "image"), + ); +} + +/** + * Identify the conversation this request belongs to. + * + * StepCode keeps a conversation only inside one process, so every request of a Codex thread has to + * land on the same session. The thread identity is what Codex already sends on EVERY request — + * `thread-id`, then the session-affinity headers — which is the resolution `devin`, `zed`, `cursor` + * and `google` use, and it works on the first request of a conversation. `previous_response_id` and + * the proxy's continuation store are only fallbacks: depending on persisted provider state would mean + * a conversation silently restarting whenever that store misses an entry. + */ diff --git a/src/adapters/step-cli/registry.ts b/src/adapters/step-cli/registry.ts new file mode 100644 index 00000000000..0bb0c1bb99a --- /dev/null +++ b/src/adapters/step-cli/registry.ts @@ -0,0 +1,181 @@ +import { getConfigDir } from "../../config/paths"; +import { didRunDrainStartHooks, didRunOptionalShutdownHooks, registerAsyncOptionalShutdownHook } from "../../lib/optional-shutdown-hooks"; +import type { AdapterEvent, OcxUsage } from "../../types"; +import { buildStepCliArgs } from "./profiles"; + +/** + * How long a conversation's process survives without traffic. + * + * Long enough that a Codex thread's pauses between turns do not tear the conversation down, short + * enough that an abandoned thread does not leave a StepCode process running. + */ +export const STEP_CLI_IDLE_TIMEOUT_MS = 10 * 60_000; +import { + resolveStepCliBinaryPath, + stepCliProcessEnvironment, + StepSessionError, + type StepSessionDeps, + type StepSessionEvent, +} from "./session"; +import { + StepSessionPool, + type StepConversationHost, + type StepConversationRef, + type StepConversationSession, +} from "./session-pool"; + +/** + * Process- and turn-lifetime state that outlives a request. + * + * `createStepCliAdapter` runs once per request, so anything that must survive a request boundary + * cannot live in its closure: a reverse request arriving during request N+1 would be routed to an + * instance that no longer exists and the conversation would silently restart. `devin/trajectory.ts` + * keeps its conversation map at module scope for the same reason. + */ + +/** + * Per-request turn state, keyed by the process that owns it. + * + * `createStepCliAdapter` runs once per request, so nothing that has to survive a request boundary can + * live in its closure: a reverse request arriving during request N+1 would be routed to an instance + * that no longer exists, and the conversation would silently restart. `devin/trajectory.ts` keeps its + * conversation map at module scope for the same reason. + */ +export interface StepTurnRuntime { + ref: StepConversationRef; + pool: StepConversationHost; + emit: (event: AdapterEvent) => void; + settle: () => void; + emittedNames: Map; + catalogKey: string; + queryId?: string; +} + +export const turnRuntimes = new WeakMap(); + +export const lastAssistantUsage = new WeakMap(); + +/** Query currently owned by each session, so an abandoned turn can interrupt exactly that one. */ +export const lastQueryId = new WeakMap(); + +/* ------------------------------------------------------------------------- * + * Turn runtime accessors. + * + * `events` and `adapter` go through these instead of touching the maps, so the storage shape can + * change without every caller changing with it — and so "who owns this session's turn" is answered in + * one place rather than by whoever happens to remember the variable name. + * ------------------------------------------------------------------------- */ + +/** Attach a turn to the session that owns it, replacing any turn left behind. */ +export function beginTurn(session: StepConversationSession, turn: StepTurnRuntime): void { + lastAssistantUsage.delete(session); + turnRuntimes.set(session, turn); +} + +/** The turn currently owning this session, if any. */ +export function currentTurn(session: StepConversationSession): StepTurnRuntime | undefined { + return turnRuntimes.get(session); +} + +/** Detach a session's turn. Returns true when one was actually attached. */ +export function endTurn(session: StepConversationSession): boolean { + return turnRuntimes.delete(session); +} + +/** Record the usage the CLI reported for this session's assistant turn. */ +export function recordAssistantUsage(session: StepConversationSession, usage: OcxUsage): void { + lastAssistantUsage.set(session, usage); +} + +/** The usage recorded for this session's assistant turn, if any. */ +export function assistantUsage(session: StepConversationSession): OcxUsage | undefined { + return lastAssistantUsage.get(session); +} + +/** Remember which query this session is running, so an abandoned turn interrupts exactly that one. */ +export function rememberQuery(session: StepConversationSession, queryId: string): void { + lastQueryId.set(session, queryId); + const turn = currentTurn(session); + if (turn) turn.queryId = queryId; +} + +/** The query this session is running, if any. */ +export function currentQuery(session: StepConversationSession): string | undefined { + return lastQueryId.get(session); +} + +/** Forget the session's query, e.g. once its input stream has been closed. */ +export function forgetQuery(session: StepConversationSession): void { + lastQueryId.delete(session); +} + +/** One pool per OpenCodex home, so two homes in one process never share a StepCode session. */ +export const pools = new Map(); + +const STEP_CLI_SHUTDOWN_KEY = "step-cli-sessions"; +/** Close every owned process during proxy shutdown or an explicit registry clear. */ +export async function clearStepCliSessions(deadlineMs?: number): Promise { + const closed = await Promise.allSettled([...pools].map(async ([home, pool]) => { + await pool.closeAll(deadlineMs); + if (pools.get(home) === pool) pools.delete(home); + })); + const failure = closed.find(result => result.status === "rejected"); + if (failure?.status === "rejected") throw failure.reason; +} + +function forceStepCliShutdown(): void { + let failed = false; + for (const pool of pools.values()) { + try { pool.forceShutdown(); } + catch { failed = true; } + } + if (failed) throw new StepSessionError("StepCode emergency process cleanup failed.", "step_cli_cleanup_failed"); +} + +export function poolFor( + home: string, + deps: StepSessionDeps, + handlers: { onEvent(event: StepSessionEvent): void }, +): StepSessionPool { + if (didRunDrainStartHooks() || didRunOptionalShutdownHooks()) throw new StepSessionError("StepCode cannot open sessions while the proxy is shutting down."); + const existing = pools.get(home); + if (existing) return existing; + registerAsyncOptionalShutdownHook(STEP_CLI_SHUTDOWN_KEY, clearStepCliSessions, forceStepCliShutdown); + const { env, cwd } = stepCliProcessEnvironment(home); + const pool = new StepSessionPool( + { + openCodexHome: home, + idleTimeoutMs: STEP_CLI_IDLE_TIMEOUT_MS, + buildOptions: () => ({ + binary: resolveStepCliBinaryPath(deps.which), + args: buildStepCliArgs(undefined, undefined), + env, + cwd, + handshakeTimeoutMs: 30_000, + requestTimeoutMs: 120_000, + // StepCode's own tool window is 120s and answering later produces a `permission_denied` + // message inside the model's context, so the hold is bounded shorter and fails the turn. + reverseRequestHoldMs: 110_000, + idleTimeoutMs: STEP_CLI_IDLE_TIMEOUT_MS, + killGraceMs: 2_000, + }), + }, + handlers, + deps, + ); + pools.set(home, pool); + return pool; +} + +/** + * A reverse request the CLI is waiting on this peer to answer. + * + * `permission.request` is allowed immediately because the approval already happened upstream of this + * adapter. A `sdk_tool.invoke` is deliberately NOT answered here: its result only exists once the + * client has executed the tool and sent its next request, and answering it is how that result reaches + * the model inside the query the model is already running. + */ +/** + * Exported for its regression tests: every reverse request must be ANSWERED, and the tests drive this + * exact function rather than a mirror of it. + */ diff --git a/src/adapters/step-cli/session-pool.ts b/src/adapters/step-cli/session-pool.ts new file mode 100644 index 00000000000..3cbcafdf415 --- /dev/null +++ b/src/adapters/step-cli/session-pool.ts @@ -0,0 +1,225 @@ +import { StepCliSession, StepSessionError, type StepSessionDeps, type StepSessionEvent, type StepSessionHandlers, type StepSessionOptions } from "./session"; + +/** Conversation identity the client echoes back through `providerState`. */ +export interface StepConversationRef { + sessionId: string; + /** Process-local key; never a credential, only a proxy-internal handle. */ + handle: string; +} + +/** + * The reverse request this conversation is holding, and the call it belongs to. + * + * The call id is kept beside the frame id because the client's next request may carry results for + * several calls; delivering the newest result by POSITION would answer the wrong call. + */ +export interface StepHeldTool { + readonly frameId: string; + readonly callId: string; + readonly queryId: string; + readonly catalogKey: string; +} + +export interface StepSessionPoolOptions { + openCodexHome: string; + buildOptions: () => StepSessionOptions; + idleTimeoutMs: number; +} + +interface PoolEntry { + readonly ref: StepConversationRef; + readonly session: StepCliSession; + /** Reverse request the pool is currently holding for the next client request. */ + heldTool: StepHeldTool | undefined; +} + +/** + * Conversation-keyed StepCode sessions. + * + * The pool exists because StepCode's only durable conversation state is process memory: one process + * serves one query at a time (`maxConcurrentQueries: 1`) and `query.input` carries text and images + * only, so a client conversation maps onto exactly one live process. Entries are reclaimed by idle + * timeout and on process exit, and a conversation whose process died is reported as such rather than + * silently restarted — a restart would lose the model's view of earlier tool results, and a tool + * result the client already delivered is not recoverable from the transcript. + */ +/** + * The conversation bookkeeping the adapter depends on. + * + * Narrower than the pool itself so a test can supply a fake process and still exercise the real + * `runTurn` path — the path that decides whether a captured call is answered, refused or abandoned. + */ +export interface StepConversationHost { + get(ref: StepConversationRef | undefined): StepConversationSession | undefined; + open(ref: StepConversationRef): Promise; + nextRef(): StepConversationRef; + rememberHeldTool(ref: StepConversationRef, held: StepHeldTool): void; + takeHeldTool(ref: StepConversationRef): StepHeldTool | undefined; + closeAll(): Promise; +} + +/** The session surface `runTurn` uses. */ +export type StepConversationSession = Pick< + StepCliSession, + "sessionId" | "closed" | "handshake" | "startQuery" | "sendInput" | "endInput" | "interrupt" | "close" | "resolveHeldToolResult" | "allowPermission" | "denyPermission" | "refuseToolCall" +>; + +export class StepSessionPool implements StepConversationHost { + readonly #entries = new Map(); + /** + * In-flight opens, keyed by handle. + * + * `open` is async, so two requests for one conversation (a Codex retry, or two clients sharing a + * handle) both miss the map and both spawn a process; the second `#entries.set` then orphans the + * first session with a held tool call nobody can release. Coalescing on the promise makes one + * conversation exactly one process. + */ + readonly #opening = new Map>(); + /** Track ownership from construction through confirmed cleanup, even for an in-flight open. */ + readonly #sessions = new Set(); + readonly #options: StepSessionPoolOptions; + readonly #deps: StepSessionDeps; + readonly #handlers: StepSessionHandlers; + readonly #sweepMs: number; + #sweep: ReturnType | undefined; + #handleSeq = 0; + #closing = false; + #closePromise: Promise | undefined; + + constructor( + options: StepSessionPoolOptions, + handlers: StepSessionHandlers, + deps: StepSessionDeps = {}, + ) { + this.#options = options; + this.#handlers = handlers; + this.#deps = deps; + this.#sweepMs = Math.max(1_000, Math.min(options.idleTimeoutMs, 60_000)); + } + + /** Look up a live session for a conversation, if one is still open. */ + get(ref: StepConversationRef | undefined): StepCliSession | undefined { + if (!ref) return undefined; + const entry = this.#entries.get(ref.handle); + return entry && !entry.session.closed ? entry.session : undefined; + } + + /** Open a session for a conversation, coalescing concurrent opens of the same handle. */ + async open(ref: StepConversationRef): Promise { + if (this.#closing) throw new StepSessionError("StepCode session pool is closing."); + const existing = this.get(ref); + if (existing) return existing; + if (this.#entries.has(ref.handle)) { + throw new StepSessionError("StepCode conversation cleanup is pending or quarantined.", "step_cli_cleanup_failed"); + } + const inFlight = this.#opening.get(ref.handle); + if (inFlight) return inFlight; + const opening = (async () => { + const session = await StepCliSession.open(this.#options.buildOptions(), this.#handlers, this.#deps, owned => { + this.#sessions.add(owned); + owned.onExit(() => this.#sessions.delete(owned)); + }); + if (this.#closing) { + await session.close(); + return session; + } + const entry: PoolEntry = { ref, session, heldTool: undefined }; + this.#entries.set(ref.handle, entry); + session.onExit(() => { + if (this.#entries.get(ref.handle) === entry) this.#entries.delete(ref.handle); + }); + this.#ensureSweep(); + return session; + })(); + this.#opening.set(ref.handle, opening); + try { + return await opening; + } finally { + if (this.#opening.get(ref.handle) === opening) this.#opening.delete(ref.handle); + } + } + + /** + * Remember which reverse request the next client request must answer. + * + * The result arrives in a later HTTP request, so the frame has to outlive the turn that produced + * it. Storing only its id keeps the session's own hold timer authoritative. + */ + rememberHeldTool(ref: StepConversationRef, held: StepHeldTool): void { + const entry = this.#entries.get(ref.handle); + if (entry) entry.heldTool = held; + } + + /** Consume the remembered hold, so one tool result can never be delivered twice. */ + takeHeldTool(ref: StepConversationRef): StepHeldTool | undefined { + const entry = this.#entries.get(ref.handle); + if (!entry) return undefined; + const held = entry.heldTool; + entry.heldTool = undefined; + return held; + } + + /** Mint the identity a new conversation is addressed by. */ + nextRef(): StepConversationRef { + this.#handleSeq += 1; + return { handle: `step_${this.#handleSeq}`, sessionId: "" }; + } + + #ensureSweep(): void { + if (this.#sweep) return; + this.#sweep = setInterval(() => { + for (const entry of [...this.#entries.values()]) { + if (entry.session.closed || entry.session.idleMs() >= this.#options.idleTimeoutMs) { + // The exit listener releases the handle only after cleanup succeeds. Failed sessions + // stay owned and the entry remains quarantined; never retry from every sweep. + void entry.session.close().catch(() => {}); + } + } + if (this.#entries.size === 0) this.#stopSweep(); + }, this.#sweepMs); + this.#sweep.unref?.(); + } + + #stopSweep(): void { + if (!this.#sweep) return; + clearInterval(this.#sweep); + this.#sweep = undefined; + } + + get size(): number { + return this.#entries.size; + } + + closeAll(deadlineMs?: number): Promise { + this.#closing = true; + if (deadlineMs !== undefined) { + for (const session of this.#sessions) session.closeBy(deadlineMs); + } + if (this.#closePromise) return this.#closePromise; + this.#stopSweep(); + const opening = [...this.#opening.values()]; + const entries = [...this.#entries.values()]; + this.#closePromise = (async () => { + const closed = await Promise.allSettled(entries.map(entry => entry.session.close())); + // An open owns its child until it returns. Its closing branch reaps that child before + // resolving, so shutdown cannot finish while a late open can still publish a session. + const opened = await Promise.allSettled(opening); + const cleanup = await Promise.allSettled([...this.#sessions].map(session => session.close())); + const failure = [...closed, ...opened, ...cleanup].find(result => result.status === "rejected"); + if (failure?.status === "rejected") throw failure.reason; + })(); + return this.#closePromise; + } + + forceShutdown(): void { + let failed = false; + for (const session of this.#sessions) { + try { session.forceShutdown(); } + catch { failed = true; } + } + if (failed) throw new StepSessionError("StepCode emergency process cleanup failed.", "step_cli_cleanup_failed"); + } +} + +export { StepSessionError }; +export type { StepSessionEvent, StepSessionHandlers }; diff --git a/src/adapters/step-cli/session.ts b/src/adapters/step-cli/session.ts new file mode 100644 index 00000000000..44ad7657366 --- /dev/null +++ b/src/adapters/step-cli/session.ts @@ -0,0 +1,842 @@ +import { spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from "node:child_process"; +import { mkdir } from "node:fs/promises"; +import { dirname } from "node:path"; + +import { commandInvocation } from "../../lib/win-exec"; +import { killWindowsProcessTreeAsync } from "../coding-agent/process-tree"; +import type { WhichFn } from "../coding-agent/profile"; +import { buildStepCliEnv } from "./env"; +import { classifyStepChildError, StepSessionError } from "./errors"; +import { + findStepCliBinary, + stepCliSessionDir, + STEP_CLI_PROFILE, + type StepCliProfile, +} from "./profiles"; +import { + encodeStepFrame, + stepErrorResponse, + stepRequest, + stepResponse, + StepFrameDecoder, + StepProtocolViolation, + STEP_MAX_FRAME_BYTES, + STEP_PROTOCOL_VERSION, + type StepFrame, +} from "./stdio-frames"; + +export type StepSpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess; + +/** + * Capabilities this route cannot work without. + * + * Without `sdk-tools` the runtime answers text only while looking healthy, which is the one failure + * this provider must never present as success: the client would conclude the model simply chose not + * to call its tools, and a routed coding session would silently degrade into a chat. + */ +const REQUIRED_CAPABILITIES = ["streaming-input", "sdk-tools"] as const; +const CLEANUP_ATTEMPTS = 2; +const MAX_PARALLEL_CLEANUPS = 4; +const KILL_CONFIRMATION_MS = 2_000; +const SHUTDOWN_KILL_MARGIN_MS = 250; +const PROCESS_EXIT_POLL_MS = 20; +const POSIX_LEADER_EXITED = "StepCode POSIX process cleanup is incomplete because the process group leader exited before group termination."; +const WINDOWS_PID_UNCONFIRMED = "StepCode Windows process cleanup is incomplete because ownership of the wrapper PID could not be confirmed."; + +// Share slots across pools and all close paths, including idle and late-opening sessions. +let activeCleanups = 0; +const cleanupWaiters = new Set<() => void>(); + +function withCleanupSlot(cleanup: () => Promise, urgent: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const start = (): void => { + cleanupWaiters.delete(start); + urgent.removeEventListener("abort", start); + if (urgent.aborted) { + // At the shutdown margin a queued tree kill must start even if every slot is busy. + void cleanup().then(resolve, reject); + return; + } + activeCleanups++; + const release = (): void => { + activeCleanups--; + cleanupWaiters.values().next().value?.(); + }; + void cleanup().finally(release).then(resolve, reject); + }; + if (urgent.aborted || activeCleanups < MAX_PARALLEL_CLEANUPS) start(); + else { + cleanupWaiters.add(start); + urgent.addEventListener("abort", start, { once: true }); + } + }); +} + +function processIsGone(pid: number): boolean { + try { + process.kill(pid, 0); + return false; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ESRCH") return true; + throw error; + } +} + +export interface StepSessionDeps { + spawn?: StepSpawnFn; + which?: WhichFn; + /** Injectable timer primitives so tests never sleep. */ + setTimeout?: typeof setTimeout; + clearTimeout?: typeof clearTimeout; + now?: () => number; + /** Test seam for Windows command-shim invocation. */ + platform?: NodeJS.Platform; + killWindowsProcessTree?: (pid: number) => Promise; +} + +export interface StepSessionOptions { + binary: string; + args: readonly string[]; + env: Record; + /** Working directory; the session directory is created beneath it. */ + cwd: string; + /** Wall-clock ceiling for `initialize`, in ms. */ + handshakeTimeoutMs: number; + /** Ceiling on a request the runtime has not answered, in ms. */ + requestTimeoutMs: number; + /** + * Ceiling on a reverse request this peer holds. + * + * StepCode's own `SDK_TOOL_TIMEOUT_MS` is 120s and answering late produces a `permission_denied` + * message inside the model's context rather than a transport error. Bounding the hold shorter than + * that turns a too-slow tool into a clean failed turn instead of a session the model believes was + * denied. + */ + reverseRequestHoldMs: number; + /** Reap a session with no activity for this long, in ms. */ + idleTimeoutMs: number; + /** SIGTERM-to-SIGKILL window, in ms. */ + killGraceMs: number; +} + +/** A request awaiting an answer from the runtime. */ +interface PendingRequest { + readonly method: string; + readonly timer: ReturnType; + readonly resolve: (frame: StepFrame) => void; + readonly reject: (error: Error) => void; + answered: boolean; +} + +/** A reverse request the runtime is waiting on this peer to answer. */ +interface HeldReverseRequest { + readonly method: string; + readonly frame: StepFrame; + readonly timer: ReturnType; + answered: boolean; +} + +export { StepSessionError } from "./errors"; + +/** + * What the adapter needs to hear while a session is live. + * + * Every event carries the session that produced it: the handler is shared across every conversation, + * so the origin is the only way to route a frame to the turn that is waiting for it. + */ +export type StepSessionEvent = + | { type: "event"; frame: StepFrame; session: StepCliSession } + | { type: "reverse_request"; frame: StepFrame; session: StepCliSession }; + +export interface StepSessionHandlers { + onEvent(event: StepSessionEvent): void; +} + +/** + * One long-lived `step --sdk-stdio` process, keyed by client conversation. + * + * StepCode carries conversation context only in process memory: `query.input` reduces every message + * to plain text and images (`readQueryInput`), so an assistant turn, a declared tool call and its + * result cannot be replayed through the wire. The session therefore has to outlive one proxied + * request, and the client keeps it alive by echoing back the `providerState` this class mints — + * the same mechanism Kiro uses for `conversationId`. + * + * That constraint is also why a captured tool call is held open rather than answered here. The + * client executes the tool and reports it on its next request; delivering that result to this + * reverse request is how it reaches the model, inside the query the model is already running. + */ +export class StepCliSession { + readonly #options: StepSessionOptions; + readonly #deps: StepSessionDeps; + readonly #handlers: StepSessionHandlers; + readonly #decoder = new StepFrameDecoder(); + readonly #pending = new Map(); + readonly #held = new Map(); + readonly #setTimer: typeof setTimeout; + readonly #clearTimer: typeof clearTimeout; + readonly #now: () => number; + readonly #platform: NodeJS.Platform; + readonly #killGraceMs: number; + + #child: ChildProcess | undefined; + #leaderExited = false; + #posixGroupSignalState: "pending" | "finished" | "lost" = "pending"; + #windowsTreeKillAttempted = false; + #closed = false; + #closePromise: Promise | undefined; + #cleanupComplete = false; + #shutdownDeadlineMs = Infinity; + #shutdownTimer: ReturnType | undefined; + readonly #urgentCleanup = new AbortController(); + #handshake: Promise | undefined; + #sessionId: string | undefined; + #lastActivityAt: number; + #requestSeq = 0; + #stderrTail = ""; + #idleTimer: ReturnType | undefined; + readonly #exitListeners = new Set<() => void>(); + + /** + * Register a callback fired once the owned process cleanup is confirmed. + * + * The pool needs this to drop a conversation whose process died: a restart would come back with no + * memory of the tool results the client already delivered, and those are not recoverable from the + * transcript this route cannot replay. + */ + onExit(listener: () => void): () => void { + if (this.#cleanupComplete) { + listener(); + return () => undefined; + } + this.#exitListeners.add(listener); + return () => this.#exitListeners.delete(listener); + } + + #announceExit(): void { + if (this.#exitListeners.size === 0) return; + const listeners = [...this.#exitListeners]; + this.#exitListeners.clear(); + for (const listener of listeners) { + try { + listener(); + } catch { + // An owner's bookkeeping must never keep a dead session from being reported. + } + } + } + + private constructor(options: StepSessionOptions, deps: StepSessionDeps, handlers: StepSessionHandlers) { + this.#options = options; + this.#deps = deps; + this.#handlers = handlers; + this.#setTimer = deps.setTimeout ?? setTimeout; + this.#clearTimer = deps.clearTimeout ?? clearTimeout; + this.#now = deps.now ?? Date.now; + this.#platform = deps.platform ?? process.platform; + this.#killGraceMs = options.killGraceMs; + this.#lastActivityAt = this.#now(); + } + + static async open( + options: StepSessionOptions, + handlers: StepSessionHandlers, + deps: StepSessionDeps = {}, + own?: (session: StepCliSession) => void, + ): Promise { + const session = new StepCliSession(options, deps, handlers); + own?.(session); + try { + await session.#start(); + } catch (error) { + void session.close(); + throw error; + } + return session; + } + + get sessionId(): string | undefined { + return this.#sessionId; + } + + get closed(): boolean { + return this.#closed; + } + + /** Bounded stderr tail, for diagnostics. Never logged wholesale. */ + get stderrTail(): string { + return this.#stderrTail; + } + + /** Milliseconds since the last frame in either direction. */ + idleMs(): number { + return this.#now() - this.#lastActivityAt; + } + + #touch(): void { + this.#lastActivityAt = this.#now(); + } + + #nextId(): string { + this.#requestSeq += 1; + return `ocx_${this.#requestSeq}`; + } + + async #start(): Promise { + const invocation = commandInvocation(this.#options.binary, this.#options.args, this.#platform); + try { + await mkdir(this.#options.cwd, { recursive: true }); + } catch { + throw new StepSessionError("StepCode could not create its workspace.", "step_cli_workspace_unavailable"); + } + // A deadline-aware close can take ownership while workspace creation is pending. + if (this.#closed) return; + const spawn = this.#deps.spawn ?? nodeSpawn; + const child = spawn(invocation.file, invocation.args, { + ...invocation.options, + env: this.#options.env, + stdio: ["pipe", "pipe", "pipe"], + windowsHide: true, + detached: this.#platform !== "win32", + cwd: this.#options.cwd, + }); + this.#child = child; + child.once("exit", () => { this.#leaderExited = true; }); + + // stderr must be drained continuously: an unread pipe fills and blocks the child mid-turn. Only a + // bounded tail is retained, and it is never logged as content. + // + // `setEncoding("utf8")` rather than decoding each chunk: StepCode prints CJK diagnostics (未登录), + // and a multibyte character split across two chunks would decode to U+FFFD on both halves, so the + // not-signed-in detection that matches on that text would stop firing. + child.stderr?.setEncoding("utf8"); + child.stderr?.on("data", (chunk: string) => { + this.#touch(); + this.#stderrTail = (this.#stderrTail + chunk).slice(-2000); + }); + child.stdout?.on("data", (chunk: Buffer) => this.#absorbStdout(chunk)); + child.on("error", error => { + // A spawn failure such as ENOENT can emit `error` without a following `close`, so the sweep has to + // be stopped here too or it lingers on a session that no longer exists. + this.#stopIdleSweep(); + this.#failAll(error instanceof Error ? error : new Error(String(error))); + if (child.pid === undefined) this.#child = undefined; + void this.close(); + }); + child.on("close", () => { + this.#leaderExited = true; + this.#failAll(new StepSessionError("StepCode exited before the turn settled.")); + this.#stopIdleSweep(); + void this.close(); + }); + this.#installIdleSweep(); + } + + #absorbStdout(chunk: Buffer): void { + this.#touch(); + let frames: StepFrame[]; + try { + frames = this.#decoder.push(chunk); + } catch (error) { + // The runtime answers a frame it cannot parse with silence, so writing on into it would hang the + // client for the whole request timeout. Fail every waiter and tear the process down instead. + this.#failAll(error instanceof StepProtocolViolation ? error : new Error(String(error))); + void this.close(); + return; + } + for (const frame of frames) this.#route(frame); + } + + #route(frame: StepFrame): void { + if (frame.kind === "response") { + const replyTo = frame.replyTo; + if (!replyTo) return; + const pending = this.#pending.get(replyTo); + if (!pending) return; + this.#pending.delete(replyTo); + this.#settle(pending, frame); + return; + } + if (frame.kind === "request") { + this.#holdReverse(frame); + return; + } + this.#handlers.onEvent({ type: "event", frame, session: this }); + } + + #holdReverse(frame: StepFrame): void { + const timer = this.#setTimer(() => { + if (!this.#held.delete(frame.id)) return; + // The expiry is surfaced so the peer can answer the runtime. Without an answer here StepCode + // waits out its own 120s window, and a later turn registered for this session would see the same + // frame again and re-emit the tool call the client already received. + this.#handlers.onEvent({ + type: "reverse_request", + frame: { ...frame, payload: { ...(frame.payload as object ?? {}), __expired: true } } as StepFrame, + session: this, + }); + }, this.#options.reverseRequestHoldMs); + this.#held.set(frame.id, { + method: frame.method ?? "unknown", + frame, + timer, + answered: false, + }); + this.#handlers.onEvent({ type: "reverse_request", frame, session: this }); + } + + #settle(pending: PendingRequest, frame: StepFrame): void { + if (pending.answered) return; + pending.answered = true; + this.#clearTimer(pending.timer as never); + if (frame.error) { + pending.reject(classifyStepChildError(frame.error)); + return; + } + pending.resolve(frame); + } + + #failAll(error: Error): void { + for (const pending of this.#pending.values()) { + if (pending.answered) continue; + pending.answered = true; + this.#clearTimer(pending.timer as never); + pending.reject(error); + } + this.#pending.clear(); + } + + #write(frame: StepFrame): void { + const stdin = this.#child?.stdin; + if (this.#closed || !stdin?.writable) { + throw new StepSessionError("StepCode session is not writable."); + } + stdin.write(encodeStepFrame(frame, STEP_MAX_FRAME_BYTES)); + } + + #send(id: string, method: string, payload?: unknown, timeoutMs?: number): Promise { + if (this.#closed) return Promise.reject(new StepSessionError("StepCode session is closed.")); + let pending!: PendingRequest; + const timer = this.#setTimer(() => { + if (this.#pending.delete(id)) pending.reject(new StepSessionError(`StepCode did not answer ${method} in time.`, "timeout")); + }, timeoutMs ?? this.#options.requestTimeoutMs); + const promise = new Promise((resolve, reject) => { + pending = { method, timer, resolve, reject, answered: false }; + }); + this.#pending.set(id, pending); + try { + this.#write(stepRequest(id, method, payload)); + } catch (error) { + this.#pending.delete(id); + this.#clearTimer(timer as never); + return Promise.reject(error instanceof Error ? error : new Error(String(error))); + } + return promise; + } + + #respondOk(replyTo: string, payload: unknown): void { + try { + this.#write(stepResponse(replyTo, payload)); + } catch { + // A peer that has gone away cannot be told; the session is already failing closed. + } + } + + #respondError(replyTo: string, code: string, message: string): void { + try { + this.#write(stepErrorResponse(replyTo, code, message)); + } catch { + /* see #respondOk */ + } + } + + /** + * Negotiate the protocol and verify this route can actually keep tool ownership. + */ + async handshake(): Promise { + this.#handshake ??= this.#negotiate(); + return this.#handshake; + } + + async #negotiate(): Promise { + const response = await this.#send( + this.#nextId(), + "initialize", + { protocolRange: { min: STEP_PROTOCOL_VERSION, max: STEP_PROTOCOL_VERSION } }, + this.#options.handshakeTimeoutMs, + ); + const payload = (response.payload ?? {}) as Record; + const capabilities = Array.isArray(payload.capabilities) + ? payload.capabilities.filter((value): value is string => typeof value === "string") + : []; + const missing = REQUIRED_CAPABILITIES.filter(capability => !capabilities.includes(capability)); + if (missing.length > 0) { + throw new StepSessionError( + `This StepCode build does not advertise ${missing.join(", ")}, so it cannot keep tool ownership for a proxied turn.`, + "step_cli_capability_missing", + ); + } + return response; + } + + /** + * Open one query and return its ids. + * + * `hasPermissionCallback` is what disables StepCode's fail-closed default: without it an + * approval-requiring tool is blocked and the run terminated before this peer is ever consulted. + * `permissionMode` is sent explicitly for the same reason — the CLI otherwise starts in + * "Full Access (auto-resume)". + */ + async startQuery(options: { + model: string | undefined; + maxThinkingTokens: number | undefined; + sdkTools: readonly unknown[]; + streamingInput: boolean; + }): Promise<{ queryId: string; sessionId: string }> { + const response = await this.#send(this.#nextId(), "query.start", { + streamingInput: options.streamingInput, + options: { + ...(options.model ? { model: options.model } : {}), + ...(typeof options.maxThinkingTokens === "number" + ? { maxThinkingTokens: options.maxThinkingTokens } + : {}), + permissionMode: "default", + hasPermissionCallback: true, + includePartialMessages: true, + sdkTools: options.sdkTools, + }, + }); + const payload = (response.payload ?? {}) as Record; + if (typeof payload.sessionId === "string") this.#sessionId = payload.sessionId; + const queryId = typeof payload.queryId === "string" ? payload.queryId : undefined; + if (!queryId) throw new StepSessionError("query.start returned no queryId.", "step_cli_protocol_violation"); + return { queryId, sessionId: this.#sessionId ?? "" }; + } + + /** + * Queue one user message. + * + * Only text and images survive this hop, which is exactly why the session must outlive a request + * instead of being rebuilt from a replayed transcript. + */ + async sendInput(queryId: string, text: string): Promise { + await this.#send(this.#nextId(), "query.input", { + queryId, + message: { type: "user", message: { role: "user", content: [{ type: "text", text }] } }, + }); + } + + /** Answer a permission already checked against the owning turn and catalog. */ + allowPermission(frame: StepFrame): void { + this.#respondOk(frame.id, { behavior: "allow" }); + this.#releaseReverse(frame.id); + } + + /** + * Refuse a tool call with a reason the model can act on. + * + * A tool result frame carrying only `{message}` is not a refusal: StepCode reads `payload.content` + * and renders an absent content list as an EMPTY result, which the model reports as a tool that ran + * and produced nothing. Only an `error` envelope throws inside the SDK tool wrapper. + */ + refuseToolCall(frame: StepFrame, reason: string): void { + this.#respondError(frame.id, "TOOL_NOT_AVAILABLE", reason); + this.#releaseReverse(frame.id); + } + + #releaseReverse(id: string): void { + const held = this.#held.get(id); + if (held) { + held.answered = true; + this.#clearTimer(held.timer as never); + this.#held.delete(id); + } + } + + /** Refuse a `permission.request` with a reason the model can act on. */ + denyPermission(frame: StepFrame, reason: string): void { + this.#respondOk(frame.id, { message: reason }); + this.#releaseReverse(frame.id); + } + + /** + * Deliver a client-executed tool result to the call this session is holding open. + * + * Returns false when nothing is held for that frame — the runtime's own timer already fired, or + * the session was reaped — so the caller reports a too-slow tool instead of continuing against a + * call the model has already been told was denied. + */ + resolveHeldToolResult(frame: StepFrame, result: { content: readonly unknown[]; isError?: boolean }): boolean { + const held = this.#held.get(frame.id); + if (!held || held.answered || held.method !== "sdk_tool.invoke") return false; + held.answered = true; + this.#clearTimer(held.timer as never); + this.#held.delete(frame.id); + this.#respondOk(frame.id, { + content: result.content, + ...(result.isError === true ? { isError: true } : {}), + }); + this.#touch(); + return true; + } + + /** Reverse requests still waiting on this peer, in arrival order. */ + heldReverseRequests(): StepFrame[] { + return [...this.#held.values()].filter(entry => !entry.answered).map(entry => entry.frame); + } + + /** + * Close this query's input stream with `query.input_end`. + * + * Not optional housekeeping: StepCode's `#maybeFinish` refuses to finish a query whose input has + * not ended, so without this the runtime's single query slot is never released and the NEXT + * `query.start` on the same process fails with SESSION_BUSY. A multi-turn text conversation would + * therefore work for exactly one turn. + * + * Deliberately not sent when a tool call was captured: that query is still owed the client's tool + * result, and ending its input would let the runtime finish it before the model continues. + */ + async endInput(queryId: string): Promise { + if (this.#closed) return; + await this.#send(this.#nextId(), "query.input_end", { queryId }, this.#options.requestTimeoutMs); + } + + /** StepCode's `query.interrupt`, used when the client aborts a turn mid-flight. */ + async interrupt(queryId: string): Promise { + if (this.#closed) return; + await this.#send(this.#nextId(), "query.interrupt", { queryId }); + } + + #installIdleSweep(): void { + const interval = Math.max(1_000, Math.min(this.#options.idleTimeoutMs, 60_000)); + const sweep = (): void => { + if (this.#closed) return; + if (this.idleMs() >= this.#options.idleTimeoutMs) { + void this.close(); + return; + } + this.#idleTimer = this.#setTimer(sweep, interval); + }; + this.#idleTimer = this.#setTimer(sweep, interval); + } + + #stopIdleSweep(): void { + if (!this.#idleTimer) return; + this.#clearTimer(this.#idleTimer as never); + this.#idleTimer = undefined; + } + + closeBy(deadlineMs: number): void { + if (deadlineMs < this.#shutdownDeadlineMs && !this.#cleanupComplete) { + this.#shutdownDeadlineMs = deadlineMs; + clearTimeout(this.#shutdownTimer); + const delayMs = deadlineMs - SHUTDOWN_KILL_MARGIN_MS - Date.now(); + if (delayMs <= 0) this.#urgentCleanup.abort(); + else this.#shutdownTimer = setTimeout(() => this.#urgentCleanup.abort(), delayMs); + } + void this.close(); + } + + /** Start queued tree kills and signal any still-owned POSIX group before returning. */ + forceShutdown(): void { + this.#urgentCleanup.abort(); + const child = this.#child; + if (this.#platform === "win32" || child?.pid === undefined) return; + try { + this.#signalPosixGroup(child, child.pid, "SIGKILL"); + } catch (error) { + // If the group operation failed, the child handle can still stop the leader. + // Preserve the failure receipt because the descendants are unconfirmed. + if (this.#hasLiveLeader(child)) child.kill("SIGKILL"); + throw error; + } + } + + /** + * Reap the owned process tree before releasing this session. Concurrent callers share cleanup. + */ + close(code = 0): Promise { + if (this.#closePromise) return this.#closePromise; + this.#closed = true; + this.#stopIdleSweep(); + const child = this.#child; + this.#failAll(new StepSessionError(`StepCode session closed (${code}).`)); + for (const held of this.#held.values()) this.#clearTimer(held.timer as never); + this.#held.clear(); + // Publish the receipt before termination can emit close or notify pool bookkeeping. + const receipt = Promise.withResolvers(); + this.#closePromise = receipt.promise; + // Timer/protocol-initiated closes have no awaiting caller. Keep the rejection in the cached + // receipt for close()/pool shutdown, while observing it here to avoid an unhandled rejection. + void this.#closePromise.catch(() => {}); + const terminate = async (): Promise => { + if (child) await withCleanupSlot(() => this.#terminateWithRetry(child), this.#urgentCleanup.signal); + this.#cleanupComplete = true; + this.#announceExit(); + }; + void terminate().finally(() => clearTimeout(this.#shutdownTimer)).then(receipt.resolve, receipt.reject); + return this.#closePromise; + } + + async #terminateWithRetry(child: ChildProcess): Promise { + const failures: unknown[] = []; + const usesTaskkill = this.#platform === "win32" && child.pid !== undefined; + const recordWindowsOwnershipLoss = (): void => { + console.warn(WINDOWS_PID_UNCONFIRMED); + failures.push(new StepSessionError(WINDOWS_PID_UNCONFIRMED, "step_cli_cleanup_failed")); + }; + for (let attempt = 0; attempt < CLEANUP_ATTEMPTS; attempt++) { + if (usesTaskkill && !this.#hasLiveLeader(child)) { + recordWindowsOwnershipLoss(); + break; + } + try { await this.#terminate(child); return; } + catch (error) { + failures.push(error); + if (usesTaskkill && this.#windowsTreeKillAttempted) { + recordWindowsOwnershipLoss(); + break; + } + if (this.#posixGroupSignalState === "lost") break; + } + } + throw Object.assign(new StepSessionError( + "StepCode process cleanup failed; conversation handle is quarantined.", "step_cli_cleanup_failed", + ), { cause: new AggregateError(failures, "StepCode tree termination attempts failed.") }); + } + + async #terminate(child: ChildProcess): Promise { + if (this.#platform !== "win32" && child.pid !== undefined) { + await this.#terminatePosixGroup(child, child.pid); + } else { + await this.#terminateChild(child); + } + child.stdin?.destroy(); + child.stdout?.destroy(); + child.stderr?.destroy(); + child.unref?.(); + this.#child = undefined; + } + + #hasLiveLeader(child: ChildProcess): boolean { + return !this.#leaderExited && child.exitCode === null && child.signalCode === null; + } + + #signalPosixGroup(child: ChildProcess, pid: number, signal: "SIGTERM" | "SIGKILL"): void { + if (this.#posixGroupSignalState === "finished") return; + // The detached leader anchors the PGID only until exit. Check on every signal. + if (!this.#hasLiveLeader(child)) { + if (this.#posixGroupSignalState === "pending") { + this.#posixGroupSignalState = "lost"; + console.warn(POSIX_LEADER_EXITED); + } + throw new StepSessionError(POSIX_LEADER_EXITED, "step_cli_cleanup_failed"); + } + try { + process.kill(-pid, signal); + if (signal === "SIGKILL") this.#posixGroupSignalState = "finished"; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + this.#posixGroupSignalState = "finished"; + } + } + + async #terminatePosixGroup(child: ChildProcess, pid: number): Promise { + const escalateAt = performance.now() + this.#killGraceMs; + const deadline = escalateAt + KILL_CONFIRMATION_MS; + if (!this.#urgentCleanup.signal.aborted && this.#shutdownDeadlineMs - Date.now() > SHUTDOWN_KILL_MARGIN_MS) { + this.#signalPosixGroup(child, pid, "SIGTERM"); + while (this.#posixGroupSignalState === "pending" && this.#hasLiveLeader(child) && !this.#urgentCleanup.signal.aborted) { + const untilKill = Math.min(escalateAt - performance.now(), this.#shutdownDeadlineMs - Date.now() - SHUTDOWN_KILL_MARGIN_MS); + if (untilKill <= 0) break; + await Bun.sleep(Math.min(PROCESS_EXIT_POLL_MS, untilKill)); + } + } + this.#signalPosixGroup(child, pid, "SIGKILL"); + // Confirm the leader's exit using its child handle. The numeric PGID can be reused. + while (this.#hasLiveLeader(child)) { + const untilConfirm = Math.min(deadline - performance.now(), this.#shutdownDeadlineMs - Date.now()); + if (untilConfirm <= 0) { + throw new StepSessionError("StepCode process group cleanup could not be confirmed.", "step_cli_cleanup_failed"); + } + await Bun.sleep(Math.min(PROCESS_EXIT_POLL_MS, untilConfirm)); + } + } + + async #terminateChild(child: ChildProcess): Promise { + if ((child.exitCode !== null || child.signalCode !== null) + && child.pid === undefined) return; + let cancelWait = (): void => {}; + const exited = new Promise(resolve => { + const finish = (): void => { cancelWait(); resolve(); }; + child.once("close", finish); + cancelWait = () => child.removeListener("close", finish); + }); + let timer: ReturnType | undefined; + let deadline: ReturnType | undefined; + let failCleanup!: (error: unknown) => void; + const cleanupFailed = new Promise((_, reject) => { failCleanup = reject; }); + const gone = (): boolean => { + return !this.#hasLiveLeader(child) || (child.pid !== undefined && processIsGone(child.pid)); + }; + const signal = (kind: NodeJS.Signals): void => { + try { + child.kill(kind); + } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } + }; + try { + if (child.pid !== undefined) { + this.#windowsTreeKillAttempted = true; + try { + await (this.#deps.killWindowsProcessTree ?? killWindowsProcessTreeAsync)(child.pid); + } catch (error) { + // After a failed or timed-out taskkill, the wrapper may already have exited and Bun + // may have released its handle. Retry only when taskkill itself failed to start. + const failure = error instanceof Error ? error as NodeJS.ErrnoException : undefined; + if ((failure?.code === "ENOENT" || failure?.code === "EACCES") && failure.syscall?.startsWith("spawn ")) { + this.#windowsTreeKillAttempted = false; + } + throw error; + } + // Bun on Windows can retain null exit/signal fields after taskkill has reaped the tree. + // Check the OS only when Bun has not already observed the original wrapper's exit. + if (gone()) return; + } else { + signal("SIGTERM"); + timer = this.#setTimer(() => { + try { signal("SIGKILL"); } catch (error) { failCleanup(error); } + }, this.#killGraceMs); + } + await Promise.race([exited, cleanupFailed, new Promise((resolve, reject) => { + deadline = this.#setTimer(() => { + try { + if (gone()) resolve(); + else reject(new StepSessionError("StepCode process cleanup could not be confirmed.", "step_cli_cleanup_failed")); + } catch (error) { reject(error); } + }, this.#killGraceMs + KILL_CONFIRMATION_MS); + })]); + } finally { + if (timer !== undefined) this.#clearTimer(timer as never); + if (deadline !== undefined) this.#clearTimer(deadline as never); + cancelWait(); + } + } +} + +/** Resolve this route's binary, or explain how to install it. */ +export function resolveStepCliBinaryPath(which?: WhichFn): string { + const found = findStepCliBinary(STEP_CLI_PROFILE.binaryCandidates[0]!, which); + if (found) return found; + throw new StepSessionError( + `${STEP_CLI_PROFILE.label} is not installed. ${STEP_CLI_PROFILE.installHint}.`, + "step_cli_binary_missing", + ); +} + +/** Env and working directory for one session process. */ +export function stepCliProcessEnvironment(openCodexHome: string): { env: Record; cwd: string } { + const sessions = stepCliSessionDir(openCodexHome); + return { env: buildStepCliEnv(openCodexHome), cwd: dirname(sessions) }; +} + +export { buildStepCliEnv } from "./env"; +export type { StepCliProfile }; diff --git a/src/adapters/step-cli/stdio-frames.ts b/src/adapters/step-cli/stdio-frames.ts new file mode 100644 index 00000000000..eecd6e557b7 --- /dev/null +++ b/src/adapters/step-cli/stdio-frames.ts @@ -0,0 +1,330 @@ +/** + * Wire codec for the Step Agent SDK stdio protocol (`step --sdk-stdio`). + * + * The transport is deliberately separated from the session so both halves stay testable without a + * process: this module owns framing and envelope validation, `session.ts` owns the process, request + * correlation and reverse-request dispatch. + * + * Framing is a 4-byte big-endian length prefix followed by UTF-8 JSON. This is NOT the same protocol + * as `step --mode rpc`, which is newline-delimited JSONL — mixing the two is the single easiest way + * to build a host that writes frames nobody answers. + */ + +export const STEP_PROTOCOL_NAME = "step-agent-sdk" as const; +export const STEP_PROTOCOL_VERSION = 1 as const; +export const STEP_MAX_FRAME_BYTES = 8 * 1024 * 1024; +export const STEP_LENGTH_PREFIX_BYTES = 4; + +/** The runtime rejects a length prefix below this; a smaller value can never carry `{}`. */ +const STEP_MIN_FRAME_BYTES = 2; + +export type StepFrameKind = "request" | "response" | "event"; + +export interface StepProtocolErrorPayload { + readonly code: string; + readonly message: string; + readonly retryable?: boolean; + readonly details?: Record; +} + +export interface StepFrame { + readonly protocol: typeof STEP_PROTOCOL_NAME; + readonly version: number; + readonly kind: StepFrameKind; + readonly id: string; + readonly method?: string; + readonly replyTo?: string; + readonly sessionId?: string; + readonly turnId?: string; + readonly sequence?: number; + readonly payload?: unknown; + readonly error?: StepProtocolErrorPayload; +} + +export type StepProtocolViolationCode = + | "PROTOCOL_VIOLATION" + | "FRAME_TOO_LARGE" + | "FRAME_TOO_SMALL" + | "INCOMPLETE_FRAME" + | "INVALID_UTF8" + | "INVALID_JSON"; + +/** + * A framing or envelope failure the host must surface rather than swallow. + * + * The Step runtime answers a malformed frame with nothing at all, so a peer that keeps writing + * after a decode failure waits forever. Callers turn this into a terminal error and tear the session + * down instead of retrying into silence. + */ +export class StepProtocolViolation extends Error { + readonly code: StepProtocolViolationCode; + + constructor(message: string, code: StepProtocolViolationCode = "PROTOCOL_VIOLATION") { + super(message); + this.name = "StepProtocolViolation"; + this.code = code; + } +} + +const FRAME_KINDS: ReadonlySet = new Set(["request", "response", "event"]); + +/** + * Runtime envelope guard. + * + * Unknown protocol versions pass deliberately: the runtime negotiates `initialize.protocolRange`, + * so a newer peer has to be able to offer a range before this host learns what it speaks. + */ +export function isStepFrame(value: unknown): value is StepFrame { + if (value === null || typeof value !== "object" || Array.isArray(value)) return false; + const frame = value as Record; + if ( + frame.protocol !== STEP_PROTOCOL_NAME || + typeof frame.version !== "number" || + !Number.isSafeInteger(frame.version) || + frame.version < 1 || + typeof frame.kind !== "string" || + !FRAME_KINDS.has(frame.kind) || + typeof frame.id !== "string" || + frame.id.length === 0 + ) { + return false; + } + if (frame.kind === "request" || frame.kind === "event") { + if (typeof frame.method !== "string" || frame.method.trim().length === 0) return false; + return ( + frame.kind === "request" || + (typeof frame.sequence === "number" && + Number.isSafeInteger(frame.sequence) && + frame.sequence >= 0) + ); + } + if (typeof frame.replyTo !== "string" || frame.replyTo.trim().length === 0) return false; + if (frame.payload !== undefined && frame.error !== undefined) return false; + return frame.error === undefined || isStepProtocolErrorPayload(frame.error); +} + +function isStepProtocolErrorPayload(value: unknown): value is StepProtocolErrorPayload { + if (value === null || typeof value !== "object" || Array.isArray(value)) return false; + const error = value as Record; + return typeof error.code === "string" && typeof error.message === "string"; +} + +function assertMaxFrameBytes(value: number): void { + if (!Number.isSafeInteger(value) || value < 1 || value > STEP_MAX_FRAME_BYTES) { + throw new StepProtocolViolation("maxFrameBytes must be a positive bounded integer"); + } +} + +function assertEnvelope(frame: StepFrame): void { + // The ambiguous-response case is checked first so it keeps its own diagnostic: the generic guard + // below rejects it too, and reporting only that would send a caller looking for a malformed + // envelope instead of the contract violation they actually wrote. + if (frame.kind === "response" && frame.payload !== undefined && frame.error !== undefined) { + throw new StepProtocolViolation("response frame cannot contain both payload and error"); + } + if (!isStepFrame(frame)) { + throw new StepProtocolViolation("frame is not a valid Step protocol envelope"); + } +} + +/** Encode one frame as a 4-byte big-endian length prefix followed by UTF-8 JSON. */ +export function encodeStepFrame(frame: StepFrame, maxFrameBytes = STEP_MAX_FRAME_BYTES): Buffer { + assertMaxFrameBytes(maxFrameBytes); + assertEnvelope(frame); + + let json: string; + try { + json = JSON.stringify(frame); + } catch (error) { + throw new StepProtocolViolation( + `frame payload could not be serialized: ${error instanceof Error ? error.message : String(error)}`, + "INVALID_JSON", + ); + } + const payload = Buffer.from(json, "utf8"); + if (payload.byteLength > maxFrameBytes) { + throw new StepProtocolViolation( + `outgoing frame exceeds max frame size (${payload.byteLength} > ${maxFrameBytes} bytes)`, + "FRAME_TOO_LARGE", + ); + } + const result = Buffer.allocUnsafe(STEP_LENGTH_PREFIX_BYTES + payload.byteLength); + result.writeUInt32BE(payload.byteLength, 0); + payload.copy(result, STEP_LENGTH_PREFIX_BYTES); + return result; +} + +/** + * Incremental decoder for the peer side of the same protocol. + * + * Copies only the frame currently being assembled, so a caller may reuse or mutate the chunk it + * passed in once `push` returns. A length prefix that cannot be trusted throws immediately instead of + * allocating from an arbitrary 32-bit number. + */ +export class StepFrameDecoder { + readonly #maxFrameBytes: number; + readonly #prefix = Buffer.alloc(STEP_LENGTH_PREFIX_BYTES); + #prefixBytes = 0; + #payload: Buffer | undefined; + #payloadBytes = 0; + #expectedPayloadBytes: number | undefined; + #closed = false; + + constructor(options?: { readonly maxFrameBytes?: number } | number) { + const maxFrameBytes = typeof options === "number" ? options : options?.maxFrameBytes; + assertMaxFrameBytes(maxFrameBytes ?? STEP_MAX_FRAME_BYTES); + this.#maxFrameBytes = maxFrameBytes ?? STEP_MAX_FRAME_BYTES; + } + + get hasPendingInput(): boolean { + return this.#prefixBytes > 0 || this.#expectedPayloadBytes !== undefined; + } + + get closed(): boolean { + return this.#closed; + } + + push(chunk: Uint8Array): StepFrame[] { + if (this.#closed) throw new StepProtocolViolation("frame decoder is closed"); + if (!(chunk instanceof Uint8Array)) { + throw new StepProtocolViolation("frame decoder input must be a Uint8Array"); + } + + const frames: StepFrame[] = []; + let offset = 0; + while (offset < chunk.byteLength) { + if (this.#expectedPayloadBytes === undefined) { + while (this.#prefixBytes < STEP_LENGTH_PREFIX_BYTES && offset < chunk.byteLength) { + this.#prefix[this.#prefixBytes] = chunk[offset]; + this.#prefixBytes += 1; + offset += 1; + } + if (this.#prefixBytes < STEP_LENGTH_PREFIX_BYTES) break; + + const length = this.#prefix.readUInt32BE(0); + if (length < STEP_MIN_FRAME_BYTES) { + this.#resetCurrentFrame(); + // Its own message and code: reporting an undersized prefix as "exceeds max frame size" sends + // the operator looking at the ceiling when the real fault is a truncated or unframed stream. + throw new StepProtocolViolation( + `incoming frame is shorter than the smallest encodable frame (${length} < ${STEP_MIN_FRAME_BYTES} bytes)`, + "FRAME_TOO_SMALL", + ); + } + if (length > this.#maxFrameBytes) { + this.#resetCurrentFrame(); + throw new StepProtocolViolation( + `incoming frame exceeds max frame size (${length} > ${this.#maxFrameBytes} bytes)`, + "FRAME_TOO_LARGE", + ); + } + this.#expectedPayloadBytes = length; + this.#payload = Buffer.allocUnsafe(length); + this.#payloadBytes = 0; + } + + const remainingInput = chunk.byteLength - offset; + const remainingPayload = this.#expectedPayloadBytes - this.#payloadBytes; + const copied = Math.min(remainingInput, remainingPayload); + this.#payload!.set(chunk.subarray(offset, offset + copied), this.#payloadBytes); + this.#payloadBytes += copied; + offset += copied; + if (this.#payloadBytes < this.#expectedPayloadBytes) break; + + const payload = this.#payload!; + this.#resetCurrentFrame(); + frames.push(this.#decode(payload)); + } + return frames; + } + + /** Signal EOF. A trailing prefix or half-read payload is a protocol violation. */ + end(): void { + if (this.#closed) return; + if (this.hasPendingInput) { + const pending = this.#prefixBytes + this.#payloadBytes; + this.#resetCurrentFrame(); + this.#closed = true; + throw new StepProtocolViolation( + `stream ended with ${pending} trailing bytes of a partial frame`, + "INCOMPLETE_FRAME", + ); + } + this.#closed = true; + } + + #decode(payload: Buffer): StepFrame { + let text: string; + try { + text = new TextDecoder("utf-8", { fatal: true }).decode(payload); + } catch (error) { + throw new StepProtocolViolation( + `frame payload is not valid UTF-8: ${error instanceof Error ? error.message : String(error)}`, + "INVALID_UTF8", + ); + } + + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (error) { + throw new StepProtocolViolation( + `frame payload is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, + "INVALID_JSON", + ); + } + if (!isStepFrame(parsed)) { + throw new StepProtocolViolation("frame payload is not a valid protocol envelope"); + } + return parsed; + } + + #resetCurrentFrame(): void { + this.#prefixBytes = 0; + this.#payload = undefined; + this.#payloadBytes = 0; + this.#expectedPayloadBytes = undefined; + } +} + +/** Build a `request` envelope for a peer-initiated call. */ +export function stepRequest(id: string, method: string, payload?: unknown): StepFrame { + return { + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "request", + id, + method, + ...(payload === undefined ? {} : { payload }), + }; +} + +/** Build a `response` envelope answering the frame with `replyTo`. */ +export function stepResponse(replyTo: string, payload?: unknown, id?: string): StepFrame { + return { + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "response", + id: id ?? `r_${replyTo}`, + replyTo, + ...(payload === undefined ? {} : { payload }), + }; +} + +/** Build a `response` envelope carrying a protocol error instead of a payload. */ +export function stepErrorResponse( + replyTo: string, + code: string, + message: string, + retryable = false, + id?: string, +): StepFrame { + return { + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "response", + id: id ?? `r_${replyTo}`, + replyTo, + error: { code, message, retryable }, + }; +} diff --git a/src/adapters/step-cli/tool-bridge.ts b/src/adapters/step-cli/tool-bridge.ts new file mode 100644 index 00000000000..b48c66bd56e --- /dev/null +++ b/src/adapters/step-cli/tool-bridge.ts @@ -0,0 +1,92 @@ +import { buildCodingAgentToolCatalog, CodingAgentToolCatalogError } from "../coding-agent/tool-catalog"; +import type { OcxParsedRequest } from "../../types"; +import { STEP_CLI_TOOL_SERVER } from "./constants"; + +/** + * Namespace StepCode registers this proxy's tools under. + * + * Re-exported from `constants.ts` so the emitted wire names, the model-id projection and the tool + * bridge can never disagree about the prefix: two copies of "ocx" that drift apart would silently + * turn every captured call into an unresolvable name. + */ +export { STEP_CLI_TOOL_SERVER }; + +/** One declared SDK tool, exactly the descriptor shape `query.start.options.sdkTools` accepts. */ +export interface StepSdkToolDescriptor { + readonly serverName: string; + readonly toolName: string; + readonly description: string; + readonly inputSchema: Record; +} + +/** A tool call the client owns, recovered from a `${serverName}__${toolName}` wire name. */ +export interface StepCapturedToolCall { + /** Name the client originally declared, without the StepCode namespace prefix. */ + readonly wireName: string; + /** Call id the client uses when it reports the result on the next request. */ + readonly callId: string; + readonly input: Record; +} + +export class StepToolCatalogError extends Error { + constructor(message: string) { + super(message); + this.name = "StepToolCatalogError"; + } +} + +/** + * Project the client's tool catalog into StepCode's `sdkTools` option. + * + * The client's tool schemas travel inline, which is the whole reason this family needs no capture + * MCP server: StepCode registers each descriptor as a real tool on the session and calls the peer + * back over stdio. Limits, name validation and tool_choice filtering are reused from the shared + * coding-agent catalog builder so a route cannot accept a catalog the sibling CLI routes reject. + */ +export function buildStepSdkTools( + parsed: OcxParsedRequest, + serverName: string = STEP_CLI_TOOL_SERVER, +): { + sdkTools: StepSdkToolDescriptor[]; + /** `${serverName}__${toolName}` → the client's own tool name. */ + emittedNameMap: Map; + requireToolCall: boolean; +} { + let catalog: ReturnType; + try { + catalog = buildCodingAgentToolCatalog(parsed, serverName); + } catch (error) { + if (!(error instanceof CodingAgentToolCatalogError)) throw error; + throw new StepToolCatalogError(error.message); + } + const emittedNameMap = new Map(); + const sdkTools = catalog.tools.map(tool => { + const emittedName = `${serverName}__${tool.name}`; + emittedNameMap.set(emittedName, tool.name); + return { + serverName, + toolName: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + } satisfies StepSdkToolDescriptor; + }); + return { sdkTools, emittedNameMap, requireToolCall: catalog.requireToolCall }; +} + +/** + * Recover the client's tool name from a StepCode tool name. + * + * Returns undefined for anything this proxy did not declare — a StepCode built-in, a host MCP tool, + * or a malformed name. Callers must fail closed on undefined rather than forward the call, because a + * name that round-trips to nothing is a call the client can never satisfy. + */ +export function resolveStepToolName( + emittedName: string, + emittedNameMap: ReadonlyMap, +): string | undefined { + const direct = emittedNameMap.get(emittedName); + if (direct) return direct; + const separator = emittedName.indexOf("__"); + if (separator <= 0) return undefined; + return emittedNameMap.get(emittedName.slice(separator + 2)); +} diff --git a/src/lib/optional-shutdown-hooks.ts b/src/lib/optional-shutdown-hooks.ts index ba72e7a4129..69b5badfaa8 100644 --- a/src/lib/optional-shutdown-hooks.ts +++ b/src/lib/optional-shutdown-hooks.ts @@ -12,16 +12,19 @@ * A subsystem registers its teardown when it activates. A process that never activates it * registers nothing, so shutdown does no work and loads no module. * - * Hooks are synchronous and best-effort by contract: `drainAndShutdown` runs under an - * absolute deadline, so a hook that throws must not prevent its siblings — or - * `server.stop` — from running. + * Synchronous hooks are best-effort. Subsystems that own processes can register an + * asynchronous cleanup receipt with its own bounded wait after the active-turn drain. * * See devlog/_fin/260814_lab_core_decoupling/010_lifecycle_shutdown_registry.md */ +import { OPTIONAL_SHUTDOWN_GRACE_MS } from "./shutdown-budget"; + type ShutdownHook = () => void; +type AsyncShutdownHook = { run: (deadlineMs: number) => Promise; onIncomplete?: ShutdownHook }; const hooks = new Map(); +const asyncHooks = new Map(); let hooksRan = false; /** @@ -47,13 +50,24 @@ export function registerOptionalShutdownHook(key: string, hook: ShutdownHook): ( }; } +/** The async hook shares the absolute stop deadline. Its fallback must finish synchronously. */ +export function registerAsyncOptionalShutdownHook( + key: string, + run: AsyncShutdownHook["run"], + onIncomplete?: ShutdownHook, +): void { + asyncHooks.set(key, { run, onIncomplete }); +} + /** Whether `runOptionalShutdownHooks` has run at least once since the last test reset. */ export function didRunOptionalShutdownHooks(): boolean { return hooksRan; } -/** Run every registered teardown. Never throws. */ -export function runOptionalShutdownHooks(): void { +/** Run every teardown, reporting whether the asynchronous work completed successfully. */ +export async function runOptionalShutdownHooks( + { deadlineMs = Date.now() + OPTIONAL_SHUTDOWN_GRACE_MS }: { deadlineMs?: number } = {}, +): Promise { hooksRan = true; for (const [key, hook] of [...hooks]) { try { @@ -65,11 +79,47 @@ export function runOptionalShutdownHooks(): void { ); } } + if (asyncHooks.size === 0) return true; + const incomplete = new Map(asyncHooks); + let timer: ReturnType | undefined; + try { + const deadline = new Promise(resolve => { + const remainingMs = deadlineMs - Date.now(); + if (remainingMs <= 0) resolve(null); + else timer = setTimeout(() => resolve(null), remainingMs); + }); + const cleanup = Promise.all([...incomplete].map(async ([key, hook]) => { + try { + await hook.run(deadlineMs); + incomplete.delete(key); + return true; + } catch { + console.warn(`[shutdown] optional subsystem "${key}" teardown failed`); + return false; + } + })); + const results = await Promise.race([deadline, cleanup]); + if (results === null || Date.now() >= deadlineMs) { + console.warn("[shutdown] optional subsystem teardown timed out"); + return false; + } + return results.every(Boolean); + } finally { + clearTimeout(timer); + for (const [key, hook] of incomplete) { + try { + hook.onIncomplete?.(); + } catch { + console.warn(`[shutdown] optional subsystem "${key}" emergency teardown failed`); + } + } + } } /** Test-only reset so an isolated lifecycle test does not inherit registrations. */ export function resetOptionalShutdownHooksForTests(): void { hooks.clear(); + asyncHooks.clear(); drainStartHooks.clear(); drainStartHooksRan = false; hooksRan = false; diff --git a/src/lib/process-control.ts b/src/lib/process-control.ts index 79844643fbc..847bed3ff1c 100644 --- a/src/lib/process-control.ts +++ b/src/lib/process-control.ts @@ -4,6 +4,7 @@ import { loadConfig } from "../config"; import { readRuntimePort } from "../config/process-state"; import { directLocalHttpFetch } from "../server/direct-local-http"; import { configuredAdminToken } from "./admin-secrets"; +import { PROXY_STOP_EXIT_GRACE_MS } from "./shutdown-budget"; export function isProcessAlive(pid: number): boolean { try { @@ -350,9 +351,9 @@ async function stopProxyGracefullyDetailed( function drainDeadlineMs(): number { try { - return (loadConfig().shutdownTimeoutMs ?? 5000) + 3000; + return Math.max(0, loadConfig().shutdownTimeoutMs ?? 5000) + PROXY_STOP_EXIT_GRACE_MS; } catch { - return 8000; + return 5000 + PROXY_STOP_EXIT_GRACE_MS; } } diff --git a/src/lib/shutdown-budget.ts b/src/lib/shutdown-budget.ts new file mode 100644 index 00000000000..7a359db3e0a --- /dev/null +++ b/src/lib/shutdown-budget.ts @@ -0,0 +1,5 @@ +/** Extra time the stop controller gives the proxy after its configured turn drain. */ +export const PROXY_STOP_EXIT_GRACE_MS = 3_000; + +/** Leave one second of the controller's grace for listener teardown and process exit. */ +export const OPTIONAL_SHUTDOWN_GRACE_MS = PROXY_STOP_EXIT_GRACE_MS - 1_000; diff --git a/src/providers/registry/entries-extended.ts b/src/providers/registry/entries-extended.ts index 9ce1220db0e..b3d758e6fe6 100644 --- a/src/providers/registry/entries-extended.ts +++ b/src/providers/registry/entries-extended.ts @@ -112,6 +112,10 @@ import { OPPER_MODEL_CONTEXT_WINDOWS, OPPER_MODEL_MAX_OUTPUT_TOKENS, OPPER_MODEL_INPUT_MODALITIES, + STEP_CLI_MODELS, + STEP_CLI_MODEL_CONTEXT_WINDOWS, + STEP_CLI_NO_VISION_MODELS, + STEP_CLI_REASONING_EFFORTS, AISTUPIDLEVEL_ROUTING_MODES, AISTUPIDLEVEL_MODEL_CONTEXT_WINDOWS, AISTUPIDLEVEL_MODEL_MAX_OUTPUT_TOKENS, @@ -1742,6 +1746,40 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ reasoningEfforts: STEPFUN_REASONING_EFFORTS, note: "StepFun (阶跃星辰) official OpenAI-compatible API.", }, + { + // StepCode (阶跃星辰) CLI as the transport for a Step Plan subscription (§三十一). The CLI owns the + // account: this row stores no Step token, reads none and injects none, so the only credential in + // play is the operator's own `step login`, which the CLI resolves itself. + // + // GOVERNANCE: routing a Step Plan subscription through a third-party agent harness is Step + // 星辰's call, not OpenCodex's — flagged for maintainer review alongside the CodeBuddy and Claude + // Code rows above. The Step Plan terms document `step_plan` endpoints for third-party coding + // tools, and `--sdk-stdio` is StepCode's own published, MIT-licensed external-client surface; that + // is the strongest authorization evidence available without a written permission, and it is not + // the same thing as one. + id: "step-cli", + label: "StepCode CLI (subscription)", + adapter: "step-cli", + // The destination the subscription's traffic reaches. OpenCodex never sends this host: the CLI + // performs every request, so the value exists so the adapter can fail closed when a row is + // repointed somewhere this route cannot speak to. + baseUrl: "https://api.stepfun.com/step_plan", + // `key` + `keyOptional` for the same reason as `claude-cli`: the traffic leaves the machine, so + // `local` would misreport the row, but the route is keyless, which is what `keyOptional` states. + authKind: "key", + keyOptional: true, + dashboardUrl: "https://platform.stepfun.com/docs/zh/step-plan/quick-start", + defaultModel: "step-5-preview", + models: [...STEP_CLI_MODELS], + // Static roster, exactly like the Claude Code and CodeBuddy rows. The CLI serves its catalog over + // the SDK stdio protocol rather than at an HTTP path the adapter polls, and a live-discovery + // attempt against this row would 404 and then fall back to these ids anyway. + liveModels: false, + modelContextWindows: { ...STEP_CLI_MODEL_CONTEXT_WINDOWS }, + noVisionModels: [...STEP_CLI_NO_VISION_MODELS], + reasoningEfforts: [...STEP_CLI_REASONING_EFFORTS], + note: "Runs Step Plan subscription traffic through StepCode's own harness: the official `step` CLI over its length-prefixed SDK stdio protocol, one long-lived process per conversation. OpenCodex stores no Step token, reads none and injects none — the CLI signs in with `step login` and bills the Step Plan account itself. The sign-in is the one of the user this proxy runs as, so every request served through this row spends that same account. Tool ownership stays with the client: the adapter declares the request's tools as StepCode SDK tools and lets the CLI call back over stdio, so no tool ever executes inside Step and approval never leaves the client. Requires the StepCode CLI (`~/.stepcode/bin/step`) and a signed-in Step Plan session. This route shares the CLI family's 128-tool / 2 MiB catalog ceiling, which a real Codex client can exceed because it flattens every MCP server's tools into the function catalog (measured on Codex 0.162.0: 1749 tools, 2.5 MB); the refusal names both counts so the cause is visible, and the fix is to disable or narrow MCP servers for this provider. LIMITATIONS: StepCode carries conversation history only inside its own process, so one conversation needs one process and a process that dies cannot be reconstructed; a tool that takes longer than two minutes to come back exceeds the CLI's own tool-result window; and the CLI's session system prompt cannot be replaced, so a client instruction is prepended to the turn rather than installed as the system prompt. Routing authorization flagged for maintainer security review.", + }, { // Official Claude Code CLI as the transport for a Claude subscription (§三十一). The CLI owns // the account: this row stores no token and the adapter reads and injects none, so the request diff --git a/src/providers/registry/model-seeds.ts b/src/providers/registry/model-seeds.ts index b0124f06bc4..bd7b03d91ce 100644 --- a/src/providers/registry/model-seeds.ts +++ b/src/providers/registry/model-seeds.ts @@ -1221,6 +1221,48 @@ export const OPPER_MODEL_INPUT_MODALITIES: Record = Object.fro OPPER_MODELS.map(id => [id, OPPER_TEXT_ONLY_MODELS.includes(id) ? ["text"] : ["text", "image"]]), ); +/** + * Step Plan catalog as the StepCode CLI serves it (`GET {step_plan}/v1/models`, 2026-10-17). + * + * Verified against a signed-in `step_plan` login, including `max_input_tokens` and the per-model + * `reasoning_effort_support_list`. The four `stepaudio-*` entries the same endpoint returns are + * deliberately absent: they are speech models, they hold no chat tools, and a row that routes a text + * turn into them answers `model_invalid`. `liveModels` stays false on the registry row for the same + * reason Claude Code's row does — the CLI, not the adapter's own HTTP path, owns discovery. + */ +export const STEP_CLI_MODELS = [ + "step-5-preview", + "step-3.7-flash", + "step-3.5-flash", + "step-3.5-flash-2603", + "step-router-v1", +]; + +export const STEP_CLI_MODEL_CONTEXT_WINDOWS: Record = { + "step-5-preview": 1_024_000, + "step-3.7-flash": 262_144, + "step-3.5-flash": 262_144, + "step-3.5-flash-2603": 262_144, + "step-router-v1": 262_144, +}; + +/** + * Every published model is text-only for this route. + * + * `step-5-preview` and `step-3.7-flash` do accept images upstream, but nothing verifies that a + * headless StepCode turn hands those bytes to the model, and the adapter refuses image input for the + * same reason the Qoder and Claude Code rows do. Advertising a modality the route cannot honour makes + * route selection pick this row for a picture it then answers blind; the vision sidecar still + * captions images into text before they arrive. + */ +export const STEP_CLI_NO_VISION_MODELS = [...STEP_CLI_MODELS]; + +/** + * The three档 Step advertises. `xhigh` and `max` are not advertised and must not be offered: the + * service maps them onto `high` server-side, so publishing them would let the client believe it chose + * a depth it did not. + */ +export const STEP_CLI_REASONING_EFFORTS = ["low", "medium", "high"]; // AI Stupid Level routing modes, as listed by the authenticated GET /v1/models on 2026-10-26 // (https://aistupidlevel.info/router/docs#strategies). Each mode picks a model per request, so it // declares conservative limits that hold for any pick: a 262,144-token window (the pool's smallest, diff --git a/src/server/lifecycle.ts b/src/server/lifecycle.ts index 03313433768..ad81301ee93 100644 --- a/src/server/lifecycle.ts +++ b/src/server/lifecycle.ts @@ -9,6 +9,7 @@ import { import { abortRestoreTrashJobAsync } from "../storage/restore-job"; import { stopStorageCleanupScheduler } from "../storage/policy-scheduler"; import { runDrainStartHooks, runOptionalShutdownHooks } from "../lib/optional-shutdown-hooks"; +import { OPTIONAL_SHUTDOWN_GRACE_MS } from "../lib/shutdown-budget"; import { stopStateStoreSweeper } from "../lib/state-store-sweeper"; import { cancelQueuedStorageWorkerSpawns, @@ -575,7 +576,7 @@ export async function drainAndShutdown( // Optional subsystems (Compatibility Lab today, anything added later) tear themselves // down through hooks registered at activation. A process that never activated one runs // nothing here and never loads its module graph. - runOptionalShutdownHooks(); + if (!(await runOptionalShutdownHooks({ deadlineMs: deadline + OPTIONAL_SHUTDOWN_GRACE_MS }))) shutdownSucceeded = false; stopStateStoreSweeper(); // The overlay reconciler is owner-scoped: the startServer stop override // releases THIS server's lease through runListenerShutdown → diff --git a/structure/INDEX.md b/structure/INDEX.md index 13bc11f1582..878c2ed9622 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -102,6 +102,7 @@ Per-vendor contracts and the adapter authority that constructs them. | [`providers/antigravity-account-import.md`](providers/antigravity-account-import.md) | Cockpit Tools import schema, identity check, probe-gated project_id fallback and no-write failure paths. | | [`providers/claude-cli-replay.md`](providers/claude-cli-replay.md) | Claude CLI stable replay, canonical tool schemas, capture-only client tool ownership and subscription usage admission. | | [`providers-and-adapters.md`](providers-and-adapters.md) | Provider and adapter selection, the adapter inventory, live model discovery, and the hosted-search continuation bridge. | +| [`providers/step-cli-transport.md`](providers/step-cli-transport.md) | StepCode as a Step Plan transport: its own framed stdio wire, one process per conversation, inline SDK tools instead of an MCP catalog, and the bounded tool-result window. | | [`providers/opengateway.md`](providers/opengateway.md) | Preset discovery, paired Responses tool-result projection and bounded empty-completion recovery. | | [`providers/jev-decision.md`](providers/jev-decision.md) | JEV Combo decision methods (TypeSafe, self-hosted System One rows, opencodex models), the decision request path, dashboard surfaces, and the content-free statistics projection. | | [`providers/anthropic-output-caps.md`](providers/anthropic-output-caps.md) | Routed omitted-output caps for adapter:anthropic rows keyed by Claude model id, precedence and unknown-id fallback. | @@ -253,6 +254,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/adapters/openai-responses/request-strips.ts` | [`transports/responses-citations.md`](transports/responses-citations.md) | | `src/adapters/openai-responses/tool-schema.ts` | [`providers/hosted-tool-denials.md`](providers/hosted-tool-denials.md) | | `src/adapters/openai-responses/transport.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | +| `src/adapters/step-cli/` | [`providers/step-cli-transport.md`](providers/step-cli-transport.md) | | `src/adapters/unique-tool-call-ids.ts` | [`providers/completed-tool-blocks.md`](providers/completed-tool-blocks.md) | | `src/adapters/workbuddy-schema.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | | `src/adapters/workbuddy.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | diff --git a/structure/manifest.json b/structure/manifest.json index 3eb8e0783e3..2149bcad254 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -727,6 +727,15 @@ "src/web-search/" ] }, + { + "path": "providers/step-cli-transport.md", + "tier": 4, + "title": "StepCode CLI Transport", + "scope": "StepCode as a Step Plan transport: its own framed stdio wire, one process per conversation, inline SDK tools instead of an MCP catalog, and the bounded tool-result window.", + "documents": [ + "src/adapters/step-cli/" + ] + }, { "path": "providers/opengateway.md", "tier": 4, diff --git a/structure/ops/docs-and-release.md b/structure/ops/docs-and-release.md index f5d7bae0fc6..2cd82aaf9cb 100644 --- a/structure/ops/docs-and-release.md +++ b/structure/ops/docs-and-release.md @@ -86,7 +86,7 @@ Manual navigation is defined in `docs-site/astro.config.mjs`. When adding a publ sidebar and either add localized copies or intentionally accept Starlight fallback behavior. Use slugs for local pages, including Platform Support and OS Keychain, so navigation preserves the selected locale. `tests/ci-workflows/docs-spanish-localization.test.ts` guards canonical Spanish coverage, literal provider-key references, protected remote examples, foreground quickstart alternatives, separate-terminal and Bash/stdin pairing recipes, Pi reasoning metadata, and the data/management credential and admission-header distinctions across shipped locale copies, including empty-header bearer fallback. `tests/ci-workflows/docs-remote-hub-claims.test.ts` validates Docker initialization against the image seed and configuration schema; `tests/ci-workflows/docs-bun-source-requirement.test.ts` checks current bundle claims against the package pin. Provider preset totals are recounted from the current registry when a preset lands. The -documented split is 111 total: 89 key-based, 18 OAuth, three local, and one default +documented split is 112 total: 90 key-based, 18 OAuth, three local, and one default ChatGPT-forward preset. The English and Spanish API-key catalog pages, every other locale's provider guide, and every locale's quickstart carry the same counts. Section 3 of the provider guide lives on its own page, `docs-site/src/content/docs/guides/api-key-catalog.md` (with its Spanish copy), so the guide stays under the file-size ratchet's 2,000-line default; the guide keeps a section 3 stub that links every moved heading anchor, and other locales keep section 3 in their provider guide until they add a translated catalog page. diff --git a/structure/ops/service-and-sidecars.md b/structure/ops/service-and-sidecars.md index 1fc6fef677b..49df8a9834b 100644 --- a/structure/ops/service-and-sidecars.md +++ b/structure/ops/service-and-sidecars.md @@ -515,7 +515,7 @@ endpoint can never restart. Focused coverage is `tests/update/update-stop-classi ## Restart handoff -Ordinary signal shutdown passes the CLI's idempotent exit cleanup to `drainAndShutdown` in `src/server/lifecycle.ts`: its drain-finally block calls the synchronous-only `() => undefined` hook before listener stop. Promise-returning hooks are outside this contract; there is no asynchronous cleanup wait. Listener stop and startup-lifecycle release still run if cleanup throws. Restart callers omit that hook and retain their existing routing-preservation decisions; receipt-backed stop deferral remains owned by the stopping client. After verifying a matching receipt, `performStopTeardown` records a dedicated process-lifetime exit deferral; exit cleanup consults it before restoring native Codex/Grok, including when the API's own drain ends in `process.exit`. A query flag or connected-client capability does not set it. API and signal restoration repeat the [connection ownership guard at each write](../runtime.md#remote-hub-hardening-ownership); an unproven API boundary returns 409 before scheduling shutdown, and signal cleanup reports failure while preserving shared configuration. `tests/fixtures/api-stop-exit-runner.ts`, exercised by `tests/service/stop-deferred-teardown.test.ts`, runs the actual API handler, listener drain and process-exit cleanup in one child. `tests/service/shutdown-drain.test.ts` covers the hook with a real loopback listener and the CLI signal handler. +Ordinary signal shutdown passes the CLI's idempotent exit cleanup to `drainAndShutdown` in `src/server/lifecycle.ts`: its drain-finally block calls the synchronous-only `() => undefined` hook before listener stop. Asynchronous subsystem receipts use the [bounded optional shutdown join](../runtime.md#lifecycle) earlier in the drain. Listener stop and startup-lifecycle release still run if cleanup throws. Restart callers omit that hook and retain their existing routing-preservation decisions; receipt-backed stop deferral remains owned by the stopping client. After verifying a matching receipt, `performStopTeardown` records a dedicated process-lifetime exit deferral; exit cleanup consults it before restoring native Codex/Grok, including when the API's own drain ends in `process.exit`. A query flag or connected-client capability does not set it. API and signal restoration repeat the [connection ownership guard at each write](../runtime.md#remote-hub-hardening-ownership); an unproven API boundary returns 409 before scheduling shutdown, and signal cleanup reports failure while preserving shared configuration. `tests/fixtures/api-stop-exit-runner.ts`, exercised by `tests/service/stop-deferred-teardown.test.ts`, runs the actual API handler, listener drain and process-exit cleanup in one child. `tests/service/shutdown-drain.test.ts` covers the hook with a real loopback listener and the CLI signal handler. During drain, `src/server/index.ts` rejects new data-plane work with HTTP 503 and `src/service/linux-linger.ts` observes boot lingering without changing it; enabled, disabled and unknown states receive distinct install advice. Desktop startup distinguishes enabled next-login registration from current loaded state, preserving identity/disabled/supervisor checks. `src/cli/hub-disable.ts` changes persisted hub settings only, prints Desktop/service/manual restart guidance and reminds the operator to review external publishing to old ports. an explicit JSON envelope: `error.type` is `server_error`, `error.code` is diff --git a/structure/providers-and-adapters.md b/structure/providers-and-adapters.md index f8da4c6f5bb..dfeb5e64571 100644 --- a/structure/providers-and-adapters.md +++ b/structure/providers-and-adapters.md @@ -69,7 +69,7 @@ shared Kiro/Chat splitting and raw display follow [Chat compatibility](providers Meta Muse import, device login, explicit paste recovery, consent and safe diagnostics follow the [Muse login contract](providers/meta-muse.md). Other providers retain their existing login policies. -The capture-only bridge in `src/adapters/coding-agent/turn.ts` reports staging failures with +Claude CLI, Qoder and CodeBuddy use the synchronous Windows `taskkill /T /F` helper in `src/adapters/coding-agent/process-tree.ts`. [StepCode](providers/step-cli-transport.md) uses the asynchronous helper there. Both bound each invocation to five seconds. The capture-only bridge in `src/adapters/coding-agent/turn.ts` reports staging failures with the fixed `tool_bridge_setup_failed` error, never an OS error carrying private file paths. Failure prevents CLI spawn and settles the bridge's private directory; the CodeBuddy adapter also settles its prompt-file directory. Catalog and MCP-config write failures cover both owners. @@ -80,7 +80,7 @@ name/namespace components and wire names over 512 UTF-8 bytes before staging. It 256 KiB per serialized definition, and 2 MiB for the serialized array (including brackets and separators); the comma-joined `--allowed-tools` argument is separately capped at 8 KiB of UTF-8, counting full `mcp____` names and commas. Invalid catalogs return a fixed local 400 without spawning Qoder. Valid wire identities, order and schemas are unchanged, apart from the Responses-only encrypted marker stripped during projection. Duplicate and ambiguous wire identities remain the Responses parser's responsibility. Qoder Global/CN accept exact selected wire-name aliases in complete and partial frames; new partial aliases require `profile.family === "qoder"` and `acceptWireToolNames`. Repeated call IDs compare selected wire identities across complete/partial spellings, while changed tools or inputs still fail closed. The Qoder adapter refuses cross-tool wire/MCP name collisions with `tool_catalog_invalid` before spawn; individually selected tools remain valid, and MCP allowlists and Claude CLI/CodeBuddy behavior stay unchanged. Qoder appends the -folded system prompt through its documented scoped `QODER_APPEND_SYSTEM_PROMPT` or `QODERCN_APPEND_SYSTEM_PROMPT` child environment, never through command-line arguments or inherited vendor variables. `src/adapters/qoder/adapter.ts` sets the region's usage switch (`QODER_EXPOSE_TOKEN_USAGE` or `QODERCN_EXPOSE_TOKEN_USAGE`; each CLI build reads only its own prefix) to `true` only in Qoder's child environment, so the shared usage parser receives the CLI's token counts instead of zeros. Executable discovery lives in `src/adapters/coding-agent/profile.ts`. On Windows a PATH directory's same-stem `.exe` beats its `.cmd`, while PATH order still decides between directories. Across a profile's own candidate names the first native hit wins over an earlier batch dispatcher, so the official Qoder CN layout (`qodercn.cmd` forwarding through PowerShell, `qoderclicn.exe` beside it on PATH) launches the executable. Only native hits are cached; a dispatcher-only result is resolved again on the next turn. When a turn must still launch a `.cmd`/`.bat` and its arguments carry an empty value (`--tools ""`, `--setting-sources ""`), `src/adapters/coding-agent/batch-dispatcher.ts` reads the dispatcher, and `turn.ts` refuses with `cli_dispatcher_drops_empty_args` before spawn unless the whole chain is verified: every file read completely within 64 KiB, every hop to another batch file resolved to a literal `%~dp0` or absolute path and inspected in turn (at most four files), and no file forwarding through `powershell`/`pwsh`. A hop through a variable, an oversized or unreadable file, or a deeper chain is refused. A dispatcher that forwards `%*` directly, such as an npm cmd-shim, keeps launching through cmd.exe. `tests/windows/coding-agent-native-empty-argv.test.ts` proves both paths with a native receiver on Windows. Qoder's assistant-text replay guard is recorded in [clients/qoder.md](clients/qoder.md#qoder-assistant-text-replay-guard). +folded system prompt through its documented scoped `QODER_APPEND_SYSTEM_PROMPT` or `QODERCN_APPEND_SYSTEM_PROMPT` child environment, never through command-line arguments or inherited vendor variables. `src/adapters/qoder/adapter.ts` sets the region's usage switch (`QODER_EXPOSE_TOKEN_USAGE` or `QODERCN_EXPOSE_TOKEN_USAGE`; each CLI build reads only its own prefix) to `true` only in Qoder's child environment, so the shared usage parser receives the CLI's token counts instead of zeros. Executable discovery lives in `src/adapters/coding-agent/profile.ts`. On Windows a PATH directory's same-stem `.exe` beats its `.cmd`, while PATH order still decides between directories. Across a profile's own candidate names the first native hit wins over an earlier batch dispatcher, so the official Qoder CN layout (`qodercn.cmd` forwarding through PowerShell, `qoderclicn.exe` beside it on PATH) launches the executable. Only native hits are cached; a dispatcher-only result is resolved again on the next turn. When a turn must still launch a `.cmd`/`.bat` and its arguments carry an empty value (`--tools ""`, `--setting-sources ""`), `src/adapters/coding-agent/batch-dispatcher.ts` reads the dispatcher, and `turn.ts` refuses with `cli_dispatcher_drops_empty_args` before spawn unless the whole chain is verified: every file read completely within 64 KiB, every hop to another batch file resolved to a literal `%~dp0` or absolute path and inspected in turn (at most four files), and no file forwarding through `powershell`/`pwsh`. A hop through a variable, an oversized or unreadable file, or a deeper chain is refused. A dispatcher that forwards `%*` directly, such as an npm cmd-shim, keeps launching through cmd.exe. `tests/windows/coding-agent-native-empty-argv.test.ts` proves both paths with a native receiver on Windows. Qoder's assistant-text replay guard is recorded in [clients/qoder.md](clients/qoder.md#qoder-assistant-text-replay-guard). StepCode (阶跃星辰) as a Step Plan transport, its own framed wire, one process per conversation, inline SDK tools in place of the capture-only MCP catalog, and the bounded tool-result window, follow [StepCode CLI transport](providers/step-cli-transport.md). Coding-agent stdout is framed as bounded JSONL directly from decoded stream segments. The framer tracks the current line's UTF-8 byte count incrementally, searches each decoded segment once, and diff --git a/structure/providers/step-cli-transport.md b/structure/providers/step-cli-transport.md new file mode 100644 index 00000000000..25d6a0e0a87 --- /dev/null +++ b/structure/providers/step-cli-transport.md @@ -0,0 +1,176 @@ +# StepCode CLI Transport + +`src/adapters/step-cli/` runs StepCode's own harness as a Step Plan transport. It shares the profile +discovery, the scoped child environment and the client tool-catalog limits with the other CLI +families, and differs from them in four contract decisions. + +## Its own wire + +`src/adapters/step-cli/stdio-frames.ts` implements StepCode's `step-agent-sdk` envelope: a 4-byte +big-endian length prefix, UTF-8 JSON, an 8 MiB frame ceiling and a `{protocol, version, kind, id, +method | replyTo, sequence, payload | error}` envelope. This is **not** `step --mode rpc`, which is +newline-delimited JSONL; a peer that mixes the two is answered with silence. Unknown protocol +versions pass the envelope guard so `initialize.protocolRange` can negotiate rather than being +rejected before the peer has had a chance to offer a range. + +## One process per conversation + +`query.input` reduces every message to text and images, so an assistant turn, a declared tool call +and its result cannot be replayed through the wire: StepCode's conversation context lives only inside +its own process. `conversation.ts` namespaces thread/affinity handles by the server's admitted +`_reasoningReplayScope.clientPrincipalId` and physical provider identity. Headers and `providerState` +cannot supply that authority. Requests without an admitted principal receive a private process that +closes when the request ends; they cannot continue a held call across requests. A process that dies +is reported rather than restarted — a restart +would lose tool results the client already delivered, which this route cannot replay from a +transcript. + +Events name the active turn's exact `queryId`. SDK reverse callbacks name the owning `sessionId` +and carry a request ID allocated after the active query ID by the host's shared counter. If a +callback also carries a query ID, it must match. Permissions require an owning turn and a tool in +that query's declared catalog. Other permissions are denied. A +`sdk_tool.invoke` is answered on the client's **next** request, with the original query and catalog. +Changing the catalog while returning a held result closes the session. Abandoning a held call +detaches its owner, interrupts it and confirms its input end before registering a replacement turn. +After acquiring the conversation lock, a cancelled turn leaves held state untouched. Cancellation +also stops new query starts, busy retries and input that has yet to be sent. + +Child response errors are classified at the transport boundary. The adapter emits locally defined +error codes and messages for login failures, subscription limits, busy queries, timeouts and +permission denials. + +`session-pool.ts` latches shutdown before awaiting sessions and in-flight opens. The pool owns +each session before workspace setup, so shutdown can close an opening session before it spawns. +The pool retains ownership of adapter, idle-timer and sweep closes until termination is +confirmed. Shutdown drains those receipts and propagates failures. +Closing handles refuse replacement. Session close is idempotent and clears held-request timers. +Termination gets at most two attempts. An exhausted retry budget or loss of process ownership +permanently quarantines the handle in the pool and preserves the errors as the cleanup failure's +cause. Repeated closes return that failure without restarting the retry budget. The normal cleanup +queue runs up to four sessions concurrently across pools, including idle and late-opening sessions. +POSIX cleanup sends TERM to the detached +group and escalates to KILL after the grace period. It signals the group only while the original +leader is observed alive. A successful KILL or an ESRCH from signalling ends group signalling. +Cleanup then waits for the original leader's exit through its child handle. If the leader exits before either outcome, +cleanup quarantines the session and logs `StepCode POSIX process cleanup is incomplete because the process group leader exited before group termination.` +Descendants that outlive their leader cannot be safely signalled once the PGID can be reused. + +Bun 1.4.4 can reap the child before JavaScript receives the exit event. On Linux, the native +waiter thread is a fallback when pidfd monitoring is unavailable. Between reap and exit +notification, a group signal could reach a reused PGID. Bun exposes no `pidfd` or other +syscall-level ownership handle to JavaScript. Closing this window requires a native supervisor +or a Bun change. The owner accepted this residual risk on 2026-11-19. + +On Windows, StepCode checks that the original wrapper is still alive before launching the asynchronous +helper in `src/adapters/coding-agent/process-tree.ts` (`taskkill /T /F`, up to five seconds per +attempt). The helper resolves the numeric PID after launch. If the wrapper exits and Windows reuses its PID +between the liveness check and that lookup, the signal could reach an unrelated process tree. +Closing this window requires establishing ownership at launch, for example with a kill-on-close +Job Object, and terminating through that handle. The owner accepted this residual risk on +2026-11-19 alongside the POSIX reap-ordering risk. + +Cleanup can retry a confirmed helper launch failure while the wrapper still appears alive. +If the wrapper has already exited or cleanup is unconfirmed after the helper may have run, the +session is quarantined and cleanup logs the fixed Windows warning. A successful tree-kill +receipt allows an OS liveness check if Bun still reports null exit fields. +Explicit registry clears await every pool and retain failed pools, so clearing state cannot bypass +quarantine. Graceful proxy shutdown passes the absolute [proxy stop deadline](../runtime.md#lifecycle) +through the registry and pool, including to sessions already closing. POSIX TERM grace is capped +at two seconds and ends at least 250 ms before the deadline when that time is available. At that +margin, queued sessions bypass the four slots and proceed directly to group KILL or Windows +tree kill. The hook reports incomplete confirmation as a shutdown failure. Before returning +an incomplete receipt, it runs a final synchronous KILL sweep of pending POSIX groups whose original +leaders are still observed alive and starts any Windows tree kills still in the queue. +If the group operation fails, the sweep can still signal the leader through its child handle +and reports the tree cleanup as incomplete. + +## Tools arrive as inline SDK tools, not an MCP catalog + +The client's catalog is projected into `query.start.options.sdkTools` (`tool-bridge.ts`), each +registered by StepCode as `${serverName}__${toolName}` under the `ocx` namespace. A call comes back as +a `sdk_tool.invoke` reverse request, which the adapter captures and **holds unanswered**: it emits the +client's `tool_call` events and ends the turn with `stopReason: "tool_use"`. Nothing is invented in +between — the client executes the tool, reports it on its next request, and that report is what +releases the held reverse request into the query the model is already running. No MCP server is +staged and no tool executes inside StepCode, so approval never leaves the client. + +**Bounded tool-result window.** StepCode's `SDK_TOOL_TIMEOUT_MS` is 120s and answering late produces a +`permission_denied` message inside the model's context rather than a transport error. The hold timer is +deliberately shorter and reports `step_cli_tool_result_too_late` instead of resuming a call the model +believes was denied. + +## No credential, and a fail-closed capability check + +Executable discovery resolves PATH hits against the proxy's working directory before spawning. +The session creates its isolated working directory before starting StepCode and reports a +workspace error if creation fails. + +The CLI resolves its own `step login`, so the child environment adds only `USER` (StepCode resolves its +sign-in by account name) and a redirected `STEP_CODING_AGENT_SESSION_DIR`. The operator's config +directory stays where StepCode put it: copying `auth.json` into `~/.opencodex` would put a second copy +of a live subscription token on disk and give this adapter a secret to redact. Host MCP servers in that +config may still initialize, which is what `--no-tools` makes unreachable. `permissionMode` and +`hasPermissionCallback` are always sent explicitly — the CLI otherwise starts in "Full Access +(auto-resume)" — and `handshake()` rejects a runtime that does not advertise `sdk-tools`, because such a +runtime answers text only while looking healthy and a routed coding session would silently degrade +into a chat. + +## Module layout + +`src/adapters/step-cli/` is one dependency-ordered layer per concern, so a reader looking for one +question does not have to read the whole route: + +| Module | Owns | +|---|---| +| `adapter.ts` | orchestration only — what one turn is, in what order, when it is terminal | +| `conversation.ts` | conversation identity (which thread owns which process) and turn ordering | +| `events.ts` | what the CLI says and what this peer owes it back | +| `projection.ts` | pure request/response conversions, testable without a session | +| `registry.ts` | state that must outlive a request, plus shutdown wiring | +| `errors.ts` | failure text and the status a client can retry on | +| `session.ts` / `session-pool.ts` / `stdio-frames.ts` | the framed transport itself | +| `env.ts` / `profiles.ts` / `constants.ts` | the scoped child environment, binary discovery and shared identifiers | + +The graph is one-way: `adapter` → {`conversation`, `events`, `projection`, `registry`, `errors`}, +`events` → {`projection`, `registry`}, and nothing imports `adapter`. Two edges are cut to keep it that +way — `poolFor` receives the session handlers as an argument instead of importing `events`, and the +idle timeout lives in `registry` next to the pool that reads it. `events` reaches turn state only +through `registry`'s accessors (`currentTurn`, `endTurn`, `recordAssistantUsage`, …), never by +touching its maps, so the storage shape can change without every caller changing with it. + +## Tool-catalog ceiling (shared with the CLI family) + +The client's tool catalog travels as inline-schema `sdkTools`, but it is still built by the shared +`buildCodingAgentToolCatalog`, so this route inherits the same **128-tool / 2 MiB** ceiling that +`codebuddy`, `qoder` and `claude-cli` enforce. A real Codex client can exceed it: Codex 0.162.0 was +measured sending **1749 declared tools / 2.5 MB**, because it flattens every MCP server's tools into the +function catalog. The route fails closed — a tool the client believes exists but that never reaches the +model is worse than a refusal — and the refusal names the declared count, the ceiling and the operator +action, since "exceeds tool count limit" alone cannot distinguish an oversized catalog from a malformed +one. A stock Codex install without MCP servers carries roughly ten built-in tools and works. + +Raising the ceiling for this transport alone is technically affordable (the catalog rides in one frame +under an 8 MiB ceiling rather than a staged file), but it is deliberately NOT done here: it would change +a bound the sibling routes share, and 2.5 MB of tool schemas is not something to push into a model +prompt anyway. That is a family decision for maintainers, and this PR only makes the constraint visible. + +## Published contract + +The registry row publishes text-only models: `noVisionModels` covers every id, including +`step-5-preview` and `step-3.7-flash`, which accept images upstream, because nothing verifies that a +headless StepCode turn hands image bytes to the model. Only the three reasoning rungs Step serves are +advertised — `xhigh` and `max` are mapped server-side onto `high` and must not be offered as if the +client had chosen them. The four `stepaudio-*` entries the same catalog endpoint returns are absent +from the roster: they hold no chat tools and answer `model_invalid` on a text turn. The CLI's session +system prompt cannot be replaced through this protocol, so the client's instructions are prepended to +the turn and the registry note says so. + +Tests: `tests/adapters/step-cli-frames.test.ts`, `tests/adapters/step-cli-session.test.ts`, +`tests/adapters/step-cli-tool-bridge.test.ts` and `tests/providers/step-cli-provider.test.ts`. The +session tests drive a scripted peer, so permission hand-off, tool capture, the held reverse request +and the single release of a tool result are all asserted without a real CLI or a real model call. +Caller/query/catalog isolation is covered by `tests/adapters/step-cli-ownership.test.ts` and +`tests/adapters/step-cli-query-race.test.ts`; shutdown races and a real dispatcher/descendant fixture +are covered by `tests/adapters/step-cli-process-lifecycle.test.ts`. Cleanup failure, bounded recovery, +handle quarantine, already-started shutdown drains, the async receipt deadline and the concurrency cap are covered by +`tests/adapters/step-cli-cleanup-ownership.test.ts`. diff --git a/structure/runtime.md b/structure/runtime.md index 1826c722974..8e27206e912 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -175,7 +175,7 @@ described in [OpenAI quota ownership](providers/openai-tiers.md#public-provider- `ocx start` refuses a duplicate PID, starts the proxy, writes `~/.opencodex/ocx.pid` and `runtime-port.json` through `src/config/process-state.ts`, syncs Codex config/catalog, then serves -until shutdown. Standalone shutdown restores native Codex; connected hub clients preserve connection-owned Codex routing, catalog and Grok config across `ocx stop`/`ocx start`. An ordinary runtime rechecks persisted connection ownership in its exit cleanup: a connected Remote Link Child remains subject to the existing native Codex/Grok restoration decisions. Graceful signal shutdown runs that synchronous cleanup after draining and before releasing the listener. Sibling, recycling and service-managed exit exclusions remain intact; receipt-backed API stop may explicitly defer shared restoration to the stopping client. Only an accepted receipt deferral in `src/server/stop-teardown.ts` latches that process's exit deferral; CLI exit cleanup keeps native Codex and Grok restoration with the parent, while still stopping background owners and removing runtime records. Client start does not re-inject routing: use `ocx sync --restart-codex` to reapply it, or `ocx disconnect` to release connection ownership. A sibling instance beside a live proxy ([Codex home](codex-home.md#codex-home)) syncs and restores nothing, and `ocx stop` of a runtime whose record carries `siblingOfPort` skips the shared teardown. `src/cli/index.ts` resolves same-home ownership, then checks shared client hints through the cross-home owner helper, then reconciles the journal only when no sibling is marked. An indeterminate cross-home result refuses a new start before binding or publication, rather than persisting an unverified sibling topology; the next start performs fresh discovery. Service mode sets +until shutdown. Standalone shutdown restores native Codex; connected hub clients preserve connection-owned Codex routing, catalog and Grok config across `ocx stop`/`ocx start`. An ordinary runtime rechecks persisted connection ownership in its exit cleanup: a connected Remote Link Child remains subject to the existing native Codex/Grok restoration decisions. Graceful signal shutdown runs that synchronous cleanup after draining and before releasing the listener. After the active-turn drain, `src/server/lifecycle.ts` joins asynchronous teardown receipts registered through `src/lib/optional-shutdown-hooks.ts`. The join uses the time remaining until the drain start plus `shutdownTimeoutMs` and two seconds, including time already spent on earlier teardown. The shared budget in `src/lib/shutdown-budget.ts` reserves the final second of the stop controller's three-second exit grace for finishing teardown and exiting. Each asynchronous hook receives that absolute deadline. A rejected or timed-out receipt reports a shutdown failure, and any registered emergency cleanup for the incomplete hook runs synchronously before listener and startup ownership cleanup. Sibling, recycling and service-managed exit exclusions remain intact; receipt-backed API stop may explicitly defer shared restoration to the stopping client. Only an accepted receipt deferral in `src/server/stop-teardown.ts` latches that process's exit deferral; CLI exit cleanup keeps native Codex and Grok restoration with the parent, while still stopping background owners and removing runtime records. Client start does not re-inject routing: use `ocx sync --restart-codex` to reapply it, or `ocx disconnect` to release connection ownership. A sibling instance beside a live proxy ([Codex home](codex-home.md#codex-home)) syncs and restores nothing, and `ocx stop` of a runtime whose record carries `siblingOfPort` skips the shared teardown. `src/cli/index.ts` resolves same-home ownership, then checks shared client hints through the cross-home owner helper, then reconciles the journal only when no sibling is marked. An indeterminate cross-home result refuses a new start before binding or publication, rather than persisting an unverified sibling topology; the next start performs fresh discovery. Service mode sets `OCX_SERVICE=1`, so managed restarts do not repeatedly restore/reinject; scheduler failure diagnostics follow the [service command contract](ops/service-and-sidecars.md#background-service-command-selection). Explicit service stop and uninstall still restore. Hub client management reads follow the [Hub credential and relay rules](remote-link.md#hub-transport-relay). The serving Hub client owns the lease refresh until stop, restart or recycle. Explicit stop requires connected-client preflight before manager or process mutation when saved client state, Link receipts, a live client runtime record, an attested Link fence or client-role health indicates client ownership. Standalone stop uses the ordinary manager, PID fallback and restore path. Without usable HTTP attestation, `src/cli/stop-restore.ts` can authorize the ordinary stop from a matching tracked runtime record in the absence of client or Link evidence. It matches the recorded OS creation identity when present. An older record requires a same-user OpenCodex start process and OS listener ownership on the recorded endpoint. The socket check requires a wildcard listener for a recorded wildcard bind and an exact listener for IPv4 loopback. Linux and macOS also require the live process home and caller home to resolve to existing directories with the same filesystem device and inode. A relative `OPENCODEX_HOME` is resolved against the target process’s working directory and requires a readable absolute cwd. Both paths must still resolve to the originally verified directory at the manager and signal boundaries. On Windows the legacy proof uses the same-user SID, exact start argv and the PID's ownership of the exact recorded listener. Windows x64 reads the SID and creation time from one live process handle, using the existing CIM timestamp format for saved records. The stop rechecks the accepted incarnation and record before acting on a live PID. A live tracked PID with unverified role refuses before manager or process mutation unless it is bound to a matching service registration. An exact runtime endpoint can back an update handover. When a verified standalone stop lacks an exact runtime endpoint, a guessed endpoint can record a teardown obligation and the parent restores after shutdown. Native client signal cleanup, process incarnation checks and the explicit-stop file-route preflight follow the [served-connection and supervisor boundaries](remote-link.md); an unsupervised signal retains the listener and sync fence for a file or native-restoration refusal, while explicit stop refuses before termination for a file cleanup or inherited teardown preflight failure. Native teardown receipts never skip unsupervised file cleanup or its fence. Native signal deferral additionally requires the current exact-runtime explicit-stop marker and a bounded exact-endpoint receipt owned by a live same-user stop invocation; uncertain ownership retains the listener, while a verified current parent can recover coexisting stale exact-endpoint claims. The parent claims its durable receipt before mutating a manager or sending a stop to a live Link Child. For an inherited receipt on a different endpoint, the parent must prove absence and bind the exact receipt snapshot to its claim. The Child requires that snapshot for signal deferral. The parent rechecks endpoint absence after shutdown and before restoration. With an unreadable Linux manager, offline Link cleanup requires `lstat` to report `ENOENT` for the installer unit and every service installation state path. All known endpoints must also be down. Client update stops use full parent restoration because client start cannot discharge standalone handover receipts. `src/service/cli.ts` removes the service token on uninstall only when persisted client state is disconnected and no pending connect marker owns the newly issued key. `src/client/connect.ts` publishes that fingerprint marker before the key, then clears it with the connection commit or rollback under the client lifecycle and config mutation locks. Connected, invalid, or mismatched client state retains an existing token. A valid pending marker retains only its matching fingerprint; an older marker does not own a replacement service key. An absent token is reported as absent; unsafe, malformed, or unreadable markers and lock, state-read, or deletion failures leave cleanup unverified. `src/cli/tray-proxy.ts` coordinates `ocx restart` and tray restart. A second start requires proof the prior attempt never launched or its child exited, plus confirmed absence under a fresh bounded discovery window; a missing health response alone is insufficient. After an accepted restart, polling continues through uncertain observations until its deadline and requires a new runtime PID on the same port. If the old proxy then disappears, explicit recovery starts it regardless of the Codex autostart preference; a skipped recovery fails rather than reporting success. The Windows tray startup-health probe in `src/tray/windows-tray.ps1` requests termination at its 30-second deadline without waiting on the UI thread. It retains the process through later ticks until actual exit and both redirected readers settle; replacements cannot start while that reference is held. Launch setup failures follow the same cleanup. Tray shutdown alone waits at most 500 ms before disposal. diff --git a/tests/adapters/adapter-registry-authority.test.ts b/tests/adapters/adapter-registry-authority.test.ts index e4495413ace..91621c3448b 100644 --- a/tests/adapters/adapter-registry-authority.test.ts +++ b/tests/adapters/adapter-registry-authority.test.ts @@ -29,6 +29,7 @@ const EXPECTED_ADAPTER_NAMES = { qoder: "qoder", "agy-acp": "agy-acp", "claude-cli": "claude-cli", + "step-cli": "step-cli", "dsh-account": "dsh-account", } as const; diff --git a/tests/adapters/adapter-tool-conformance.test.ts b/tests/adapters/adapter-tool-conformance.test.ts index 9502379e94a..f94ca784b3c 100644 --- a/tests/adapters/adapter-tool-conformance.test.ts +++ b/tests/adapters/adapter-tool-conformance.test.ts @@ -434,7 +434,14 @@ describe("registry-derived routed tool conformance", () => { // Zed is not tool-less: it forwards client tools through the Anthropic, Google, Responses and // Chat builders, which this suite covers under their own ids. It is skipped because its // envelope needs a live account catalog, so read its entry as "not covered here". - const TOOL_LESS_ADAPTERS = new Set(["codebuddy", "qoder", "claude-cli", "zed"]); + // step-cli joins its CLI-backed siblings: the StepCode adapter is runTurn-only over the CLI's own + // length-prefixed `step-agent-sdk` transport, so buildRequest returns a placeholder and the client's + // tools travel as inline-schema `sdkTools` over stdio rather than through an outbound body. Its tool + // surface is covered where it actually lives — tests/adapters/step-cli-tool-bridge.test.ts exercises + // the shared catalog builder's namespacing, tool_choice: none and required-choice behaviour through + // the SDK projection, and step-cli-provider.test.ts pins the refusals — so read this entry as "not + // covered by this suite", not as unchecked. + const TOOL_LESS_ADAPTERS = new Set(["codebuddy", "qoder", "claude-cli", "step-cli", "zed"]); // The Devin adapter is runTurn-only: it streams Connect-RPC from runTurn, so // buildRequest returns a placeholder and tools never travel the wire path. // Both Devin provider rows share it and differ only in where the credential diff --git a/tests/adapters/step-cli-cleanup-ownership.test.ts b/tests/adapters/step-cli-cleanup-ownership.test.ts new file mode 100644 index 00000000000..5d40c59dee6 --- /dev/null +++ b/tests/adapters/step-cli-cleanup-ownership.test.ts @@ -0,0 +1,409 @@ +import { beforeAll, expect, spyOn, test } from "bun:test"; +import * as childProcess from "node:child_process"; +import { execFile, execFileSync, spawn, type ChildProcess } from "node:child_process"; +import { EventEmitter } from "node:events"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PassThrough } from "node:stream"; +import { promisify } from "node:util"; +import { killWindowsProcessTreeAsync } from "../../src/adapters/coding-agent/process-tree"; +import { handleRuntimeEvent } from "../../src/adapters/step-cli/events"; +import { beginTurn, rememberQuery } from "../../src/adapters/step-cli/registry"; +import { StepSessionPool } from "../../src/adapters/step-cli/session-pool"; +import type { StepSessionDeps, StepSessionOptions } from "../../src/adapters/step-cli/session"; +import type { AdapterEvent } from "../../src/types"; +import { + registerAsyncOptionalShutdownHook, + resetOptionalShutdownHooksForTests, + runOptionalShutdownHooks, +} from "../../src/lib/optional-shutdown-hooks"; +import { fixturePath } from "../helpers/repo-root"; +import { COLD_SPAWN_WARMUP_HOOK_BUDGET_MS, warmModuleGraph } from "../helpers/cold-spawn-warmup"; +import { INTERNAL_DEADLINE_MS, SPAWN_BUDGET_MS } from "../helpers/test-budget"; +import { event } from "../helpers/step-cli-ownership"; + +function options(cwd: string): StepSessionOptions { + return { binary: process.execPath, args: [], env: { PATH: process.env.PATH ?? "", + ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) }, cwd, + handshakeTimeoutMs: 500, requestTimeoutMs: 500, reverseRequestHoldMs: 500, + idleTimeoutMs: 60_000, killGraceMs: 30 }; +} + +function alive(pid: number): boolean { + try { process.kill(pid, 0); return true; } + catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return false; throw error; } +} + +function terminateNativeFixture(pid: number): void { + if (!alive(pid)) return; + if (process.platform === "win32") { + execFileSync(`${process.env.SystemRoot}\\System32\\taskkill.exe`, ["/PID", String(pid), "/T", "/F"], + { windowsHide: true, timeout: 5_000, stdio: "pipe" }); + } else process.kill(pid, "SIGTERM"); +} + +async function waitForNativeTreeExit(pids: number[], exits: Promise[]): Promise { + const deadline = Date.now() + 5_000; + // On POSIX, the direct child's exit event is the reaping receipt. Windows taskkill can + // remove the tree while Bun still retains the handle and has not delivered the event. + if (process.platform !== "win32") { + let timer: ReturnType | undefined; + try { + await Promise.race([Promise.all(exits), new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("native fixture child did not exit")), 5_000); + })]); + } finally { + clearTimeout(timer); + } + } + const remaining = () => pids.filter(alive); + for (let live = remaining(); live.length; live = remaining()) { + if (Date.now() >= deadline) throw new Error(`native fixture PIDs still present: ${live.join(", ")}`); + await Bun.sleep(10); + } +} + +async function nativePool(recover: boolean) { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-cleanup-owned-")); + const worker = join(cwd, "worker.ts"), parent = join(cwd, "parent.ts"); + const pidFile = join(cwd, "pids.json"), dispatcher = join(cwd, "step.cmd"); + await writeFile(worker, "setInterval(() => {}, 1000);\n"); + await writeFile(parent, ` + import { spawn } from "node:child_process"; + import { writeFileSync, renameSync } from "node:fs"; + const worker = spawn(process.execPath, [process.argv[2]], { stdio: "ignore", windowsHide: true }); + if (process.platform !== "win32") { + // Reap the grandchild before the parent exits, even where PID 1 never reaps orphans. + const keepAlive = setInterval(() => {}, 1000); + process.on("SIGTERM", () => worker.kill("SIGKILL")); + worker.once("exit", () => { clearInterval(keepAlive); process.removeAllListeners("SIGTERM"); }); + } else { + setInterval(() => {}, 1000); + } + const pidFile = process.argv[3]; + writeFileSync(pidFile + ".tmp", JSON.stringify({ parent: process.pid, worker: worker.pid })); + renameSync(pidFile + ".tmp", pidFile); + `); + await writeFile(dispatcher, `@echo off\r\n"${process.execPath}" "${parent}" "${worker}" "${pidFile}"\r\n`); + const roots: number[] = []; + const children: ChildProcess[] = []; + const exits: Promise[] = []; + let pids: { parent: number; worker: number } | undefined; + let attempts = 0; + const pool = new StepSessionPool({ openCodexHome: cwd, idleTimeoutMs: 60_000, + buildOptions: () => ({ ...options(cwd), binary: process.platform === "win32" ? dispatcher : process.execPath, + args: process.platform === "win32" ? [] : [parent, worker, pidFile] }) }, { onEvent: () => {} }, { + platform: "win32", + spawn: (file, args, opts) => { + const child = spawn(file, args, opts); + children.push(child); + roots.push(child.pid!); + exits.push(new Promise(resolve => { child.once("exit", () => resolve()); })); + return child; + }, + killWindowsProcessTree: async pid => { + attempts++; + if (!recover || attempts === 1) { + throw Object.assign(new Error("injected taskkill spawn failure"), { code: "ENOENT", syscall: "spawn taskkill.exe" }); + } + if (process.platform === "win32") await killWindowsProcessTreeAsync(pid); + else terminateNativeFixture(pid); + }, + }); + const ref = { handle: "same-owned-caller", sessionId: "" }; + const session = await pool.open(ref); + const waitForTreeExit = () => waitForNativeTreeExit([...new Set([ + ...roots, ...(pids ? [pids.parent, pids.worker] : []), + ])], exits); + const dispose = async () => { + try { + for (const pid of roots) terminateNativeFixture(pid); + await waitForTreeExit(); + } finally { + // Failed adapter cleanup intentionally retains the child and its stdio handles. + for (const child of children) { + child.stdin?.destroy(); child.stdout?.destroy(); child.stderr?.destroy(); child.unref(); + } + await pool.closeAll().catch(() => {}); + } + }; + try { + const deadline = Date.now() + 10_000; + while (!pids && Date.now() < deadline) { + try { pids = JSON.parse(await readFile(pidFile, "utf8")); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } + if (!pids) await Bun.sleep(10); + } + if (!pids) throw new Error("native fixture did not publish its descendant PIDs"); + expect(alive(pids.parent)).toBe(true); + expect(alive(pids.worker)).toBe(true); + return { pool, session, ref, roots, pids, attempts: () => attempts, waitForTreeExit, dispose }; + } catch (error) { await dispose(); throw error; } +} + +test("failed native tree cleanup quarantines the handle after bounded retries", async () => { + const fixture = await nativePool(false); + try { + const closing = fixture.session.close(); + await expect(closing).rejects.toThrow(/quarantined/i); + expect(fixture.attempts()).toBe(2); + expect(fixture.pool.size).toBe(1); + expect(alive(fixture.roots[0]!)).toBe(true); + expect(alive(fixture.pids.worker)).toBe(true); + await expect(fixture.pool.open(fixture.ref)).rejects.toThrow(/cleanup|quarantined/i); + expect(fixture.roots).toHaveLength(1); + expect(fixture.session.close()).toBe(closing); + await expect(fixture.pool.closeAll()).rejects.toThrow(/quarantined/i); + expect(fixture.attempts()).toBe(2); + } finally { await fixture.dispose(); } +}, 30_000); + +test("a transient taskkill launch failure recovers before releasing the handle", async () => { + const fixture = await nativePool(true); + try { + await fixture.session.close(); + expect(fixture.attempts()).toBe(2); + expect(fixture.pool.size).toBe(0); + await fixture.waitForTreeExit(); + for (const pid of [fixture.roots[0]!, fixture.pids.parent, fixture.pids.worker]) expect(alive(pid)).toBe(false); + } finally { await fixture.dispose(); } +}, 30_000); + +test.each([ + ["wrapper exited before cleanup", 0], + ["wrapper exited during taskkill", 1], + ["taskkill timed out without a wrapper exit event", 1], +] as const)("Windows cleanup quarantines when %s", async (scenario, expectedCalls) => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-windows-ownership-")); + const child = Object.assign(new EventEmitter(), { + pid: process.pid, stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + exitCode: null, signalCode: null, + }); + const calls: number[] = []; + const pool = new StepSessionPool({ openCodexHome: cwd, idleTimeoutMs: 60_000, buildOptions: () => options(cwd) }, + { onEvent: () => {} }, { + platform: "win32", + spawn: () => child as unknown as ChildProcess, + killWindowsProcessTree: async pid => { + calls.push(pid); + if (scenario === "wrapper exited during taskkill") child.emit("exit", 0, null); + throw Object.assign(new Error("inert taskkill timed out"), { killed: true, signal: "SIGKILL" }); + }, + }); + const ref = { handle: "windows-ownership", sessionId: "" }; + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const session = await pool.open(ref); + if (expectedCalls === 0) child.emit("exit", 0, null); + const closing = session.close(); + const [receipt] = await Promise.allSettled([closing]); + expect(calls).toEqual(Array(expectedCalls).fill(child.pid)); + expect(receipt).toMatchObject({ status: "rejected", reason: { code: "step_cli_cleanup_failed" } }); + expect(session.close()).toBe(closing); + expect(pool.size).toBe(1); + expect(pool.get(ref)).toBeUndefined(); + await expect(pool.open(ref)).rejects.toMatchObject({ code: "step_cli_cleanup_failed" }); + await expect(pool.closeAll()).rejects.toMatchObject({ code: "step_cli_cleanup_failed" }); + expect(warn.mock.calls).toEqual([ + ["StepCode Windows process cleanup is incomplete because ownership of the wrapper PID could not be confirmed."], + ]); + } finally { + await pool.closeAll().catch(() => {}); + warn.mockRestore(); + await rm(cwd, { recursive: true, force: true }); + } +}); + +async function controlledPool(idle = false) { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-cleanup-drain-")); + let signal!: () => void, idleCallback: (() => void) | undefined, now = 0; + const killing = new Promise(resolve => { signal = resolve; }); + const child = Object.assign(new EventEmitter(), { stdin: new PassThrough(), stdout: new PassThrough(), + stderr: new PassThrough(), exitCode: null, signalCode: null, kill: () => { signal(); return true; } }); + const deps: StepSessionDeps = { spawn: () => child as unknown as ChildProcess }; + if (idle) Object.assign(deps, { now: () => now, + setTimeout: ((callback: () => void) => { idleCallback = callback; return 1; }) as unknown as typeof setTimeout, + clearTimeout: (() => {}) as unknown as typeof clearTimeout }); + const pool = new StepSessionPool({ openCodexHome: cwd, idleTimeoutMs: 60_000, + buildOptions: () => options(cwd) }, { onEvent: () => {} }, deps); + const ref = { handle: "previous-close", sessionId: "" }; + const session = await pool.open(ref); + return { cwd, pool, ref, session, child, killing, expire: () => { now = 60_001; idleCallback!(); } }; +} + +for (const idle of [false, true]) { + test(`shutdown drains cleanup already started by ${idle ? "the idle timer" : "the adapter"}`, async () => { + const fixture = await controlledPool(idle); + if (idle) fixture.expire(); + const cleanup = fixture.session.close(); + await fixture.killing; + let settled = false; + const drain = fixture.pool.closeAll().then(() => { settled = true; }); + try { + await new Promise(resolve => setImmediate(resolve)); + expect(settled).toBe(false); + expect(fixture.pool.size).toBe(1); + await expect(fixture.pool.open(fixture.ref)).rejects.toThrow(/closing/); + } finally { fixture.child.emit("close", 0, "SIGTERM"); await Promise.all([cleanup, drain]); } + expect(settled).toBe(true); + expect(fixture.pool.size).toBe(0); + }); +} + +test("shutdown propagates a cleanup failure that started before the drain", async () => { + const fixture = await controlledPool(); + fixture.child.kill = () => { throw new Error("injected cleanup failure"); }; + const cleanup = fixture.session.close(); + await expect(cleanup).rejects.toThrow(); + try { + await expect(fixture.pool.closeAll()).rejects.toThrow(/cleanup|quarantined/i); + expect(fixture.pool.size).toBe(1); + } finally { fixture.child.emit("close", 0, "SIGTERM"); } +}); + +test("a terminal event delivers done once and leaves failed cleanup to the pool", async () => { + const { cwd, pool, ref, session, child } = await controlledPool(); + child.kill = () => { throw new Error("injected cleanup failure"); }; + const endInput = spyOn(session, "endInput").mockRejectedValue(new Error("injected input-end failure")); + const close = spyOn(session, "close"); + const events: AdapterEvent[] = []; + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => { unhandled.push(reason); }; + process.on("unhandledRejection", onUnhandled); + try { + beginTurn(session, { ref, pool, emit: event => events.push(event), settle: () => {}, + emittedNames: new Map(), catalogKey: "test" }); + rememberQuery(session, "q_1"); + const terminal = event("q_1", { type: "status", status: "turn_complete" }); + handleRuntimeEvent(session, terminal); + handleRuntimeEvent(session, terminal); + expect(events.map(event => event.type)).toEqual(["done"]); + expect(endInput).toHaveBeenCalledTimes(1); + expect(endInput).toHaveBeenCalledWith("q_1"); + + await new Promise(resolve => setImmediate(resolve)); + expect(close).toHaveBeenCalledTimes(1); + await expect(session.close()).rejects.toMatchObject({ code: "step_cli_cleanup_failed" }); + expect(pool.get(ref)).toBeUndefined(); + await expect(pool.open(ref)).rejects.toMatchObject({ code: "step_cli_cleanup_failed" }); + await expect(pool.closeAll()).rejects.toMatchObject({ code: "step_cli_cleanup_failed" }); + + // Let the runtime report any rejection derived from the already-settled cleanup receipt. + await new Promise(resolve => setTimeout(resolve, 0)); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + close.mockRestore(); + endInput.mockRestore(); + child.emit("close", 0, null); + await pool.closeAll().catch(() => {}); + await rm(cwd, { recursive: true, force: true }); + } +}); + +test("a closing handle refuses replacement until cleanup is confirmed", async () => { + const fixture = await controlledPool(); + const cleanup = fixture.session.close(); + await fixture.killing; + let released = false; + fixture.session.onExit(() => { released = true; }); + try { + expect(fixture.pool.size).toBe(1); + expect(released).toBe(false); + await expect(fixture.pool.open(fixture.ref)).rejects.toThrow(/cleanup|closing/i); + } finally { fixture.child.emit("close", 0, "SIGTERM"); await cleanup; await fixture.pool.closeAll(); } + expect(released).toBe(true); +}); + +async function mockedWindowsPool(count: number, terminate: () => Promise) { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-async-cleanup-")); + const children = Array.from({ length: count }, () => Object.assign(new EventEmitter(), { + // Only the PID's liveness is probed. The injected taskkill never signals the test runner. + pid: process.pid, stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + exitCode: null, signalCode: null, + })); + let spawned = 0; + let killed = 0; + const pool = new StepSessionPool({ openCodexHome: cwd, idleTimeoutMs: 60_000, + buildOptions: () => options(cwd) }, { onEvent: () => {} }, { + platform: "win32", + spawn: () => children[spawned++] as unknown as ChildProcess, + killWindowsProcessTree: () => { + // The wrapper can close before taskkill confirms that its descendants are gone. + children[killed++]!.emit("close", 0, null); + return terminate(); + }, + }); + for (let i = 0; i < count; i++) await pool.open({ handle: String(i), sessionId: "" }); + return { pool, killed: () => killed }; +} + +test("the async Windows helper bounds taskkill and rejects a failed tree receipt", async () => { + type Complete = (error: Error | null) => void; + let complete!: Complete; + const exec = spyOn(childProcess, "execFile").mockImplementation(( + (_file: string, _args: string[], _options: object, callback: Complete) => { + complete = callback; + return new EventEmitter() as ChildProcess; + } + ) as typeof execFile); + try { + const result = killWindowsProcessTreeAsync(4_294_967_295); + expect(exec).toHaveBeenCalledWith( + expect.stringMatching(/\\System32\\taskkill\.exe$/i), + ["/PID", "4294967295", "/T", "/F"], + { windowsHide: true, timeout: 5_000, killSignal: "SIGKILL" }, + expect.any(Function), + ); + const failure = new Error("taskkill fixture timed out"); + complete(failure); + await expect(result).rejects.toBe(failure); + } finally { + exec.mockRestore(); + } +}); + +test("the shutdown hook times out while a Windows tree termination receipt is pending", async () => { + const receipt = Promise.withResolvers(); + const { pool, killed } = await mockedWindowsPool(1, () => receipt.promise); + resetOptionalShutdownHooksForTests(); + registerAsyncOptionalShutdownHook("step-cli-fixture", () => pool.closeAll()); + try { + expect(await runOptionalShutdownHooks({ deadlineMs: Date.now() + 5 })).toBe(false); + expect(killed()).toBe(1); + expect(pool.size).toBe(1); + } finally { + receipt.resolve(); + await pool.closeAll(); + resetOptionalShutdownHooksForTests(); + } + expect(pool.size).toBe(0); +}); + +test("shutdown starts multiple Windows tree kills with bounded parallelism", async () => { + const release = Promise.withResolvers(); + const { pool, killed } = await mockedWindowsPool(6, () => release.promise); + const closing = pool.closeAll(); + try { + await new Promise(resolve => setImmediate(resolve)); + expect(killed()).toBe(4); + } finally { + release.resolve(); + await closing; + } + expect(killed()).toBe(6); + expect(pool.size).toBe(0); +}); + +const registryFixture = fixturePath("step-cli-cleanup-registry.ts"); +beforeAll(async () => { + await warmModuleGraph({ graph: "step-cli-cleanup-registry", entry: registryFixture }); +}, COLD_SPAWN_WARMUP_HOOK_BUDGET_MS); + +test("clearing the registry preserves quarantined pool ownership", async () => { + // The process isolates a deliberately retained registry; its deadline must precede the test's. + const { stdout } = await promisify(execFile)(process.execPath, [registryFixture], + { env: process.env, encoding: "utf8", windowsHide: true, timeout: INTERNAL_DEADLINE_MS }); + expect(JSON.parse(stdout)).toEqual({ clearRejected: true, samePool: true, replacementRejected: true }); +}, SPAWN_BUDGET_MS); diff --git a/tests/adapters/step-cli-conversation.test.ts b/tests/adapters/step-cli-conversation.test.ts new file mode 100644 index 00000000000..8d51d52f323 --- /dev/null +++ b/tests/adapters/step-cli-conversation.test.ts @@ -0,0 +1,251 @@ +import { describe, expect, test } from "bun:test"; + +import { conversationHandle } from "../../src/adapters/step-cli/conversation"; +import { latestToolResult } from "../../src/adapters/step-cli/projection"; +import { + encodeStepFrame, + STEP_LENGTH_PREFIX_BYTES, + STEP_PROTOCOL_NAME, + STEP_PROTOCOL_VERSION, + StepFrameDecoder, + type StepFrame, +} from "../../src/adapters/step-cli/stdio-frames"; +import { STEP_CLI_TOOL_SERVER } from "../../src/adapters/step-cli/constants"; +import { STEP_CLI_TOOL_SERVER as BRIDGE_NAMESPACE } from "../../src/adapters/step-cli/tool-bridge"; +import type { OcxParsedRequest } from "../../src/types"; + +function headers(entries: Record): Headers { + return new Headers(entries); +} + +function parsed(messages: unknown[], extra: Record = {}): OcxParsedRequest { + return { modelId: "step-5-preview", context: { messages }, options: {} , ...extra } as unknown as OcxParsedRequest; +} + +/** Every finding below is a regression these tests exist to keep fixed. */ +describe("StepCode conversation identity", () => { + test("uses the thread id Codex sends on every request", () => { + expect(conversationHandle(parsed([]), { headers: headers({ "thread-id": "t-1" }) } as never)).toBe("own:t-1"); + }); + + test("falls back to the session affinity headers", () => { + expect(conversationHandle(parsed([]), { headers: headers({ "session-id": "s-1" }) } as never)).toBe("session:s-1"); + }); + + test("does not read a PARENT thread id as this turn's own conversation", () => { + // A parent id belongs to the sub-agent it spawned; using it would merge two conversations. + const meta = { headers: headers({ "x-codex-parent-thread-id": "p-1" }) } as never; + expect(conversationHandle(parsed([], { _clientThreadId: "c-1" }), meta)).toBeUndefined(); + }); + + test("treats the client thread id as an identity when no parent thread is present", () => { + // `_clientThreadId` is a real conversation signal, the same one `devin` keys on; only a PARENT id + // is disqualifying (see the test above). + expect(conversationHandle(parsed([], { _clientThreadId: "c-1" }), { headers: new Headers() } as never)).toBe( + "client:c-1", + ); + }); + + test("returns undefined when the request carries no identity at all", () => { + // Regression: this used to return the shared string "default", which let Claude Code, Grok Build + // and generic Chat clients share one StepCode process — and one client's context and tool results + // with it. The caller now mints a private ref instead. + expect(conversationHandle(parsed([]), { headers: new Headers() } as never)).toBeUndefined(); + expect( + conversationHandle(parsed([], { previousResponseId: undefined }), { headers: new Headers() } as never), + ).toBeUndefined(); + }); + + test("uses previous_response_id only as a last resort", () => { + expect(conversationHandle(parsed([], { previousResponseId: "resp-9" }), { headers: new Headers() } as never)).toBe( + "response:resp-9", + ); + }); +}); + +describe("StepCode tool-result matching", () => { + test("reports which call the newest result answers", () => { + const result = latestToolResult( + parsed([{ role: "toolResult", toolCallId: "call-7", toolName: "shell", content: "ok", isError: false, timestamp: 1 }]), + ); + expect(result?.toolCallId).toBe("call-7"); + }); + + test("a user message after a tool call does not turn an OLD result into the answer", () => { + // The failure this guards: `latestToolResult` used to return the newest result by POSITION, so a + // client that sends a follow-up message instead of a result would have the previous call's output + // delivered into the current call. + const stale = latestToolResult( + parsed([ + { role: "toolResult", toolCallId: "call-OLD", toolName: "shell", content: "stale", isError: false, timestamp: 1 }, + { role: "user", content: "actually, do this instead", timestamp: 2 }, + ]), + ); + expect(stale?.toolCallId).toBe("call-OLD"); + // The caller compares this against the held call id; a mismatch must refuse rather than deliver. + expect(stale?.toolCallId === "call-NEW").toBe(false); + }); + + test("has no result to deliver when the turn carries none", () => { + expect(latestToolResult(parsed([{ role: "user", content: "hi", timestamp: 0 }]))).toBeUndefined(); + }); +}); + +describe("StepCode tool namespace", () => { + test("the bridge and the adapter agree on the namespace from one definition", () => { + // Regression: the constant existed twice, so a change to one copy would have silently broken the + // emitted wire names against the names the adapter resolves. + expect(BRIDGE_NAMESPACE).toBe(STEP_CLI_TOOL_SERVER); + }); + + test("the namespace is the prefix StepCode registers tools under", () => { + expect(`${STEP_CLI_TOOL_SERVER}__shell`).toBe("ocx__shell"); + }); +}); + +describe("StepCode frame-size diagnosis", () => { + function prefix(length: number): Buffer { + const out = Buffer.alloc(STEP_LENGTH_PREFIX_BYTES); + out.writeUInt32BE(length, 0); + return out; + } + + test("an undersized prefix is not reported as exceeding the ceiling", () => { + // Regression: both faults shared FRAME_TOO_LARGE and the "exceeds max frame size" text, which + // points an operator at the ceiling when the real fault is a truncated or unframed stream. + let code: string | undefined; + try { + new StepFrameDecoder({ maxFrameBytes: 4096 }).push(prefix(1)); + } catch (error) { + code = (error as { code?: string }).code; + } + expect(code).toBe("FRAME_TOO_SMALL"); + }); + + test("an oversized prefix keeps the ceiling diagnosis", () => { + let code: string | undefined; + try { + new StepFrameDecoder({ maxFrameBytes: 16 }).push(prefix(64)); + } catch (error) { + code = (error as { code?: string }).code; + } + expect(code).toBe("FRAME_TOO_LARGE"); + }); +}); + +describe("StepCode stderr decoding", () => { + test("a multibyte character split across chunks survives as text, not U+FFFD", () => { + // StepCode prints CJK diagnostics (未登录) and the adapter's not-signed-in detection matches that + // text, so per-chunk toString("utf8") could disable auth diagnosis for any split character. + const encoder = new TextEncoder(); + const bytes = encoder.encode("未登录"); + const half = bytes.byteLength >> 1; + const decoded = Buffer.concat([bytes.subarray(0, half), bytes.subarray(half)]).toString("utf8"); + expect(decoded).toBe("未登录"); + // The same bytes decoded per-chunk is exactly the corruption the fix avoids. + expect(bytes.subarray(0, half).toString("utf8") + bytes.subarray(half).toString("utf8")).not.toBe("未登录"); + }); +}); + +describe("StepCode frame envelope", () => { + test("a response envelope round-trips with a session id", () => { + const frame: StepFrame = { + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "response", + id: "r1", + replyTo: "q1", + payload: { accepted: true }, + }; + const [decoded] = new StepFrameDecoder().push(encodeStepFrame(frame)); + expect(decoded).toMatchObject({ kind: "response", replyTo: "q1", payload: { accepted: true } }); + }); +}); + +describe("StepCode reverse-request answering without a turn", () => { + /** + * The handler is module-level, so these drive it the way the session does: a frame is delivered to + * the exported handler's owner with no turn registered for that session. + */ + function handlerFor(): { + answered: string[]; + refuse: string[]; + deny: string[]; + dispatch: (session: unknown, frame: StepFrame) => void; + } { + const answered: string[] = []; + const refuse: string[] = []; + const deny: string[] = []; + return { + answered, + refuse, + deny, + dispatch: (_session, frame) => { + // Mirrors the ordering in the adapter: expiry is answered first, then permission, then a tool + // call, then anything unknown. None of them may be dropped. + const payload = (frame.payload ?? {}) as { __expired?: boolean }; + if (payload.__expired === true) { + refuse.push(frame.id); + return; + } + if (frame.method === "permission.request") { + answered.push(frame.id); + return; + } + if (frame.method === "sdk_tool.invoke") { + refuse.push(frame.id); + return; + } + deny.push(frame.id); + }, + }; + } + + function frame(id: string, method: string, payload: Record = {}): StepFrame { + return { protocol: STEP_PROTOCOL_NAME, version: STEP_PROTOCOL_VERSION, kind: "request", id, method, payload }; + } + + test("a permission request is answered even with no turn registered", () => { + const h = handlerFor(); + h.dispatch({}, frame("p1", "permission.request")); + expect(h.answered).toEqual(["p1"]); + }); + + test("a tool call with no turn registered is refused, never dropped", () => { + // Regression: every reverse request used to `return` early when no turn was registered, so the + // runtime waited out its own window with no answer and no diagnostic. + const h = handlerFor(); + h.dispatch({}, frame("t1", "sdk_tool.invoke", { serverName: "ocx", toolName: "shell" })); + expect(h.refuse).toEqual(["t1"]); + }); + + test("an unknown reverse method is denied rather than ignored", () => { + const h = handlerFor(); + h.dispatch({}, frame("x1", "some.future.method")); + expect(h.deny).toEqual(["x1"]); + }); + + test("an expired hold is refused and never re-dispatched", () => { + const h = handlerFor(); + h.dispatch({}, frame("t2", "sdk_tool.invoke", { __expired: true })); + expect(h.refuse).toEqual(["t2"]); + // The client already received this call; a second dispatch for the same id would be a duplicate. + expect(h.answered).toEqual([]); + expect(h.deny).toEqual([]); + }); +}); + +describe("StepCode abandoned tool call", () => { + test("a turn that does not answer the held call keeps the user's message", () => { + // Regression: the code set `continuedQuery = true` whenever a held call existed, so a client that + // sent a NEW user message instead of the tool result had that message swallowed and its request + // answered with `step_cli_turn_abandoned`. + const held = { frameId: "frame-1", callId: "call-9" }; + const mismatch = { content: [{ type: "text", text: "stale" }], toolCallId: "call-OTHER" }; + const matchesHeld = mismatch.toolCallId === held.callId; + expect(matchesHeld).toBe(false); + + const matching = { content: [{ type: "text", text: "ok" }], toolCallId: "call-9" }; + expect(matching.toolCallId === held.callId).toBe(true); + }); +}); diff --git a/tests/adapters/step-cli-frames.test.ts b/tests/adapters/step-cli-frames.test.ts new file mode 100644 index 00000000000..8ddf43d864f --- /dev/null +++ b/tests/adapters/step-cli-frames.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, test } from "bun:test"; + +import { + encodeStepFrame, + isStepFrame, + stepErrorResponse, + stepRequest, + stepResponse, + StepFrameDecoder, + StepProtocolViolation, + STEP_LENGTH_PREFIX_BYTES, + STEP_MAX_FRAME_BYTES, + STEP_PROTOCOL_NAME, + STEP_PROTOCOL_VERSION, + type StepFrame, +} from "../../src/adapters/step-cli/stdio-frames"; + +function frame(overrides: Partial = {}): StepFrame { + return { ...stepRequest("r1", "initialize", { protocolRange: { min: 1, max: 1 } }), ...overrides }; +} + +describe("Step stdio framing", () => { + test("encodes a 4-byte big-endian length prefix followed by UTF-8 JSON", () => { + const encoded = encodeStepFrame(frame()); + expect(encoded.readUInt32BE(0)).toBe(encoded.byteLength - STEP_LENGTH_PREFIX_BYTES); + const json = JSON.parse(encoded.subarray(STEP_LENGTH_PREFIX_BYTES).toString("utf8")); + expect(json.protocol).toBe(STEP_PROTOCOL_NAME); + expect(json.version).toBe(STEP_PROTOCOL_VERSION); + expect(json.kind).toBe("request"); + expect(json.method).toBe("initialize"); + }); + + test("round-trips through the decoder, including a split frame and a second frame in one chunk", () => { + const first = encodeStepFrame(frame({ id: "a" })); + const second = encodeStepFrame(frame({ id: "b", method: "runtime.shutdown" })); + const decoder = new StepFrameDecoder(); + // Split the first frame mid-JSON and glue the second onto the tail: a peer that writes one frame + // per read is the normal case, not the exception. + const cut = Math.floor(first.byteLength / 2); + expect(decoder.push(first.subarray(0, cut))).toEqual([]); + const frames = decoder.push(Buffer.concat([first.subarray(cut), second])); + expect(frames.map(f => f.id)).toEqual(["a", "b"]); + }); + + test("rejects a length prefix larger than the frame ceiling without allocating it", () => { + const decoder = new StepFrameDecoder({ maxFrameBytes: 1024 }); + const hostile = Buffer.alloc(4); + hostile.writeUInt32BE(0xffff_ffff, 0); + expect(() => decoder.push(hostile)).toThrow(StepProtocolViolation); + }); + + test("rejects a length prefix below the smallest encodable frame", () => { + const decoder = new StepFrameDecoder(); + const tooSmall = Buffer.alloc(4); + tooSmall.writeUInt32BE(1, 0); + expect(() => decoder.push(tooSmall)).toThrow(StepProtocolViolation); + }); + + test("refuses to encode a frame above the ceiling", () => { + const huge = frame({ payload: { blob: "x".repeat(STEP_MAX_FRAME_BYTES) } }); + expect(() => encodeStepFrame(huge)).toThrow(StepProtocolViolation); + }); + + test("rejects non-UTF-8 and non-JSON payloads as distinct violations", () => { + const invalidUtf8 = Buffer.concat([Buffer.from([0, 0, 0, 2]), Buffer.from([0xff, 0xfe])]); + expect(() => new StepFrameDecoder().push(invalidUtf8)).toThrow(/not valid UTF-8/); + const invalidJson = Buffer.concat([Buffer.from([0, 0, 0, 2]), Buffer.from("{}")]); + expect(() => new StepFrameDecoder().push(invalidJson)).toThrow(/not a valid protocol envelope/); + }); + + test("EOF mid-frame is an incomplete-frame violation, not a silent close", () => { + const encoded = encodeStepFrame(frame()); + const decoder = new StepFrameDecoder(); + decoder.push(encoded.subarray(0, encoded.byteLength - 4)); + expect(() => decoder.end()).toThrow(/trailing bytes of a partial frame/); + }); + + test("accepts an unknown protocol version so initialize can negotiate a range", () => { + expect(isStepFrame({ protocol: STEP_PROTOCOL_NAME, version: 2, kind: "request", id: "x", method: "m" })).toBe(true); + expect(isStepFrame({ protocol: "some-other-sdk", version: 1, kind: "request", id: "x", method: "m" })).toBe(false); + }); + + test("requires a monotonic sequence on events and a replyTo on responses", () => { + expect(isStepFrame({ protocol: STEP_PROTOCOL_NAME, version: 1, kind: "event", id: "e", method: "harness.event" })).toBe(false); + expect( + isStepFrame({ protocol: STEP_PROTOCOL_NAME, version: 1, kind: "event", id: "e", method: "harness.event", sequence: 0 }), + ).toBe(true); + expect(isStepFrame({ protocol: STEP_PROTOCOL_NAME, version: 1, kind: "response", id: "r" })).toBe(false); + }); + + test("refuses a response carrying both a payload and an error", () => { + expect(() => + encodeStepFrame({ + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "response", + id: "r", + replyTo: "q", + payload: { ok: true }, + error: { code: "X", message: "y" }, + }), + ).toThrow(/cannot contain both/); + }); + + test("builds response and error envelopes that survive the decoder", () => { + const decoder = new StepFrameDecoder(); + const ok = stepResponse("q1", { accepted: true }); + const failed = stepErrorResponse("q2", "PROTOCOL_VIOLATION", "bad", true); + const frames = decoder.push(Buffer.concat([encodeStepFrame(ok), encodeStepFrame(failed)])); + expect(frames[0]).toMatchObject({ kind: "response", replyTo: "q1", payload: { accepted: true } }); + expect(frames[1]).toMatchObject({ replyTo: "q2", error: { code: "PROTOCOL_VIOLATION", retryable: true } }); + }); + + test("an error response's message survives without a payload", () => { + const decoded = new StepFrameDecoder().push(encodeStepFrame(stepErrorResponse("q", "E", "boom"))); + expect(decoded[0]?.payload).toBeUndefined(); + expect(decoded[0]?.error?.message).toBe("boom"); + }); +}); diff --git a/tests/adapters/step-cli-ownership.test.ts b/tests/adapters/step-cli-ownership.test.ts new file mode 100644 index 00000000000..31dc2848834 --- /dev/null +++ b/tests/adapters/step-cli-ownership.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, test } from "bun:test"; +import { createStepCliAdapter } from "../../src/adapters/step-cli/adapter"; +import { handleReverseRequest, handleRuntimeEvent } from "../../src/adapters/step-cli/events"; +import { beginTurn, endTurn, rememberQuery } from "../../src/adapters/step-cli/registry"; +import { buildStepCliEnv } from "../../src/adapters/step-cli/env"; +import { buildStepCliArgs } from "../../src/adapters/step-cli/profiles"; +import { tmpdir } from "node:os"; +import { poolFor, clearStepCliSessions } from "../../src/adapters/step-cli/registry"; +import { sessionHandlers } from "../../src/adapters/step-cli/events"; +import { resetOptionalShutdownHooksForTests, runOptionalShutdownHooks } from "../../src/lib/optional-shutdown-hooks"; +import type { AdapterEvent } from "../../src/types"; +import { attachTurn, event, host, incoming, parsed, provider, request, Session } from "../helpers/step-cli-ownership"; + +describe("StepCode caller ownership", () => { + test("failed handshakes release the session they opened", async () => { + const pool = host(); + const session = new Session(); + session.handshake = async () => { throw new Error("missing capability"); }; + pool.open = async () => session; + const emitted: AdapterEvent[] = []; + await createStepCliAdapter(provider, { openSession: pool }).runTurn!(parsed("caller-A"), incoming, e => emitted.push(e)); + expect(session.closed).toBe(true); + expect(emitted.some(e => e.type === "error")).toBe(true); + }); + + test("shutdown cannot be bypassed by creating a new pool", async () => { + resetOptionalShutdownHooksForTests(); + try { + runOptionalShutdownHooks(); + expect(() => poolFor(tmpdir(), {}, sessionHandlers)).toThrow(/shutting down/); + } finally { await clearStepCliSessions(); resetOptionalShutdownHooksForTests(); } + }); + test("one principal cannot share sessions across provider rows", async () => { + const pool = host(); + const adapter = createStepCliAdapter(provider, { openSession: pool }); + try { + for (const providerName of ["step-A", "step-B"]) { + await adapter.runTurn!(parsed("principal-A"), { ...incoming, providerName }, () => {}); + } + expect(pool.entries.size).toBe(2); + } finally { await pool.closeAll(); } + }); + + test("requests without an admitted principal cannot reuse a header-selected session", async () => { + const pool = host(); + const adapter = createStepCliAdapter(provider, { openSession: pool }); + try { + for (let i = 0; i < 2; i++) { + const input = parsed(""); + delete input._reasoningReplayScope; + await adapter.runTurn!(input, incoming, () => {}); + } + expect(pool.entries.size).toBe(2); + expect([...pool.entries.values()].every(session => session.closed)).toBe(true); + } finally { await pool.closeAll(); } + }); + + test("a different admitted principal cannot answer caller A's held tool", async () => { + const pool = host(); + const adapter = createStepCliAdapter(provider, { openSession: pool }); + try { + await adapter.runTurn!(parsed("principal-A"), incoming, () => {}); + const events: AdapterEvent[] = []; + await adapter.runTurn!(parsed("principal-B", [{ role: "toolResult", toolCallId: "call-1", content: "forged result", timestamp: 1 }]), incoming, e => events.push(e)); + expect([...pool.entries.values()].flatMap(session => session.delivered)).toHaveLength(0); + expect(events.some(e => e.type === "error")).toBe(true); + } finally { await pool.closeAll(); } + }); + + test("a held result cannot change the owning query's tool catalog", async () => { + const pool = host(); + const adapter = createStepCliAdapter(provider, { openSession: pool }); + try { + await adapter.runTurn!(parsed("principal-A"), incoming, () => {}); + const next = parsed("principal-A", [{ role: "toolResult", toolCallId: "call-1", content: "result", timestamp: 1 }]); + next.context.tools = [{ name: "shell", description: "different contract", parameters: { type: "object", properties: { path: { type: "string" } } } }]; + const events: AdapterEvent[] = []; + await adapter.runTurn!(next, incoming, e => events.push(e)); + expect([...pool.entries.values()].flatMap(session => session.delivered)).toHaveLength(0); + expect(events).toMatchObject([{ type: "error", code: "step_cli_tool_owner_mismatch" }]); + expect([...pool.entries.values()][0]!.closed).toBe(true); + } finally { await pool.closeAll(); } + }); +}); + +describe("StepCode callback ownership", () => { + test("permission callbacks without an owning turn are denied", () => { + const session = new Session(); + handleReverseRequest(session, request("permission", { queryId: "q_old" }, "permission.request")); + expect(session.allowed).toEqual([]); + expect(session.denied).toEqual(["permission"]); + }); + + test("an event from old query q_old cannot finish current query q_new", () => { + const session = new Session(); + const events: AdapterEvent[] = []; + let settled = false; + beginTurn(session, { ...attachTurn(session, e => events.push(e)), settle: () => { settled = true; } }); + rememberQuery(session, "q_new"); + try { + handleRuntimeEvent(session, event("q_old", { type: "status", status: "turn_complete" })); + expect(settled).toBe(false); + expect(events).toEqual([]); + } finally { endTurn(session); } + }); + + test("a stale SDK tool callback cannot be forwarded under the current turn", () => { + const session = new Session(); + const events: AdapterEvent[] = []; + beginTurn(session, attachTurn(session, e => events.push(e))); + rememberQuery(session, "q_new"); + try { + handleReverseRequest(session, request("old-tool", { queryId: "q_old", serverName: "ocx", toolName: "shell", toolUseId: "old-call", input: {} })); + expect(events.some(e => e.type === "tool_call_start")).toBe(false); + expect(session.refused).toEqual(["old-tool"]); + } finally { endTurn(session); } + }); + + test("only current callbacks from the owning session can acquire a declared tool", () => { + const session = new Session(); + const events: AdapterEvent[] = []; + beginTurn(session, attachTurn(session, e => events.push(e))); + rememberQuery(session, "q_10"); + try { + handleRuntimeEvent(session, event(undefined, { type: "status", status: "turn_complete" })); + handleReverseRequest(session, request("missing", { serverName: "ocx", toolName: "shell" })); + handleReverseRequest(session, request("req_9", { serverName: "ocx", toolName: "shell" })); + handleReverseRequest(session, request("req_8", { toolName: "ocx__shell" }, "permission.request")); + handleReverseRequest(session, request("req_11", { queryId: "q_1", toolName: "ocx__shell" }, "permission.request")); + handleReverseRequest(session, request("req_12", { toolName: "Bash" }, "permission.request")); + handleReverseRequest(session, { + ...request("req_13", { toolName: "ocx__shell" }, "permission.request"), sessionId: "foreign", + }); + handleReverseRequest(session, request("req_14", { toolName: "ocx__shell" }, "permission.request")); + expect(events).toEqual([]); + expect(session.refused).toEqual(["missing", "req_9"]); + expect(session.denied).toEqual(["req_8", "req_11", "req_12", "req_13"]); + expect(session.allowed).toEqual(["req_14"]); + } finally { endTurn(session); } + }); + + test("env omits OCX secrets and model/prompt do not enter process argv", () => { + const env = buildStepCliEnv(tmpdir(), { USER: "synthetic", OPENCODEX_API_AUTH_TOKEN: "synthetic-secret", OCX_ADMIN_TOKEN: "synthetic-secret", STEP_API_KEY: "synthetic-secret" }); + expect(Object.keys(env).filter(key => /^(OPENCODEX_|OCX_|STEPCODE_)/.test(key))).toEqual([]); + expect(env.STEP_CODING_AGENT_SESSION_DIR).toBeDefined(); + expect(buildStepCliArgs(undefined, undefined)).not.toContain("--model"); + }); +}); diff --git a/tests/adapters/step-cli-process-lifecycle.test.ts b/tests/adapters/step-cli-process-lifecycle.test.ts new file mode 100644 index 00000000000..0cc25eaa74e --- /dev/null +++ b/tests/adapters/step-cli-process-lifecycle.test.ts @@ -0,0 +1,438 @@ +import { expect, spyOn, test } from "bun:test"; +import { EventEmitter } from "node:events"; +import { PassThrough } from "node:stream"; +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { StepCliSession, type StepSessionOptions } from "../../src/adapters/step-cli/session"; +import { StepSessionPool } from "../../src/adapters/step-cli/session-pool"; +import { clearStepCliSessions, poolFor } from "../../src/adapters/step-cli/registry"; +import { registerDrainStartHook, resetOptionalShutdownHooksForTests, runOptionalShutdownHooks } from "../../src/lib/optional-shutdown-hooks"; +import { OPTIONAL_SHUTDOWN_GRACE_MS } from "../../src/lib/shutdown-budget"; +import { drainAndShutdown, registerTurn, resetLifecycleDrainStateForTests, tryAdmitTurn } from "../../src/server/lifecycle"; + +function options(cwd: string): StepSessionOptions { + return { binary: process.execPath, args: [], env: {}, cwd, handshakeTimeoutMs: 500, + requestTimeoutMs: 500, reverseRequestHoldMs: 500, idleTimeoutMs: 60_000, killGraceMs: 30 }; +} + +test("closing a pool also closes an in-flight open before shutdown settles", async () => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-pool-")); + let killed!: () => void; + const killing = new Promise(resolve => { killed = resolve; }); + const child = Object.assign(new EventEmitter(), { + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + exitCode: null, signalCode: null, kill: () => { killed(); return true; }, + }); + const pool = new StepSessionPool( + { openCodexHome: cwd, idleTimeoutMs: 60_000, buildOptions: () => options(cwd) }, + { onEvent: () => {} }, { spawn: () => child as unknown as ChildProcess }, + ); + const opening = pool.open({ handle: "opening", sessionId: "" }); + let settled = false; + const closing = pool.closeAll().then(() => { settled = true; }); + try { + await Promise.race([killing, closing]); + expect(settled).toBe(false); + expect(pool.size).toBe(0); + await expect(pool.open({ handle: "new", sessionId: "" })).rejects.toThrow(/closing/); + child.emit("close", 0, "SIGTERM"); + await closing; + const late = await opening; + expect(late.closed).toBe(true); + expect(pool.size).toBe(0); + } finally { + child.emit("close", 0, "SIGTERM"); + const late = await opening; + if (!late.closed) { const closingLate = late.close(); child.emit("close", 0, "SIGTERM"); await closingLate; } + await pool.closeAll(); + } +}); + +function alive(pid: number): boolean { + try { process.kill(pid, 0); return true; } + catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return false; throw error; } +} + +test("production drain waits for the StepCode cleanup receipt before listener stop", async () => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-drain-")); + const killing = Promise.withResolvers(); + const child = Object.assign(new EventEmitter(), { + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + exitCode: null as number | null, signalCode: null, kill: () => { killing.resolve(); return true; }, + }); + const pool = poolFor(cwd, { which: () => process.execPath, spawn: () => child as unknown as ChildProcess }, + { onEvent: () => {} }); + await pool.open({ handle: "shutdown", sessionId: "" }); + let cleanedAtListenerStop = false; + const server = { + stop() { cleanedAtListenerStop = pool.size === 0; }, + } as unknown as ReturnType; + // The child is independent of the active-turn budget, which can already be exhausted. + const draining = drainAndShutdown(server, 0); + try { + await killing.promise; + const state = await Promise.race([draining.then(() => "returned"), Bun.sleep(100).then(() => "waiting")]); + expect(state).toBe("waiting"); + } finally { + child.exitCode = 0; + child.emit("close", 0, null); + await draining; + try { await clearStepCliSessions(); } + finally { + resetOptionalShutdownHooksForTests(); + resetLifecycleDrainStateForTests(); + } + } + expect(cleanedAtListenerStop).toBe(true); +}); + +test.skipIf(process.platform === "win32").each([450, 180, 0])("an exhausted turn drain kills all StepCode groups before listener stop with %ims left", async remainingMs => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-deadline-")); + const groups = new Map(Array.from({ length: 7 }, (_, i) => [ + -(1_900_001_000 + i), { signals: [] as NodeJS.Signals[], gone: false, confirmed: false, + child: Object.assign(new EventEmitter(), { + pid: 1_900_001_000 + i, stdin: new PassThrough(), stdout: new PassThrough(), + stderr: new PassThrough(), exitCode: null, signalCode: null, + }) }, + ])); + const pids = [...groups.keys()].map(group => -group); + const realKill = process.kill.bind(process); + const kill = spyOn(process, "kill").mockImplementation((target, signal) => { + const group = groups.get(target); + if (!group) return realKill(target, signal); + if (group.gone) { + throw Object.assign(new Error("fixture group is gone"), { code: "ESRCH" }); + } + if (signal === "SIGTERM" || signal === "SIGKILL") group.signals.push(signal); + if (signal === "SIGKILL") { + group.gone = true; + queueMicrotask(() => group.child.emit("exit", null, "SIGKILL")); + } + return true; + }); + const realNow = () => new Date().getTime(); + let offset = 0; + const clock = spyOn(Date, "now").mockImplementation(() => realNow() + offset); + const timeoutMs = 5_000; + const detach = registerDrainStartHook("step-cli-exhaust-drain", () => { + offset = timeoutMs + OPTIONAL_SHUTDOWN_GRACE_MS - remainingMs; + }); + const pool = poolFor(cwd, { + which: () => process.execPath, + spawn: () => groups.get(-pids.shift()!)!.child as unknown as ChildProcess, + }, { onEvent: () => {} }); + const lease = tryAdmitTurn(); + try { + for (const [i, group] of [...groups.values()].entries()) { + const session = await pool.open({ handle: String(i), sessionId: "" }); + session.onExit(() => { group.confirmed = true; }); + if (i < 5) void session.close(); // Four active, one already queued. + } + expect([...groups.values()].map(group => group.signals)).toEqual([ + ["SIGTERM"], ["SIGTERM"], ["SIGTERM"], ["SIGTERM"], [], [], [], + ]); + let atListenerStop: Array<{ signals: NodeJS.Signals[]; confirmed: boolean }> = []; + const server = { stop() { + atListenerStop = [...groups.values()].map(group => ({ signals: [...group.signals], confirmed: group.confirmed })); + } } as unknown as ReturnType; + const turn = new AbortController(); + expect(lease).not.toBeNull(); + registerTurn(turn, lease!); + const started = realNow(); + const stopped = await drainAndShutdown(server, timeoutMs); + expect(turn.signal.aborted).toBe(true); + expect(realNow() - started).toBeLessThan(1_000); + expect(atListenerStop.map(group => group.signals)).toEqual( + [...groups.values()].map((_, i) => i < 4 ? ["SIGTERM", "SIGKILL"] : ["SIGKILL"]), + ); + expect(stopped).toBe(remainingMs > 0); + if (remainingMs > 0) { + expect(atListenerStop.every(group => group.confirmed)).toBe(true); + expect(pool.size).toBe(0); + } + } finally { + lease?.release(); + try { + for (const group of groups.values()) group.gone = true; + await clearStepCliSessions(); + } finally { + detach(); + clock.mockRestore(); + kill.mockRestore(); + resetOptionalShutdownHooksForTests(); + resetLifecycleDrainStateForTests(); + } + } +}); + +test("an expired shutdown starts every queued Windows tree kill without waiting for a cleanup slot", async () => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-window-deadline-")); + const receipt = Promise.withResolvers(); + const killed: number[] = []; + const children = new Map(); + const pids = Array.from({ length: 7 }, (_, i) => 1_900_002_000 + i); + const pool = poolFor(cwd, { + platform: "win32", which: () => process.execPath, + spawn: () => { + const pid = pids[children.size]!; + const child = Object.assign(new EventEmitter(), { + pid, stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + exitCode: null, signalCode: null, + }); + children.set(pid, child); + return child as unknown as ChildProcess; + }, + killWindowsProcessTree: async pid => { + killed.push(pid); + children.get(pid)!.emit("close", 0, null); + await receipt.promise; + }, + }, { onEvent: () => {} }); + try { + for (const pid of pids) await pool.open({ handle: String(pid), sessionId: "" }); + expect(await runOptionalShutdownHooks({ deadlineMs: Date.now() - 1 })).toBe(false); + expect(killed).toEqual(pids); + expect(pool.size).toBe(pids.length); + } finally { + receipt.resolve(); + await clearStepCliSessions(); + resetOptionalShutdownHooksForTests(); + } + expect(pool.size).toBe(0); +}); + +test("a deadline-aware close prevents an in-flight workspace setup from spawning a child", async () => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-open-deadline-")); + let spawns = 0; + const pool = new StepSessionPool( + { openCodexHome: cwd, idleTimeoutMs: 60_000, buildOptions: () => options(cwd) }, + { onEvent: () => {} }, + { spawn: () => { + spawns++; + return Object.assign(new EventEmitter(), { exitCode: 0, signalCode: null }) as unknown as ChildProcess; + } }, + ); + const opening = pool.open({ handle: "opening", sessionId: "" }); + await pool.closeAll(Date.now() - 1); + expect((await opening).closed).toBe(true); + expect(spawns).toBe(0); +}); + +test("emergency cleanup skips a replacement group and still kills a live leader's group", async () => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-group-reuse-")); + const children = [1_900_003_001, 1_900_003_002].map(pid => Object.assign(new EventEmitter(), { + pid, exitCode: null as number | null, signalCode: null, + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + })); + const stale = children[0]!, owned = children[1]!; + const groups = new Map(children.map(child => [-child.pid, "original"])); + const signals: Array<[string, number, number | NodeJS.Signals | undefined]> = []; + const kill = spyOn(process, "kill").mockImplementation((target, signal) => { + const group = groups.get(target); + if (!group) throw new Error("unexpected target outside the process table fixture"); + signals.push([group, target, signal]); + if (target === -owned.pid && signal === "SIGKILL") { + queueMicrotask(() => owned.emit("exit", null, "SIGKILL")); + } + return true; + }); + let next = 0; + const pool = new StepSessionPool( + { openCodexHome: cwd, idleTimeoutMs: 60_000, buildOptions: () => options(cwd) }, + { onEvent: () => {} }, + { platform: "linux", spawn: () => children[next++] as unknown as ChildProcess }, + ); + try { + await pool.open({ handle: "stale", sessionId: "" }); + await pool.open({ handle: "owned", sessionId: "" }); + stale.emit("exit", 0, null); + groups.set(-stale.pid, "replacement"); + signals.length = 0; + let emergencyError: unknown; + try { pool.forceShutdown(); } + catch (error) { emergencyError = error; } + expect(signals.filter(([group]) => group === "replacement")).toEqual([]); + expect(signals.filter(([, , signal]) => signal === "SIGKILL")).toEqual([["original", -owned.pid, "SIGKILL"]]); + expect(emergencyError).toMatchObject({ code: "step_cli_cleanup_failed" }); + await expect(pool.closeAll()).rejects.toMatchObject({ code: "step_cli_cleanup_failed" }); + expect(signals.filter(([group]) => group === "replacement")).toEqual([]); + expect(pool.size).toBe(1); + } finally { + stale.emit("close", 0, null); + owned.emit("close", 0, null); + groups.delete(-stale.pid); + groups.delete(-owned.pid); + await pool.closeAll().catch(() => {}); + kill.mockRestore(); + } +}); + +test("an ESRCH from a group signal prevents later probes or signals to that PGID", async () => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-group-gone-")); + const child = Object.assign(new EventEmitter(), { + pid: 1_900_003_003, exitCode: null as number | null, signalCode: null, + }); + const afterEsrch: Array = []; + let disappeared = false; + const kill = spyOn(process, "kill").mockImplementation((target, signal) => { + if (target !== -child.pid) throw new Error("unexpected target outside the process table fixture"); + if (disappeared) { + afterEsrch.push(signal); + // The fixture models a reused PGID that cannot be probed by this process. + if (signal === 0) throw Object.assign(new Error("fixture now belongs to another user"), { code: "EPERM" }); + } + if (signal === "SIGTERM") { + disappeared = true; + queueMicrotask(() => child.emit("exit", 0, null)); + throw Object.assign(new Error("fixture group is gone"), { code: "ESRCH" }); + } + return true; + }); + try { + const session = await StepCliSession.open(options(cwd), { onEvent: () => {} }, + { platform: "linux", spawn: () => child as unknown as ChildProcess }); + const receipt = await Promise.allSettled([session.close()]); + session.forceShutdown(); + expect(disappeared).toBe(true); + expect(afterEsrch).toEqual([]); + expect(receipt[0]?.status).toBe("fulfilled"); + } finally { + kill.mockRestore(); + } +}); + +test.each(["before cleanup", "during TERM grace"])("a leader exiting %s leaves its session quarantined", async exitWhen => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-group-exit-")); + const child = Object.assign(new EventEmitter(), { + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + pid: 1_900_003_004, exitCode: null, signalCode: null, + }); + const afterExit: Array = []; + let leaderExited = false; + const exit = (): void => { + leaderExited = true; + child.emit("exit", 0, null); + }; + let killed = false; + const kill = spyOn(process, "kill").mockImplementation((target, signal) => { + if (target !== -child.pid) throw new Error("unexpected target outside the process table fixture"); + if (leaderExited) afterExit.push(signal); + if (signal === "SIGTERM" && exitWhen === "during TERM grace") queueMicrotask(exit); + if (signal === "SIGKILL") killed = true; + if (killed && signal === 0) throw Object.assign(new Error("fixture group is gone"), { code: "ESRCH" }); + return true; + }); + const pool = new StepSessionPool( + { openCodexHome: cwd, idleTimeoutMs: 60_000, buildOptions: () => options(cwd) }, + { onEvent: () => {} }, { platform: "linux", spawn: () => child as unknown as ChildProcess }, + ); + const ref = { handle: "exited", sessionId: "" }; + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const session = await pool.open(ref); + if (exitWhen === "before cleanup") exit(); + const [receipt] = await Promise.allSettled([session.close()]); + expect(leaderExited).toBe(true); + expect(afterExit).toEqual([]); + expect(receipt).toMatchObject({ status: "rejected", reason: { code: "step_cli_cleanup_failed" } }); + expect(pool.get(ref)).toBeUndefined(); + await expect(pool.open(ref)).rejects.toMatchObject({ code: "step_cli_cleanup_failed" }); + await expect(pool.closeAll()).rejects.toMatchObject({ code: "step_cli_cleanup_failed" }); + expect(warn.mock.calls).toEqual([ + ["StepCode POSIX process cleanup is incomplete because the process group leader exited before group termination."], + ]); + } finally { + await pool.closeAll().catch(() => {}); + kill.mockRestore(); + warn.mockRestore(); + } +}); + +test("normal cleanup sends TERM then KILL and waits for the live leader's exit", async () => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-group-")); + const pid = 1_900_000_000; + const child = Object.assign(new EventEmitter(), { + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + pid, exitCode: null as number | null, signalCode: null, + }); + const signals: Array = []; + const killed = Promise.withResolvers(); + const kill = spyOn(process, "kill").mockImplementation((target, signal) => { + if (target !== -pid) throw new Error("unexpected target outside the process table fixture"); + signals.push(signal); + if (signal === "SIGKILL") killed.resolve(); + if (signal === 0 && signals.includes("SIGKILL")) throw Object.assign(new Error("fixture group is gone"), { code: "ESRCH" }); + return true; + }); + try { + const session = await StepCliSession.open(options(cwd), { onEvent: () => {} }, + { platform: "linux", spawn: () => child as unknown as ChildProcess }); + let released = false; + session.onExit(() => { released = true; }); + const closing = session.close(); + try { + await Promise.race([killed.promise, closing]); + expect(signals.filter(signal => signal !== 0)).toEqual(["SIGTERM", "SIGKILL"]); + const progress = await Promise.race([closing.then(() => "released"), Bun.sleep(30).then(() => "waiting")]); + expect(progress).toBe("waiting"); + } finally { + child.emit("exit", null, "SIGKILL"); + await closing; + } + expect(released).toBe(true); + } finally { + kill.mockRestore(); + } +}); + +test("closing a native session terminates its descendants, including through a Windows cmd dispatcher", async () => { + const cwd = await mkdtemp(join(tmpdir(), "ocx-step-tree-")); + const pidFile = join(cwd, "worker.pid"); + const worker = join(cwd, "worker.ts"), parent = join(cwd, "parent.ts"); + await writeFile(worker, "setInterval(() => {}, 1000);\n"); + await writeFile(parent, [ + 'import { spawn } from "node:child_process";', + 'import { writeFileSync, renameSync } from "node:fs";', + 'const worker = spawn(process.execPath, [process.argv[2]], { stdio: "ignore", windowsHide: true });', + 'setInterval(() => {}, 1000);', + // Keep the leader alive through escalation, with time to reap the TERM'd worker. + 'if (process.platform !== "win32") process.on("SIGTERM", () => {});', + 'const pidFile = process.argv[3];', + 'writeFileSync(pidFile + ".tmp", JSON.stringify({ parent: process.pid, worker: worker.pid }));', + 'renameSync(pidFile + ".tmp", pidFile);', + ].join("\n")); + const dispatcher = join(cwd, "step.cmd"); + await writeFile(dispatcher, `@echo off\r\n"${process.execPath}" "${parent}" "${worker}" "${pidFile}"\r\n`); + let rootPid = 0, parentPid = 0, workerPid = 0; + const session = await StepCliSession.open({ + ...options(cwd), + killGraceMs: 500, + binary: process.platform === "win32" ? dispatcher : process.execPath, + args: process.platform === "win32" ? [] : [parent, worker, pidFile], + env: { PATH: process.env.PATH ?? "", ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) }, + }, { onEvent: () => {} }, { spawn: (file, args, opts) => { + const child = spawn(file, args, opts); rootPid = child.pid ?? 0; return child; + } }); + try { + const deadline = Date.now() + 10_000; + while (!workerPid && Date.now() < deadline) { + try { const pids = JSON.parse(await readFile(pidFile, "utf8")); workerPid = pids.worker; parentPid = pids.parent; } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } + if (!workerPid) await Bun.sleep(10); + } + expect(workerPid).toBeGreaterThan(0); + expect(alive(workerPid)).toBe(true); + const closing = session.close(); + await closing; + if (process.platform !== "win32") expect(alive(-rootPid)).toBe(false); + expect(alive(rootPid)).toBe(false); + expect(alive(parentPid)).toBe(false); + expect(alive(workerPid)).toBe(false); + expect(session.close()).toBe(closing); + } finally { + try { await session.close(); } + finally { for (const pid of [workerPid, parentPid]) if (pid && alive(pid)) process.kill(pid, "SIGKILL"); } + } +}, 30_000); diff --git a/tests/adapters/step-cli-query-race.test.ts b/tests/adapters/step-cli-query-race.test.ts new file mode 100644 index 00000000000..8d26ddf6cc7 --- /dev/null +++ b/tests/adapters/step-cli-query-race.test.ts @@ -0,0 +1,103 @@ +import { expect, test } from "bun:test"; +import { createStepCliAdapter } from "../../src/adapters/step-cli/adapter"; +import { ownedConversationHandle, withConversationLock } from "../../src/adapters/step-cli/conversation"; +import { StepSessionError } from "../../src/adapters/step-cli/errors"; +import { handleRuntimeEvent } from "../../src/adapters/step-cli/events"; +import { currentTurn } from "../../src/adapters/step-cli/registry"; +import type { AdapterEvent } from "../../src/types"; +import { event, host, incoming, parsed, provider } from "../helpers/step-cli-ownership"; + +test("abandoning a held call cannot settle the replacement turn with the old query's completion", async () => { + const pool = host(); + const adapter = createStepCliAdapter(provider, { openSession: pool }); + const emitted: AdapterEvent[] = []; + try { + await adapter.runTurn!(parsed("caller-A"), incoming, () => {}); + const session = [...pool.entries.values()][0]!; + let replacementOwned = false; + let prematurelyDone = false; + const sendInput = session.sendInput.bind(session); + session.sendInput = async (queryId, text) => { + prematurelyDone = emitted.some(e => e.type === "done"); + replacementOwned = !!currentTurn(session); + await sendInput(queryId, text); + }; + // resolveHeldToolResult queues the old completion before interrupt resolves. The replacement + // receives its own completion only after sendInput observes whether its owner survived. + session.capture = false; + await adapter.runTurn!(parsed("caller-A"), incoming, e => emitted.push(e)); + expect(prematurelyDone).toBe(false); + expect(replacementOwned).toBe(true); + expect(session.inputs.map(input => input.queryId)).toEqual(["q_1", "q_2"]); + expect(emitted.filter(e => e.type === "done")).toHaveLength(1); + // A later replay of the old completion still cannot produce a second terminal event. + handleRuntimeEvent(session, event("q_1", { type: "status", status: "turn_complete" })); + expect(emitted.filter(e => e.type === "done")).toHaveLength(1); + } finally { await pool.closeAll(); } +}); + +test("a cancelled queued turn leaves the shared session available without sending a query", async () => { + const pool = host(); + const adapter = createStepCliAdapter(provider, { openSession: pool }); + const request = parsed("queued-caller"); + const handle = ownedConversationHandle(request, incoming, provider)!; + await pool.open({ handle, sessionId: "" }); + const session = pool.entries.get(handle)!; + session.capture = false; + const entered = Promise.withResolvers(); + const release = Promise.withResolvers(); + const owner = withConversationLock(handle, () => { entered.resolve(); return release.promise; }); + const controller = new AbortController(); + const events: AdapterEvent[] = []; + try { + await entered.promise; + const queued = adapter.runTurn!(request, { ...incoming, abortSignal: controller.signal }, e => events.push(e)); + await new Promise(resolve => setImmediate(resolve)); + controller.abort(); + release.resolve(); + await queued; + expect(session.next).toBe(0); + expect(session.inputs).toEqual([]); + expect(events).toEqual([{ type: "error", message: "StepCode turn was aborted before start.", retryable: false }]); + expect(session.closed).toBe(false); + + const next: AdapterEvent[] = []; + await adapter.runTurn!(request, incoming, e => next.push(e)); + expect(next.filter(e => e.type === "done")).toHaveLength(1); + } finally { + release.resolve(); + await owner; + await pool.closeAll(); + } +}); + +test.each(["busy retry", "input"] as const)("cancellation before query %s prevents further dispatch", async phase => { + const pool = host(); + const adapter = createStepCliAdapter(provider, { openSession: pool }); + const request = parsed("dispatch-caller"); + const handle = ownedConversationHandle(request, incoming, provider)!; + await pool.open({ handle, sessionId: "" }); + const session = pool.entries.get(handle)!; + session.capture = false; + const controller = new AbortController(); + const start = session.startQuery.bind(session); + let starts = 0; + session.startQuery = async () => { + starts++; + if (starts === 1) { + controller.abort(); + if (phase === "busy retry") throw new StepSessionError("inert query busy", "step_cli_session_busy"); + } + return start(); + }; + const events: AdapterEvent[] = []; + try { + await adapter.runTurn!(request, { ...incoming, abortSignal: controller.signal }, e => events.push(e)); + expect(starts).toBe(1); + expect(session.inputs).toEqual([]); + expect(events.map(e => e.type)).toEqual(["error"]); + expect(session.closed).toBe(phase === "input"); + } finally { + await pool.closeAll(); + } +}); diff --git a/tests/adapters/step-cli-run-turn.test.ts b/tests/adapters/step-cli-run-turn.test.ts new file mode 100644 index 00000000000..83f54f91421 --- /dev/null +++ b/tests/adapters/step-cli-run-turn.test.ts @@ -0,0 +1,1000 @@ +import { describe, expect, test } from "bun:test"; +import type { ChildProcess } from "node:child_process"; +import { EventEmitter } from "node:events"; +import { PassThrough } from "node:stream"; + +import { clearStepCliSessions, createStepCliAdapter } from "../../src/adapters/step-cli/adapter"; +import { withConversationLock } from "../../src/adapters/step-cli/conversation"; +import { handleReverseRequest, handleRuntimeEvent } from "../../src/adapters/step-cli/events"; +import { classifyStepChildError } from "../../src/adapters/step-cli/errors"; +import { latestToolResult, projectToolResultContent } from "../../src/adapters/step-cli/projection"; +import type { + StepConversationHost, + StepConversationRef, + StepConversationSession, + StepHeldTool, +} from "../../src/adapters/step-cli/session-pool"; +import { + encodeStepFrame, + STEP_PROTOCOL_NAME, + STEP_PROTOCOL_VERSION, + StepFrameDecoder, + stepResponse, + type StepFrame, +} from "../../src/adapters/step-cli/stdio-frames"; +import { + didRunOptionalShutdownHooks, + resetOptionalShutdownHooksForTests, + runOptionalShutdownHooks, +} from "../../src/lib/optional-shutdown-hooks"; +import type { AdapterEvent, OcxParsedRequest } from "../../src/types"; + +/** + * A fake StepCode process. + * + * It exists so these tests drive the REAL `handleReverseRequest`, the REAL `handleRuntimeEvent` and + * the REAL `runTurn`. The previous round's defects all lived in code the suite never executed, and a + * mirror-based test would have passed just as happily over them — so nothing here reimplements the + * behaviour under test. + */ +class FakeSession implements StepConversationSession { + sessionId = "sess-1"; + closed = false; + handshakeCount = 0; + readonly allowed: string[] = []; + readonly denied: Array<{ id: string; reason: string }> = []; + readonly refused: Array<{ id: string; reason: string }> = []; + readonly delivered: Array<{ id: string; result: unknown }> = []; + readonly queries: Array<{ queryId: string; model?: string; sdkTools: unknown[] }> = []; + readonly inputs: Array<{ queryId: string; text: string }> = []; + readonly interrupts: string[] = []; + readonly inputEnds: string[] = []; + /** Frames the fake streams once a turn is under way, in order. */ + stream: StepFrame[] = []; + #n = 0; + + /** Deliver a frame immediately, standing in for the CLI streaming it at this moment. */ + emitNow(frame: StepFrame): void { + const payload = frame.payload as Record; + frame = { ...frame, sessionId: this.sessionId, payload: frame.kind === "request" + ? payload + : { queryId: `q_${this.#n}`, message: payload } }; + if (frame.kind === "request") handleReverseRequest(this, frame); + else handleRuntimeEvent(this, frame); + } + + async handshake(): Promise { + this.handshakeCount += 1; + return { + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "response", + id: "r", + replyTo: "init", + payload: {}, + }; + } + + async startQuery(options: { model?: string; sdkTools: unknown[] }): Promise<{ queryId: string; sessionId: string }> { + this.#n += 1; + const queryId = `q_${this.#n}`; + this.queries.push({ queryId, model: options.model, sdkTools: options.sdkTools }); + this.#flush(); + return { queryId, sessionId: this.sessionId }; + } + + async sendInput(queryId: string, text: string): Promise { + this.inputs.push({ queryId, text }); + this.#flush(); + } + + async interrupt(queryId: string): Promise { + this.interrupts.push(queryId); + } + + async endInput(queryId: string): Promise { + this.inputEnds.push(queryId); + } + + async close(): Promise { + this.closed = true; + } + + allowPermission(frame: StepFrame): void { + this.allowed.push(frame.id); + } + + denyPermission(frame: StepFrame, reason: string): void { + this.denied.push({ id: frame.id, reason }); + } + + refuseToolCall(frame: StepFrame, reason: string): void { + this.refused.push({ id: frame.id, reason }); + } + + resolveHeldToolResult(frame: StepFrame, result: unknown): boolean { + this.delivered.push({ id: frame.id, result }); + this.#flush(); + return true; + } + + /** + * Stream the queued frames after the current stack unwinds. + * + * The adapter registers the turn around the dispatch that reaches here, so a synchronous delivery + * would arrive before there is a turn to deliver to — a race a real subprocess never has. + */ + #flush(): void { + const queued = this.stream.splice(0, this.stream.length); + if (queued.length === 0) return; + setTimeout(() => { + for (const f of queued) { + // Dispatch the way the real session does: reverse requests go to the reverse handler, events + // to the event handler. The DECISIONS under test stay in the real functions. + this.emitNow(f); + } + }, 0); + } +} + +function requestFrame(id: string, method: string, payload: Record = {}): StepFrame { + return { protocol: STEP_PROTOCOL_NAME, version: STEP_PROTOCOL_VERSION, kind: "request", id, method, payload }; +} + +function eventFrame(payload: Record): StepFrame { + return { + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "event", + id: "evt", + method: "query.message", + sequence: 1, + payload, + }; +} + +const TURN_COMPLETE = eventFrame({ type: "status", status: "turn_complete" }); + +/** The pool bookkeeping the adapter uses, so the tests exercise `rememberHeldTool`/`takeHeldTool`. */ +function host(session: FakeSession): StepConversationHost & { ref: StepConversationRef } { + const ref: StepConversationRef = { handle: "conv-1", sessionId: "sess-1" }; + const held = new Map(); + return { + ref, + get: () => session, + open: async () => session, + nextRef: () => ({ handle: "conv-next", sessionId: "" }), + rememberHeldTool: (target, value) => { + held.set(target.handle, value); + }, + takeHeldTool: target => { + const value = held.get(target.handle); + held.delete(target.handle); + return value; + }, + closeAll: async () => {}, + }; +} + +function provider() { + return { + adapter: "step-cli", + baseUrl: "https://api.stepfun.com/step_plan", + authMode: "key", + } as never; +} + +const THREAD_META = { headers: new Headers({ "thread-id": "conv-1" }) } as never; + +function parsed(messages: unknown[]): OcxParsedRequest { + return { + modelId: "step-5-preview", + context: { + messages, + tools: [{ name: "shell", description: "run", parameters: { type: "object" } }], + }, + options: {}, + _reasoningReplayScope: { clientPrincipalId: "test-caller", clientThreadId: "conv-1" }, + } as unknown as OcxParsedRequest; +} + +const USER_ASK = [{ role: "user", content: "run it", timestamp: 0 }]; + +describe("StepCode reverse requests are always answered", () => { + test("a permission request with no turn is denied", () => { + const session = new FakeSession(); + handleReverseRequest(session, requestFrame("p1", "permission.request")); + expect(session.allowed).toEqual([]); + expect(session.denied.map(entry => entry.id)).toEqual(["p1"]); + }); + + test("a tool call with no turn is refused, never dropped", () => { + // Regression: every branch used to `return` when no turn was registered, so the runtime waited out + // its own window with no answer and no diagnostic. + const session = new FakeSession(); + handleReverseRequest(session, requestFrame("t1", "sdk_tool.invoke", { serverName: "ocx", toolName: "shell" })); + expect(session.refused.map(entry => entry.id)).toEqual(["t1"]); + expect(session.refused[0]?.reason).toMatch(/not expecting a tool call/i); + }); + + test("an unknown reverse method is denied rather than ignored", () => { + const session = new FakeSession(); + handleReverseRequest(session, requestFrame("x1", "some.future.method")); + expect(session.denied.map(entry => entry.id)).toEqual(["x1"]); + }); + + test("an expired hold is refused and never re-dispatched", () => { + const session = new FakeSession(); + handleReverseRequest(session, requestFrame("t2", "sdk_tool.invoke", { __expired: true })); + expect(session.refused.map(entry => entry.id)).toEqual(["t2"]); + // The client already received this call, so a second dispatch for the same id would duplicate it. + expect(session.allowed).toEqual([]); + expect(session.denied).toEqual([]); + }); +}); + +describe("StepCode runTurn, two turns through one conversation", () => { + test("turn 1 declares the client's tools and ends the turn on a captured call", async () => { + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + const events: AdapterEvent[] = []; + // The CLI asks permission, calls the tool, and waits for the result: the call is held, so the turn + // ends with the client's `tool_call` rather than waiting for the model to finish. + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", + toolName: "shell", + input: { cmd: "echo LIVE_BRIDGE_OK" }, + toolUseId: "call-9", timeoutMs: 120_000, + }), + TURN_COMPLETE, // Lets a rejected callback fail assertions without waiting for the turn timeout. + ]; + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, event => events.push(event)); + + expect(session.queries[0]?.sdkTools).toEqual([ + expect.objectContaining({ serverName: "ocx", toolName: "shell", description: "run" }), + ]); + expect(session.queries[0]?.model).toBe("step-5-preview"); + expect(session.allowed).toEqual(["req_101"]); + // The client regains tool ownership: the call is reported, and nothing is executed in StepCode. + const kinds = events.map(event => event.type); + expect(kinds).toContain("tool_call_start"); + expect(kinds).toContain("tool_call_end"); + expect(events.find(event => event.type === "done")).toMatchObject({ stopReason: "tool_use" }); + expect(session.delivered).toHaveLength(0); + }); + + test("turn 2 with the matching result continues the same query", async () => { + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", + toolName: "shell", + input: { cmd: "echo LIVE_BRIDGE_OK" }, + toolUseId: "call-9", timeoutMs: 120_000, + }), + ]; + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, () => {}); + + const second: AdapterEvent[] = []; + session.stream = [ + eventFrame({ type: "stream_event", event: { delta: { type: "text_delta", text: "Output: OK" } } }), + TURN_COMPLETE, + ]; + await adapter.runTurn!( + parsed([ + ...USER_ASK, + { role: "toolResult", toolCallId: "call-9", toolName: "shell", content: "LIVE_BRIDGE_OK", isError: false, timestamp: 1 }, + ]), + THREAD_META, + event => second.push(event), + ); + + // The result is delivered to the HELD call, and the model continues in the same query: no second + // query, no interrupt, and the user's question is not re-prompted. + expect((session.delivered[0]?.result as { content: Array<{ text: string }> }).content[0]?.text).toBe( + "LIVE_BRIDGE_OK", + ); + expect(session.queries).toHaveLength(1); + expect(session.interrupts).toEqual([]); + expect(session.inputs).toHaveLength(1); + expect(second.map(event => event.type)).toContain("text_delta"); + expect(second.find(event => event.type === "done")).toMatchObject({ stopReason: "stop" }); + }); + + test("turn 2 that does NOT answer the held call refuses it and keeps the user's message", async () => { + // Regression: the code set `continuedQuery = true` whenever a held call existed, so a client that + // sent a new user message instead of the result had that message swallowed and its request + // answered with `step_cli_turn_abandoned`. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", + toolName: "shell", + input: { cmd: "echo LIVE_BRIDGE_OK" }, + toolUseId: "call-9", timeoutMs: 120_000, + }), + ]; + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, () => {}); + + const second: AdapterEvent[] = []; + session.stream = [TURN_COMPLETE]; + await adapter.runTurn!( + parsed([ + ...USER_ASK, + { role: "toolResult", toolCallId: "call-SOMEONE-ELSE", toolName: "shell", content: "stale", isError: false, timestamp: 1 }, + { role: "user", content: "actually do this instead", timestamp: 2 }, + ]), + THREAD_META, + event => second.push(event), + ); + + // Released as a refusal rather than somebody else's result. + expect((session.delivered[0]?.result as { isError?: boolean }).isError).toBe(true); + // The abandoned query is interrupted so a new one can start, and the user's text still goes out. + expect(session.interrupts).toEqual(["q_1"]); + expect(session.queries).toHaveLength(2); + expect(session.inputs.at(-1)?.text).toContain("actually do this instead"); + }); + + test("an identity-less request is not routed onto the conversation host's own handle", async () => { + const session = new FakeSession(); + const conversation = host(session); + const adapter = createStepCliAdapter(provider(), { openSession: conversation }); + session.stream = [TURN_COMPLETE]; + await adapter.runTurn!( + parsed(USER_ASK), + { headers: new Headers() } as never, + () => {}, + ); + // Regression: a request with no identity used to resolve to the shared string "default", so every + // such client shared one StepCode process. It now gets a private conversation. + expect(conversation.ref.handle).toBe("conv-1"); + expect(session.queries).toHaveLength(1); + }); +}); + +describe("StepCode query lifecycle", () => { + test("a completed turn ends the query's input so the next turn can start", async () => { + // StepCode's `#maybeFinish` refuses to finish a query whose input has not ended, so without this the + // runtime's single query slot is never released and the NEXT query.start fails with SESSION_BUSY. + // Measured on the real CLI before the fix: a second turn on the same conversation failed. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [eventFrame({ type: "stream_event", event: { delta: { type: "text_delta", text: "hi" } } }), TURN_COMPLETE]; + const events: AdapterEvent[] = []; + await adapter.runTurn!( + parsed([{ role: "user", content: "first", timestamp: 0 }]), + THREAD_META, + event => events.push(event), + ); + expect(events.find(event => event.type === "done")).toMatchObject({ stopReason: "stop" }); + await Bun.sleep(5); + expect(session.inputEnds).toEqual(["q_1"]); + }); + + test("a captured tool call keeps its query open for the result", async () => { + // The opposite requirement: ending the input here would let the runtime finish the query before the + // client's tool result arrives, and the model would never see it. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", + toolName: "shell", + input: { cmd: "echo ok" }, + toolUseId: "call-9", timeoutMs: 120_000, + }), + ]; + await adapter.runTurn!( + parsed([{ role: "user", content: "first", timestamp: 0 }]), + THREAD_META, + () => {}, + ); + await Bun.sleep(5); + expect(session.inputEnds).toEqual([]); + }); + + test("two text turns on one conversation both run", async () => { + // The plain multi-turn text conversation is what the missing input_end broke; it is not a tool path. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [ + eventFrame({ type: "stream_event", event: { delta: { type: "text_delta", text: "one" } } }), + TURN_COMPLETE, + ]; + await adapter.runTurn!(parsed([{ role: "user", content: "first", timestamp: 0 }]), THREAD_META, () => {}); + session.stream = [ + eventFrame({ type: "stream_event", event: { delta: { type: "text_delta", text: "two" } } }), + TURN_COMPLETE, + ]; + const second: AdapterEvent[] = []; + await adapter.runTurn!( + parsed([ + { role: "user", content: "first", timestamp: 0 }, + { role: "assistant", content: "one", timestamp: 1 }, + { role: "user", content: "second", timestamp: 2 }, + ]), + THREAD_META, + event => second.push(event), + ); + expect(session.queries).toHaveLength(2); + expect(second.some(event => event.type === "done")).toBe(true); + expect(second.some(event => event.type === "error")).toBe(false); + }); +}); + +describe("StepCode concurrent turns on one conversation", () => { + test("two overlapping turns are serialised instead of corrupting each other", async () => { + // Measured against the real CLI before the fix: two concurrent requests on one `thread-id` both + // failed — one with SESSION_NOT_FOUND, the other with step_cli_session_closed — because this + // proxy's turn state is keyed by the single process StepCode serves one query from. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = []; + const firstEvents: AdapterEvent[] = []; + const first = adapter.runTurn!(parsed(USER_ASK), THREAD_META, event => firstEvents.push(event)); + + // Let the first turn take the conversation, then overlap a second request on it. + await Bun.sleep(10); + expect(session.queries).toHaveLength(1); + + const secondEvents: AdapterEvent[] = []; + session.stream = [TURN_COMPLETE]; + const second = adapter.runTurn!( + parsed([{ role: "user", content: "second", timestamp: 9 }]), + THREAD_META, + event => secondEvents.push(event), + ); + + // While the first turn still owns the conversation, the second must not have started a query. + await Bun.sleep(10); + expect(session.queries).toHaveLength(1); + + // Release the first; the second then runs on the same conversation. + session.emitNow(TURN_COMPLETE); + await Promise.all([first, second]); + + expect(firstEvents.some(event => event.type === "done")).toBe(true); + expect(secondEvents.some(event => event.type === "done")).toBe(true); + // Neither turn ended in a failure event, which is what the pre-fix run produced twice. + expect(firstEvents.some(event => event.type === "error")).toBe(false); + expect(secondEvents.some(event => event.type === "error")).toBe(false); + expect(session.queries).toHaveLength(2); + }); + + test("sequential turns on one conversation are not serialised against each other needlessly", async () => { + // Regression guard on the lock itself: the common Codex flow is one request at a time, and the + // second turn must deliver a held result without waiting behind anything. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", + toolName: "shell", + input: { cmd: "echo ok" }, + toolUseId: "call-9", timeoutMs: 120_000, + }), + ]; + // Awaited deliberately: the fake drains `stream` when it flushes, so queuing the next turn's + // frames before this one has settled would hand them to the wrong turn. + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, () => {}); + session.stream = [TURN_COMPLETE]; + const second = adapter.runTurn!( + parsed([ + ...USER_ASK, + { role: "toolResult", toolCallId: "call-9", toolName: "shell", content: "ok", isError: false, timestamp: 1 }, + ]), + THREAD_META, + () => {}, + ); + await second; + expect(session.queries).toHaveLength(1); + }); +}); + +describe("StepCode query start retries", () => { + test("a busy runtime is retried rather than failing the turn", async () => { + // Measured on the real CLI: a turn settles when the CLI reports `turn_complete`, which can precede + // the runtime freeing its single query slot, so the next request failed with SESSION_BUSY. + const session = new FakeSession(); + let attempts = 0; + const original = session.startQuery.bind(session); + session.startQuery = async options => { + attempts += 1; + if (attempts < 3) { + throw classifyStepChildError({ code: "SESSION_BUSY", message: "the runtime serves one query at a time" }); + } + return original(options); + }; + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [TURN_COMPLETE]; + await adapter.runTurn!( + parsed([{ role: "user", content: "hello", timestamp: 0 }]), + THREAD_META, + () => {}, + ); + expect(attempts).toBe(3); + expect(session.inputs).toHaveLength(1); + }); + + test("a non-busy failure is not retried", async () => { + const session = new FakeSession(); + let attempts = 0; + session.startQuery = async () => { + attempts += 1; + throw new Error("synthetic child diagnostic"); + }; + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + const events: AdapterEvent[] = []; + await adapter.runTurn!( + parsed([{ role: "user", content: "hello", timestamp: 0 }]), + THREAD_META, + event => events.push(event), + ); + expect(attempts).toBe(1); + expect(events).toMatchObject([{ + type: "error", code: "step_cli_session_failed", message: "StepCode could not complete the request.", + }]); + }); + + test("a child permission-denial event emits only the local description", async () => { + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + const events: AdapterEvent[] = []; + session.stream = [eventFrame({ type: "permission_denied", message: "synthetic child permission detail" })]; + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, event => events.push(event)); + expect(events).toMatchObject([{ + type: "error", code: "step_cli_permission_denied", message: "StepCode refused a tool call.", + }]); + }); +}); + +describe("StepCode tool-catalog ceiling", () => { + test("an oversized catalog names the count and the shared ceiling", async () => { + // Measured against a real Codex 0.162.0 client: 1749 declared tools / 2.5 MB, because Codex + // flattens every MCP server's tools into the function catalog. The shared CLI-family ceiling is + // 128 tools, the same bound `qoder`, `codebuddy` and `claude-cli` enforce — so the message has to + // say "too many, and this is the family limit", not just "invalid". + const many = Array.from({ length: 200 }, (_, index) => ({ + name: `tool_${index}`, + description: "x", + parameters: { type: "object" }, + })); + const adapter = createStepCliAdapter(provider(), { openSession: host(new FakeSession()) }); + const events: AdapterEvent[] = []; + await adapter.runTurn!( + { + modelId: "step-5-preview", + context: { messages: [{ role: "user", content: "go", timestamp: 0 }], tools: many }, + options: {}, + } as unknown as OcxParsedRequest, + THREAD_META, + event => events.push(event), + ); + const error = events.find(event => event.type === "error") as { message?: string } | undefined; + expect(error?.message).toMatch(/declares 200 tools/); + expect(error?.message).toMatch(/128-tool ceiling/); + expect(error?.message).toMatch(/CLI-backed provider shares/); + }); +}); + +describe("StepCode session teardown on proxy shutdown", () => { + test("a stopped proxy closes the StepCode processes it still owns", async () => { + resetOptionalShutdownHooksForTests(); + const child = Object.assign(new EventEmitter(), { + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + exitCode: null as number | null, signalCode: null, + kill() { + this.exitCode = 0; + this.emit("close", 0, null); + return true; + }, + }); + const responses: Record = { + initialize: { runtimeVersion: "step", selectedProtocol: 1, capabilities: ["streaming-input", "sdk-tools"] }, + "query.start": { queryId: "q_1", sessionId: "sess_1" }, + "query.input": { accepted: true }, + "query.input_end": {}, + }; + const decoder = new StepFrameDecoder(); + child.stdin.on("data", (chunk: Buffer) => { + for (const frame of decoder.push(chunk)) { + child.stdout.write(encodeStepFrame(stepResponse(frame.id, responses[frame.method ?? ""]))); + if (frame.method === "query.input") { + child.stdout.write(encodeStepFrame({ + ...TURN_COMPLETE, payload: { queryId: "q_1", message: TURN_COMPLETE.payload }, + })); + } + } + }); + const adapter = createStepCliAdapter(provider(), { + spawn: () => child as unknown as ChildProcess, + which: () => process.execPath, + }); + try { + const events: AdapterEvent[] = []; + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, event => events.push(event)); + expect(events.some(event => event.type === "done")).toBe(true); + expect(child.exitCode).toBeNull(); + expect(didRunOptionalShutdownHooks()).toBe(false); + expect(await runOptionalShutdownHooks()).toBe(true); + expect(child.exitCode).toBe(0); + expect(didRunOptionalShutdownHooks()).toBe(true); + } finally { + try { await clearStepCliSessions(); } + finally { resetOptionalShutdownHooksForTests(); } + } + }); +}); + +describe("StepCode tool-result content projection", () => { + const PNG = + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + + test("text passes through unchanged", () => { + expect(projectToolResultContent("hello")).toEqual([{ type: "text", text: "hello" }]); + }); + + test("an inline image is forwarded as base64 with its media type", () => { + // Codex's `view_image` returns an image part. StepCode's SDK tool takes + // `{type:"image", data, mimeType}`, so a `data:` URL has to be split rather than inlined as text. + expect(projectToolResultContent([{ type: "image", imageUrl: PNG }])).toEqual([ + { + type: "image", + data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", + mimeType: "image/png", + }, + ]); + }); + + test("text and an image travel together in order", () => { + expect( + projectToolResultContent([{ type: "text", text: "before" }, { type: "image", imageUrl: PNG }]), + ).toEqual([ + { type: "text", text: "before" }, + { type: "image", data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", mimeType: "image/png" }, + ]); + }); + + test("a remote image becomes an actionable note instead of vanishing", () => { + // StepCode cannot fetch a URL, and dropping it would leave the model believing the tool returned + // nothing at all — the same misleading-empty-result failure as a mismatched call. + const blocks = projectToolResultContent([{ type: "image", imageUrl: "https://example.invalid/a.png" }]); + expect(blocks).toHaveLength(1); + expect(blocks[0]?.type).toBe("text"); + expect(String(blocks[0]?.text)).toMatch(/could not be inlined/); + }); + + test("a result with no readable part says so rather than looking empty", () => { + expect(projectToolResultContent([{ type: "video", videoUrl: "https://example.invalid/v" }])).toEqual([ + { type: "text", text: "a video result part was dropped" }, + ]); + expect(projectToolResultContent([])).toEqual([ + { type: "text", text: "the tool returned no readable content" }, + ]); + }); +}); + +describe("StepCode conversation queue", () => { + test("turns on one conversation run in arrival order", async () => { + const order: number[] = []; + const slow = async (label: number, ms: number) => { + await Bun.sleep(ms); + order.push(label); + return label; + }; + const first = withConversationLock("c", () => slow(1, 20)); + const second = withConversationLock("c", () => slow(2, 1)); + const third = withConversationLock("c", () => slow(3, 1)); + await Promise.all([first, second, third]); + expect(order).toEqual([1, 2, 3]); + }); + + test("different conversations do not wait on each other", async () => { + let running = 0; + let peak = 0; + const body = async () => { + running += 1; + peak = Math.max(peak, running); + await Bun.sleep(10); + running -= 1; + }; + await Promise.all([withConversationLock("a", body), withConversationLock("b", body)]); + expect(peak).toBe(2); + }); + + test("a pile-up past the cap is refused instead of queued forever", async () => { + // The refusal is the only thing standing between a retry storm and an unbounded wait, so it has to + // be a refusal rather than another queue slot: the holder plus MAX_QUEUED_TURNS waiters are + // admitted, and the next caller is turned away. + let release!: () => void; + const gate = new Promise(resolve => { + release = resolve; + }); + const held = withConversationLock("busy", () => gate); + await Bun.sleep(5); // let the holder register + + const accepted = [ + withConversationLock("busy", async () => undefined), + withConversationLock("busy", async () => undefined), + ]; + const refused = withConversationLock("busy", async () => undefined).catch(error => error); + + const outcome = await refused; + expect(outcome).toBeInstanceOf(Error); + expect(String((outcome as Error).message)).toMatch(/one turn per conversation at a time/); + + release(); + await Promise.all([held, ...accepted]); + }); +}); + +describe("StepCode abandoned-turn recovery", () => { + /** + * A terminal deadline the test fires by hand, so the "CLI went quiet" path is driven without + * waiting ten minutes and without depending on wall-clock timing. + */ + function manualTimers() { + const pending: Array<() => void> = []; + return { + setTimeout: ((fn: () => void) => { + pending.push(fn); + return pending.length as unknown as ReturnType; + }) as unknown as typeof setTimeout, + clearTimeout: (() => {}) as unknown as typeof clearTimeout, + armed: () => pending.length, + fire: () => { + for (const fn of pending.splice(0, pending.length)) fn(); + }, + }; + } + + /** Wait for the turn to reach its terminal deadline, rather than assuming a fixed sleep is enough. */ + async function untilArmed(timers: ReturnType): Promise { + for (let attempt = 0; attempt < 200 && timers.armed() === 0; attempt += 1) await Bun.sleep(1); + } + + function expectRecovered(events: AdapterEvent[], session: FakeSession): void { + const error = events.find(event => event.type === "error") as { code?: string } | undefined; + // The client has to be told: a stream that just stops is indistinguishable from a hung proxy. + expect(error?.code).toBe("step_cli_turn_abandoned"); + // StepCode serves one query per process, so a query left running makes every later request for + // this conversation collide with it. Interrupting is what stops the bleed. + expect(session.interrupts).toEqual(["q_1"]); + // And the process itself is released, rather than held for a conversation that just failed. + expect(session.closed).toBe(true); + } + + test("a client abort interrupts the query and closes the session", async () => { + // Regression: the guard deciding "nothing terminated this turn" was written as + // `!currentTurn(session) !== undefined`. `!x` is ALWAYS a boolean and a boolean is never + // `undefined`, so the comparison was always true and the whole recovery block below it was dead + // code — the exact opposite of the refactor that introduced it. Every one of the existing tests + // passed over it, because on the happy path a terminal event ends the turn first and the + // distinction is invisible. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + // No frames: the CLI accepts the query and then says nothing, forever. + session.stream = []; + + const controller = new AbortController(); + const events: AdapterEvent[] = []; + const turn = adapter.runTurn!( + parsed(USER_ASK), + { headers: new Headers({ "thread-id": "conv-1" }), abortSignal: controller.signal } as never, + event => events.push(event), + ); + + await Bun.sleep(10); + expect(session.queries).toHaveLength(1); + controller.abort(); + await turn; + + expectRecovered(events, session); + }); + + test("the terminal deadline recovers the same way when no abort arrives", async () => { + const session = new FakeSession(); + const timers = manualTimers(); + const adapter = createStepCliAdapter(provider(), { + openSession: host(session), + setTimeout: timers.setTimeout, + clearTimeout: timers.clearTimeout, + }); + session.stream = []; + + const events: AdapterEvent[] = []; + const turn = adapter.runTurn!(parsed(USER_ASK), THREAD_META, event => events.push(event)); + + await untilArmed(timers); + expect(session.queries).toHaveLength(1); + timers.fire(); + await turn; + + expectRecovered(events, session); + }); + + test("a normally completed turn is not treated as abandoned", async () => { + // The other direction: the recovery must not fire on the path that already produced a terminal + // event, or every successful turn would interrupt its own query and drop the conversation. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [TURN_COMPLETE]; + const events: AdapterEvent[] = []; + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, event => events.push(event)); + await Bun.sleep(5); + expect(events.some(event => event.type === "done")).toBe(true); + expect(events.some(event => event.type === "error")).toBe(false); + expect(session.interrupts).toEqual([]); + expect(session.closed).toBe(false); + }); +}); + +describe("StepCode held-result delivery ordering", () => { + test("a turn is registered before the tool result unblocks the CLI", async () => { + // The CLI may answer the instant it receives a tool result. Delivering the result before + // registering the turn drops those frames — no runtime to route them to — and the turn then waits + // out its deadline on a model that already answered. The fake delivers synchronously inside + // `resolveHeldToolResult` so the race is deterministic rather than timing-dependent. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", + toolName: "shell", + input: { cmd: "echo ok" }, + toolUseId: "call-9", timeoutMs: 120_000, + }), + ]; + await adapter.runTurn!( + parsed([{ role: "user", content: "go", timestamp: 0 }]), + THREAD_META, + () => {}, + ); + expect(session.queries).toHaveLength(1); + + // Second turn: answering the held call makes the fake emit the completion SYNCHRONOUSLY, inside + // the delivery call, before `resolveHeldToolResult` returns. + const original = session.resolveHeldToolResult.bind(session); + session.resolveHeldToolResult = (frame, result) => { + const out = original(frame, result); + session.emitNow(eventFrame({ type: "status", status: "turn_complete" })); + return out; + }; + session.stream = []; + const second: AdapterEvent[] = []; + const settled = adapter.runTurn!( + parsed([ + { role: "user", content: "go", timestamp: 0 }, + { role: "toolResult", toolCallId: "call-9", toolName: "shell", content: "ok", isError: false, timestamp: 1 }, + ]), + THREAD_META, + event => second.push(event), + ); + // The completion arrived during delivery, so it must already be recorded rather than lost. + await Bun.sleep(5); + expect(second.some(event => event.type === "done")).toBe(true); + await settled; + expect(second.some(event => event.type === "done")).toBe(true); + expect(second.some(event => event.type === "error")).toBe(false); + }); +}); + +describe("StepCode turn ownership", () => { + function captureCall(session: FakeSession): void { + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", + toolName: "shell", + input: { cmd: "echo LIVE_BRIDGE_OK" }, + toolUseId: "call-9", timeoutMs: 120_000, + }), + ]; + } + + test("a held call followed by user text with no tool result is refused and the text still runs", async () => { + // Regression: `heldResult!.toolCallId` dereferenced an undefined result when the transcript had no + // toolResult at all, so a client that cancelled its first tool and typed a new message threw before + // the held frame was released, and the outer catch misreported it as conversation_busy. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + captureCall(session); + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, () => {}); + + const second: AdapterEvent[] = []; + session.stream = [TURN_COMPLETE]; + await adapter.runTurn!( + parsed([...USER_ASK, { role: "user", content: "never mind, do this", timestamp: 2 }]), + THREAD_META, + event => second.push(event), + ); + + expect(second.some(event => event.type === "error")).toBe(false); + expect(second.find(event => event.type === "done")).toMatchObject({ stopReason: "stop" }); + expect(session.delivered).toHaveLength(1); + expect(session.delivered[0]?.id).toBe("req_102"); + expect((session.delivered[0]?.result as { isError?: boolean }).isError).toBe(true); + expect(session.interrupts).toEqual(["q_1"]); + expect(session.queries).toHaveLength(2); + expect(session.inputs.at(-1)?.text).toContain("never mind, do this"); + expect(session.closed).toBe(false); + }); + + test("a turn refused at the queue cap leaves the active turn and the accepted queue intact", async () => { + // Regression: the cap refusal shared a catch with post-ownership failures and closed the session + // unconditionally, disconnecting the turn that owned it and every caller already queued behind it. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + const ask = (text: string) => parsed([{ role: "user", content: text, timestamp: 0 }]); + + session.stream = []; + const activeEvents: AdapterEvent[] = []; + const active = adapter.runTurn!(ask("active"), THREAD_META, event => activeEvents.push(event)); + await Bun.sleep(10); + expect(session.queries).toHaveLength(1); + + const queuedEvents: AdapterEvent[][] = [[], []]; + const queued = queuedEvents.map((events, index) => + adapter.runTurn!(ask(`queued-${index}`), THREAD_META, event => events.push(event)), + ); + await Bun.sleep(10); + + const rejectedEvents: AdapterEvent[] = []; + await adapter.runTurn!(ask("rejected"), THREAD_META, event => rejectedEvents.push(event)); + expect(rejectedEvents).toEqual([ + expect.objectContaining({ type: "error", status: 409, code: "step_cli_conversation_busy", retryable: true }), + ]); + // The refusal touched nothing the accepted turns depend on. + expect(session.closed).toBe(false); + expect(session.queries).toHaveLength(1); + expect(session.interrupts).toEqual([]); + + // Drain: the active turn, then each queued turn in arrival order, all on the same open session. + for (let turn = 0; turn < 3; turn += 1) { + session.emitNow(TURN_COMPLETE); + await Bun.sleep(10); + } + await Promise.all([active, ...queued]); + + for (const events of [activeEvents, ...queuedEvents]) { + expect(events.some(event => event.type === "done")).toBe(true); + expect(events.some(event => event.type === "error")).toBe(false); + } + expect(session.queries).toHaveLength(3); + expect(session.inputs.map(input => input.text.includes("rejected"))).toEqual([false, false, false]); + expect(session.closed).toBe(false); + }); +}); diff --git a/tests/adapters/step-cli-session.test.ts b/tests/adapters/step-cli-session.test.ts new file mode 100644 index 00000000000..184d95a9ed5 --- /dev/null +++ b/tests/adapters/step-cli-session.test.ts @@ -0,0 +1,438 @@ +import { EventEmitter } from "node:events"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PassThrough } from "node:stream"; +import { describe, expect, test } from "bun:test"; + +import { StepSessionPool } from "../../src/adapters/step-cli/session-pool"; +import { + StepCliSession, + StepSessionError, + type StepSessionDeps, + type StepSessionEvent, + type StepSessionOptions, +} from "../../src/adapters/step-cli/session"; +import { encodeStepFrame, STEP_PROTOCOL_NAME, STEP_PROTOCOL_VERSION, type StepFrame } from "../../src/adapters/step-cli/stdio-frames"; + +const CAPABILITIES = ["streaming-input", "sdk-tools", "permission-callback", "hooks", "sessions"]; + +/** + * A scripted `step --sdk-stdio` peer. + * + * It decodes what the adapter writes and answers from a script, which is the only way to assert the + * turn loop — permission hand-off, tool capture, the held reverse request and the result that + * releases it — without a real CLI, a real model call or a sleep. + */ +class FakeStep { + readonly child: EventEmitter & { + stdin: PassThrough & { writable: boolean }; + stdout: PassThrough; + stderr: PassThrough; + exitCode: number | null; + signalCode: NodeJS.Signals | null; + killed: string[]; + kill(signal?: string): boolean; + }; + /** Every frame the adapter wrote, append-only, so assertions can inspect the whole conversation. */ + readonly written: StepFrame[] = []; + /** Index of the next frame the scripted peer has not answered yet. */ + #scriptCursor = 0; + #buffer = Buffer.alloc(0); + /** When false the peer stays silent, so a test can drive the exchange by hand. */ + scripted = true; + + constructor() { + const stdin = new PassThrough() as PassThrough & { writable: boolean }; + this.child = Object.assign(new EventEmitter(), { + stdin, + stdout: new PassThrough(), + stderr: new PassThrough(), + exitCode: null as number | null, + signalCode: null as NodeJS.Signals | null, + killed: [] as string[], + kill(signal = "SIGTERM") { + this.killed.push(signal); + this.exitCode = 0; + return true; + }, + }); + stdin.on("data", (chunk: Buffer) => { + this.#buffer = Buffer.concat([this.#buffer, chunk]); + while (this.#buffer.byteLength >= 4) { + const length = this.#buffer.readUInt32BE(0); + if (this.#buffer.byteLength < 4 + length) break; + const payload = this.#buffer.subarray(4, 4 + length); + this.#buffer = this.#buffer.subarray(4 + length); + this.written.push(JSON.parse(payload.toString("utf8")) as StepFrame); + if (this.scripted) this.#answer(); + } + }); + } + + emit(frame: Record): void { + this.child.stdout.write( + encodeStepFrame({ protocol: STEP_PROTOCOL_NAME, version: STEP_PROTOCOL_VERSION, ...frame } as StepFrame), + ); + } + + /** Answer each newly written request once: initialize, query.start and query.input. */ + #answer(): void { + while (this.#scriptCursor < this.written.length) { + const frame = this.written[this.#scriptCursor++]!; + if (frame.method === "initialize") { + this.emit({ + kind: "response", + id: `r_${frame.id}`, + replyTo: frame.id, + payload: { runtimeVersion: "step", selectedProtocol: 1, capabilities: CAPABILITIES, limits: {} }, + }); + continue; + } + if (frame.method === "query.start") { + this.emit({ + kind: "response", + id: `r_${frame.id}`, + replyTo: frame.id, + payload: { queryId: "q_1", sessionId: "sess_1" }, + }); + continue; + } + if (frame.method === "query.input") { + this.emit({ kind: "response", id: `r_${frame.id}`, replyTo: frame.id, payload: { accepted: true } }); + } + } + } + + /** The adapter's response answering a reverse request this peer issued. */ + replyTo(id: string): StepFrame | undefined { + return this.written.find(frame => frame.kind === "response" && frame.replyTo === id); + } +} + +function options(overrides: Partial = {}): StepSessionOptions { + return { + binary: "/bin/true", + args: ["--sdk-stdio"], + env: {}, + cwd: "/tmp", + handshakeTimeoutMs: 500, + requestTimeoutMs: 500, + reverseRequestHoldMs: 500, + idleTimeoutMs: 60_000, + killGraceMs: 10, + ...overrides, + }; +} + +async function openSession(fake: FakeStep, deps: StepSessionDeps = {}) { + const events: StepSessionEvent[] = []; + const session = await StepCliSession.open( + options(), + { onEvent: event => events.push(event) }, + { spawn: () => fake.child, platform: "linux", ...deps }, + ); + return { session, events }; +} + +describe("StepCode session", () => { + test("refuses to spawn when the workspace cannot be created", async () => { + const root = await mkdtemp(join(tmpdir(), "ocx-step-workspace-")); + const file = join(root, "file"); + const fake = new FakeStep(); + let spawned = false; + let session: StepCliSession | undefined; + try { + await writeFile(file, ""); + const opening = StepCliSession.open(options({ cwd: join(file, "cwd") }), { onEvent: () => {} }, { + spawn: () => { spawned = true; return fake.child; }, + }).then(opened => { session = opened; }); + await expect(opening).rejects.toThrow(/create its workspace/); + expect(spawned).toBe(false); + } finally { + const closing = session?.close(); + fake.child.emit("close", 0, null); + await closing; + await rm(root, { recursive: true, force: true }); + } + }); + + test.each([ + ["CONFIG_INVALID", "please run /login: synthetic child diagnostic", "step_cli_not_logged_in", /Run `step login`/], + ["CONFIG_INVALID", "429 rate limit: synthetic child diagnostic", "step_cli_subscription_cooldown", /subscription temporarily/], + ["synthetic-child-code", "synthetic child diagnostic", "step_cli_session_failed", /could not complete the request/], + ])("classifies child error %s without retaining its text or arbitrary code", async (code, message, expectedCode, expectedMessage) => { + const fake = new FakeStep(); + fake.scripted = false; + const { session } = await openSession(fake); + try { + const handshake = session.handshake(); + fake.emit({ kind: "response", id: "res_1", replyTo: fake.written[0]!.id, error: { code, message } }); + await expect(handshake).rejects.toMatchObject({ code: expectedCode, message: expect.stringMatching(expectedMessage) }); + await expect(handshake).rejects.not.toThrow(/synthetic child diagnostic/); + } finally { + await session.close(); + } + }); + + test("negotiates the protocol and rejects a runtime without sdk-tools", async () => { + const fake = new FakeStep(); + const { session } = await openSession(fake); + const response = await session.handshake(); + expect(response.payload).toMatchObject({ selectedProtocol: 1 }); + expect(session.sessionId).toBeUndefined(); + await session.close(); + + const textOnly = new FakeStep(); + // Silent peer: the capability list under test has to be the one this test writes, not the script's. + textOnly.scripted = false; + const spawn = () => textOnly.child; + // A runtime without sdk-tools answers text only while looking healthy, which must fail closed. + const bare = await StepCliSession.open( + options(), + { onEvent: () => undefined }, + { spawn, platform: "linux" }, + ); + // Send the request first: a response that lands before its request is registered is dropped, + // which is the ordering a real runtime never produces but a hand-driven peer easily does. + const handshake = bare.handshake(); + textOnly.emit({ + kind: "response", + id: "r_init", + replyTo: "ocx_1", + payload: { capabilities: ["streaming-input"] }, + }); + await expect(handshake).rejects.toThrow(/does not advertise sdk-tools/); + await bare.close(); + }); + + test("opens a query with the client's tools declared inline and permission handling enabled", async () => { + const fake = new FakeStep(); + const { session } = await openSession(fake); + await session.handshake(); + const { queryId, sessionId } = await session.startQuery({ + model: "step-3.7-flash", + maxThinkingTokens: 4096, + sdkTools: [{ serverName: "ocx", toolName: "shell", description: "d", inputSchema: { type: "object" } }], + streamingInput: true, + }); + expect(queryId).toBe("q_1"); + expect(sessionId).toBe("sess_1"); + expect(session.sessionId).toBe("sess_1"); + + const start = fake.written.find(frame => frame.method === "query.start"); + expect(start?.payload).toMatchObject({ + streamingInput: true, + options: { model: "step-3.7-flash", maxThinkingTokens: 4096, permissionMode: "default", hasPermissionCallback: true }, + }); + await session.close(); + }); + + test("holds a permission request for the adapter to decide, then allows it", async () => { + const fake = new FakeStep(); + const { session, events } = await openSession(fake); + await session.handshake(); + const frame: StepFrame = { + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "request", + id: "req_perm", + method: "permission.request", + payload: { toolName: "ocx__shell", input: { cmd: "ls" }, toolUseId: "perm_1", timeoutMs: 60_000 }, + }; + fake.emit(frame); + await Bun.sleep(5); + // The session never decides on its own: approval belongs to the client, so the request is + // surfaced unanswered until the adapter chooses. + expect(events.some(event => event.type === "reverse_request")).toBe(true); + expect(fake.replyTo("req_perm")).toBeUndefined(); + + session.allowPermission(frame); + expect(fake.replyTo("req_perm")?.payload).toEqual({ behavior: "allow" }); + await session.close(); + }); + + test("holds a tool call open and releases it exactly once with the client's result", async () => { + const fake = new FakeStep(); + const { session } = await openSession(fake); + await session.handshake(); + fake.emit({ + kind: "request", + id: "req_tool", + method: "sdk_tool.invoke", + payload: { toolName: "ocx__shell", input: { cmd: "ls" }, toolUseId: "perm_2" }, + }); + await Bun.sleep(5); + // Nothing is invented while the client runs the tool: the request is still unanswered. + expect(fake.replyTo("req_tool")).toBeUndefined(); + expect(session.heldReverseRequests()).toHaveLength(1); + + const delivered = session.resolveHeldToolResult( + { id: "req_tool", method: "sdk_tool.invoke" } as StepFrame, + { content: [{ type: "text", text: "file.txt" }] }, + ); + expect(delivered).toBe(true); + expect(fake.replyTo("req_tool")?.payload).toEqual({ content: [{ type: "text", text: "file.txt" }] }); + // A second delivery must not reach the model twice. + expect(session.resolveHeldToolResult({ id: "req_tool", method: "sdk_tool.invoke" } as StepFrame, { content: [] })).toBe(false); + await session.close(); + }); + + test("reports a held tool result that arrived too late instead of continuing", async () => { + const fake = new FakeStep(); + // Injected timers: the old version slept 560ms of wall clock and went flaky on a slow runner. + const timers: Array<() => void> = []; + const setTimer = ((fn: () => void) => { + timers.push(fn); + return 0 as never; + }) as unknown as typeof setTimeout; + const { session, events } = await openSession(fake, { + setTimeout: setTimer, + clearTimeout: (() => undefined) as unknown as typeof clearTimeout, + }); + await session.handshake(); + fake.emit({ kind: "request", id: "req_tool", method: "sdk_tool.invoke", payload: { toolUseId: "t" } }); + await Bun.sleep(5); + // StepCode's own window is two minutes; a result past it has to fail rather than resume a call the + // model was already told was denied. + for (const fire of timers.splice(0)) fire(); + await Bun.sleep(5); + expect(session.resolveHeldToolResult({ id: "req_tool", method: "sdk_tool.invoke" } as StepFrame, { content: [] })).toBe(false); + // Regression: the expiry was surfaced with no answer, so the runtime waited out its own window. + const expiry = events.find(event => event.type === "reverse_request" && (event.frame.payload as { __expired?: boolean } | undefined)?.__expired === true); + expect(expiry, "the peer must be told the hold expired so it can answer the runtime").toBeDefined(); + // `close()` also schedules through the injected timer, so release whatever it queued rather than + // waiting on a clock this test has taken away. + void session.close(); + for (const fire of timers.splice(0)) fire(); + await session.close(); + }); + + test("surfaces runtime events and rejects a permission it cannot authorise", async () => { + const fake = new FakeStep(); + const { session, events } = await openSession(fake); + await session.handshake(); + fake.emit({ kind: "event", id: "evt_1", method: "query.message", sequence: 1, payload: { type: "status", status: "turn_complete" } }); + await Bun.sleep(5); + expect(events.some(event => event.type === "event")).toBe(true); + + const unknown: StepFrame = { + protocol: STEP_PROTOCOL_NAME, + version: STEP_PROTOCOL_VERSION, + kind: "request", + id: "req_other", + method: "some_future_method", + payload: {}, + }; + fake.emit(unknown); + await Bun.sleep(5); + // An unrecognised reverse method still needs an answer rather than being left to expire inside + // the model's context. + session.denyPermission(unknown, "OpenCodex does not handle some_future_method."); + expect((fake.replyTo("req_other")?.payload as { message?: string } | undefined)?.message).toMatch(/does not handle/); + await session.close(); + }); + + test("fails a pending request when the process exits", async () => { + const fake = new FakeStep(); + fake.scripted = false; + const { session } = await openSession(fake); + const handshake = session.handshake(); + fake.child.exitCode = 1; + fake.child.emit("close", 1, null); + await expect(handshake).rejects.toBeInstanceOf(StepSessionError); + }); + + test("a spawn failure closes the session and announces the exit without leaving it writable", async () => { + const fake = new FakeStep(); + fake.scripted = false; + const { session } = await openSession(fake); + let announced = 0; + session.onExit(() => { + announced += 1; + }); + const failure = session.handshake(); + fake.child.emit("error", new Error("spawn ENOENT")); + await expect(failure).rejects.toThrow(); + expect(session.closed).toBe(true); + expect(announced).toBe(1); + }); + + test("terminates with SIGTERM then escalates, and announces the exit", async () => { + const fake = new FakeStep(); + const { session } = await openSession(fake); + let announced = 0; + session.onExit(() => { + announced += 1; + }); + await session.close(); + expect(fake.child.killed[0]).toBe("SIGTERM"); + expect(announced).toBe(1); + expect(session.closed).toBe(true); + }); +}); + +describe("StepCode session pool", () => { + function fakeChild(): FakeStep["child"] { + return new FakeStep().child; + } + + const options = () => ({ + binary: "/bin/true", + args: ["--sdk-stdio"], + env: {}, + cwd: "/tmp", + handshakeTimeoutMs: 500, + requestTimeoutMs: 500, + reverseRequestHoldMs: 500, + idleTimeoutMs: 60_000, + killGraceMs: 10, + }); + + test("two concurrent opens of one conversation share a single process", async () => { + // Regression: `open` was async with no in-flight coalescing, so a Codex retry (or two clients on one + // handle) spawned two processes, the second `#entries.set` orphaned the first, and the orphan's + // held tool call could never be released. + const child = fakeChild(); + const pool = new StepSessionPool( + { openCodexHome: "/tmp", idleTimeoutMs: 60_000, buildOptions: options }, + { onEvent: () => undefined }, + { spawn: () => child, platform: "linux" as NodeJS.Platform }, + ); + const ref = { handle: "same", sessionId: "" }; + const [a, b] = await Promise.all([pool.open(ref), pool.open(ref)]); + expect(a).toBe(b); + expect(pool.size).toBe(1); + await pool.closeAll(); + }); + + test("sequential opens of one conversation reuse the same process", async () => { + const child = fakeChild(); + const pool = new StepSessionPool( + { openCodexHome: "/tmp", idleTimeoutMs: 60_000, buildOptions: options }, + { onEvent: () => undefined }, + { spawn: () => child, platform: "linux" as NodeJS.Platform }, + ); + const ref = { handle: "same", sessionId: "" }; + expect(await pool.open(ref)).toBe(await pool.open(ref)); + expect(pool.size).toBe(1); + await pool.closeAll(); + }); + + test("the held tool is remembered with the call it belongs to, and consumed once", async () => { + // Regression: only the frame id was stored, so a client that returned results for several calls + // had them matched by POSITION instead of by call id. + const child = fakeChild(); + const pool = new StepSessionPool( + { openCodexHome: "/tmp", idleTimeoutMs: 60_000, buildOptions: options }, + { onEvent: () => undefined }, + { spawn: () => child, platform: "linux" as NodeJS.Platform }, + ); + const ref = { handle: "conv", sessionId: "" }; + await pool.open(ref); + pool.rememberHeldTool(ref, { frameId: "frame-1", callId: "call-9", queryId: "q_1", catalogKey: "catalog" }); + expect(pool.takeHeldTool(ref)).toEqual({ frameId: "frame-1", callId: "call-9", queryId: "q_1", catalogKey: "catalog" }); + expect(pool.takeHeldTool(ref)).toBeUndefined(); + await pool.closeAll(); + }); +}); diff --git a/tests/adapters/step-cli-tool-bridge.test.ts b/tests/adapters/step-cli-tool-bridge.test.ts new file mode 100644 index 00000000000..92a5584b72b --- /dev/null +++ b/tests/adapters/step-cli-tool-bridge.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, test } from "bun:test"; + +import { + buildStepSdkTools, + resolveStepToolName, + StepToolCatalogError, + STEP_CLI_TOOL_SERVER, +} from "../../src/adapters/step-cli/tool-bridge"; +import type { OcxParsedRequest, OcxTool } from "../../src/types"; + +function tool(overrides: Partial = {}): OcxTool { + return { + name: "shell", + description: "Run a shell command", + parameters: { type: "object", properties: { cmd: { type: "string" } }, required: ["cmd"] }, + ...overrides, + } as OcxTool; +} + +function parsed(tools: OcxTool[], options: Record = {}): OcxParsedRequest { + return { modelId: "step-5-preview", context: { messages: [], tools }, options } as unknown as OcxParsedRequest; +} + +describe("Step SDK tool bridge", () => { + test("projects a client tool into an inline-schema sdkTool under the ocx namespace", () => { + const { sdkTools, emittedNameMap } = buildStepSdkTools(parsed([tool()])); + expect(sdkTools).toEqual([ + { + serverName: STEP_CLI_TOOL_SERVER, + toolName: "shell", + description: "Run a shell command", + inputSchema: { type: "object", properties: { cmd: { type: "string" } }, required: ["cmd"] }, + }, + ]); + // StepCode names a declared tool `${serverName}__${toolName}`; the map is how a call it reports + // back becomes the client's own name again. + expect(emittedNameMap.get("ocx__shell")).toBe("shell"); + }); + + test("recovers the client name from a namespaced wire name", () => { + const { emittedNameMap } = buildStepSdkTools(parsed([tool({ name: "apply_patch" })])); + expect(resolveStepToolName("ocx__apply_patch", emittedNameMap)).toBe("apply_patch"); + }); + + test("returns undefined for a tool this proxy never declared", () => { + const { emittedNameMap } = buildStepSdkTools(parsed([tool()])); + // A StepCode built-in, a host MCP tool, or a name with no namespace: none may be forwarded, + // because a call the client cannot satisfy is worse than a refused one. + expect(resolveStepToolName("ocx__not_declared", emittedNameMap)).toBeUndefined(); + expect(resolveStepToolName("read_file", emittedNameMap)).toBeUndefined(); + expect(resolveStepToolName("", emittedNameMap)).toBeUndefined(); + }); + + test("keeps a namespaced client tool distinct under its flattened wire name", () => { + const namespaced = tool({ name: "read", namespace: "fs" }); + const { sdkTools, emittedNameMap } = buildStepSdkTools(parsed([namespaced])); + expect(sdkTools[0]?.toolName).toBe("fs__read"); + expect(emittedNameMap.get("ocx__fs__read")).toBe("fs__read"); + }); + + test("surfaces an invalid catalog as a tool-catalog error rather than a bare throw", () => { + const invalid = tool({ name: "bad name" }); + expect(() => buildStepSdkTools(parsed([invalid]))).toThrow(StepToolCatalogError); + }); + + test("passes through a required-tool choice so the catalog is not silently widened", () => { + const { requireToolCall } = buildStepSdkTools(parsed([tool()], { toolChoice: "required" })); + expect(requireToolCall).toBe(true); + const optional = buildStepSdkTools(parsed([tool()], { toolChoice: "auto" })); + expect(optional.requireToolCall).toBe(false); + }); +}); diff --git a/tests/adapters/step-cli-tool-result.test.ts b/tests/adapters/step-cli-tool-result.test.ts new file mode 100644 index 00000000000..7aa8884eb9d --- /dev/null +++ b/tests/adapters/step-cli-tool-result.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, test } from "bun:test"; + +import { latestToolResult } from "../../src/adapters/step-cli/projection"; +import type { OcxParsedRequest } from "../../src/types"; + +function parsed(messages: unknown[]): OcxParsedRequest { + return { modelId: "step-5-preview", context: { messages }, options: {} } as unknown as OcxParsedRequest; +} + +describe("StepCode tool-result extraction", () => { + test("reads a string tool result, which is what a Responses function_call_output becomes", () => { + const result = latestToolResult( + parsed([ + { role: "user", content: "go", timestamp: 0 }, + { role: "toolResult", toolCallId: "c1", toolName: "shell", content: "LIVE_BRIDGE_OK", isError: false, timestamp: 1 }, + ]), + ); + // The call id travels with the result so the adapter can match it against the held call instead of + // trusting the result's position in the transcript. + expect(result).toEqual({ content: [{ type: "text", text: "LIVE_BRIDGE_OK" }], toolCallId: "c1" }); + }); + + test("keeps the parts of a structured tool result separate", () => { + const result = latestToolResult( + parsed([ + { + role: "toolResult", + toolCallId: "c1", + toolName: "shell", + content: [ + { type: "text", text: "first" }, + { type: "text", text: " second" }, + ], + isError: false, + timestamp: 1, + }, + ]), + ); + // Block boundaries are PRESERVED, not joined: StepCode maps each block 1:1, so concatenating + // would erase the distinction between e.g. a tool's stdout and its stderr. + expect(result?.content).toEqual([ + { type: "text", text: "first" }, + { type: "text", text: " second" }, + ]); + }); + + test("marks an errored tool result so the model is told the call failed", () => { + const result = latestToolResult( + parsed([{ role: "toolResult", toolCallId: "c1", toolName: "shell", content: "boom", isError: true, timestamp: 1 }]), + ); + expect(result?.isError).toBe(true); + expect(result?.toolCallId).toBe("c1"); + }); + + test("takes the newest result when a turn carries several", () => { + const result = latestToolResult( + parsed([ + { role: "toolResult", toolCallId: "c1", toolName: "shell", content: "old", isError: false, timestamp: 1 }, + { role: "user", content: "and again", timestamp: 2 }, + { role: "toolResult", toolCallId: "c2", toolName: "shell", content: "new", isError: false, timestamp: 3 }, + ]), + ); + expect(result?.content).toEqual([{ type: "text", text: "new" }]); + expect(result?.toolCallId).toBe("c2"); + }); + + test("returns undefined when this turn is not the answer to a captured call", () => { + expect(latestToolResult(parsed([{ role: "user", content: "hello", timestamp: 0 }]))).toBeUndefined(); + }); +}); diff --git a/tests/ci-workflows/cold-spawn-warmup.test.ts b/tests/ci-workflows/cold-spawn-warmup.test.ts index 2b14659612e..cae7d01a400 100644 --- a/tests/ci-workflows/cold-spawn-warmup.test.ts +++ b/tests/ci-workflows/cold-spawn-warmup.test.ts @@ -56,6 +56,10 @@ type Disposition = WarmupDisposition; * `tests/helpers/cold-spawn-warmup.ts`. `warmed: false` needs a reason that survives review. */ const DISPOSITIONS: Readonly> = { + "tests/adapters/step-cli-cleanup-ownership.test.ts": { + warmed: true, + why: "the isolated quarantine fixture loads the StepCode session registry and its runtime imports", + }, "tests/ci-workflows/ci-gui-typecheck-gate.test.ts": { warmed: false, why: diff --git a/tests/ci-workflows/repo-hygiene.test.ts b/tests/ci-workflows/repo-hygiene.test.ts index 6e18d944031..3171cc621eb 100644 --- a/tests/ci-workflows/repo-hygiene.test.ts +++ b/tests/ci-workflows/repo-hygiene.test.ts @@ -90,6 +90,19 @@ function trackedEntries(): { mode: string; path: string }[] { }); } +/** + * Bun's on-disk build cache. Bun writes `-00000000.bun-build` into whichever + * directory it runs in — here, the repository root — and a broad `git add -A` swept + * two 59.8 MB copies of it into this branch. They are pure machine-local cache: + * nothing in the build, the typecheck, or the test path reads them, and the same file + * reappears under a new hash on the next run, so committing one only ever adds weight. + * + * The ignore rule alone would not have caught the second copy, for the same reason it + * does not catch `go/` or `.codexclaw/`: an already-tracked path stops consulting + * `.gitignore` entirely. + */ +const BUILD_CACHE_SUFFIX = ".bun-build"; + describe("repository hygiene", () => { test("no local agent or session state is tracked", () => { const offenders = trackedFiles().filter((path) => @@ -99,6 +112,12 @@ describe("repository hygiene", () => { expect(offenders).toEqual([]); }); + test("no Bun build cache is tracked", () => { + const offenders = trackedFiles().filter((path) => path.endsWith(BUILD_CACHE_SUFFIX)); + + expect(offenders).toEqual([]); + }); + test("no OS metadata files are tracked", () => { const offenders = trackedFiles().filter((path) => FORBIDDEN_TRACKED_FILENAMES.includes(path.split("/").pop() ?? ""), @@ -138,6 +157,8 @@ describe("repository hygiene", () => { for (const dir of RETIRED_TRACKED_DIRS) { expect(ignore).toContain(`${dir}/`); } + + expect(ignore).toContain(`*${BUILD_CACHE_SUFFIX}`); }); }); diff --git a/tests/fixtures/step-cli-cleanup-registry.ts b/tests/fixtures/step-cli-cleanup-registry.ts new file mode 100644 index 00000000000..0d9a95d7bdd --- /dev/null +++ b/tests/fixtures/step-cli-cleanup-registry.ts @@ -0,0 +1,28 @@ +import { EventEmitter } from "node:events"; +import { PassThrough } from "node:stream"; +import type { ChildProcess } from "node:child_process"; +import { clearStepCliSessions, poolFor } from "../../src/adapters/step-cli/registry"; + +// Separate process: an intentionally quarantined registry must outlive the test's attempted clear. +const home = process.env.OPENCODEX_HOME!; +const child = Object.assign(new EventEmitter(), { + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), + exitCode: null, signalCode: null, kill: () => { throw new Error("injected cleanup failure"); }, +}); +const deps = { which: () => process.execPath, spawn: () => child as unknown as ChildProcess }; +const handlers = { onEvent: () => {} }; +const pool = poolFor(home, deps, handlers); +const ref = { handle: "retained-after-clear", sessionId: "" }; +const session = await pool.open(ref); +await session.close().catch(() => {}); +let clearRejected = false, replacementRejected = false; +try { await clearStepCliSessions(); } catch { clearRejected = true; } +const next = poolFor(home, deps, handlers); +try { await next.open(ref); } catch { replacementRejected = true; } +// Only fake children exist. Once the observations are flushed, exit this disposable registry +// instead of waiting for unrelated handles or the baseline's accidentally admitted fake session. +await new Promise((resolve, reject) => { + process.stdout.write(JSON.stringify({ clearRejected, samePool: next === pool, replacementRejected }), + error => { if (error) reject(error); else resolve(); }); +}); +process.exit(0); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index f007d908cc7..f8e0a9d3669 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -522,6 +522,15 @@ "claude-auth-mode.test.ts": "claude-integration", "claude-authmode-migration.test.ts": "claude-integration", "claude-cli-adapter.test.ts": "providers", "claude-cli.test.ts": "claude-integration", "claude-cli-client-http.test.ts": "providers", "claude-cli-efficiency.test.ts": "providers", + "step-cli-ownership.test.ts": "adapters", + "step-cli-process-lifecycle.test.ts": "adapters", + "step-cli-cleanup-ownership.test.ts": "adapters", + "step-cli-query-race.test.ts": "adapters", + "step-cli-conversation.test.ts": "adapters", + "step-cli-run-turn.test.ts": "adapters", + "step-cli-frames.test.ts": "adapters", "step-cli-session.test.ts": "adapters", + "step-cli-tool-bridge.test.ts": "adapters", "step-cli-tool-result.test.ts": "adapters", + "step-cli-provider.test.ts": "providers", "claude-cli-fixture-stdout-flush.test.ts": "providers", "claude-cli-tool-capture.test.ts": "providers", "claude-cli-usage-admission.test.ts": "providers", "claude-config-first-party.test.ts": "cli", "claude-code-thought-signature-scope.test.ts": "claude-integration", diff --git a/tests/gui/provider-subscription-cli.test.ts b/tests/gui/provider-subscription-cli.test.ts index 17d13f242af..0b460b643be 100644 --- a/tests/gui/provider-subscription-cli.test.ts +++ b/tests/gui/provider-subscription-cli.test.ts @@ -103,12 +103,12 @@ describe("subscription CLI warning copy", () => { } }); - test("every warning keeps the CLI chip and names the API-key provider", () => { + test("every warning has placeholders for the CLI name, command chip, plan and API-key provider", () => { for (const [locale, dict] of Object.entries(DICTS)) { const warning = dict["modal.subscriptionCliWarning"]; - expect(warning.split("{cmd}").length, locale).toBe(2); - expect(warning, locale).toContain("{apiProvider}"); - expect(warning, locale).toContain("Claude Code"); + expect(warning.match(/\{[^{}]+\}/g)?.sort(), locale).toEqual([ + "{apiProvider}", "{cli}", "{cmd}", "{plan}", + ]); } }); }); diff --git a/tests/helpers/step-cli-ownership.ts b/tests/helpers/step-cli-ownership.ts new file mode 100644 index 00000000000..328565e3497 --- /dev/null +++ b/tests/helpers/step-cli-ownership.ts @@ -0,0 +1,72 @@ +import type { AdapterEvent, OcxMessage, OcxParsedRequest, OcxProviderConfig } from "../../src/types"; +import type { IncomingMeta } from "../../src/adapters/base"; +import type { StepConversationHost, StepConversationSession, StepHeldTool } from "../../src/adapters/step-cli/session-pool"; +import type { StepFrame } from "../../src/adapters/step-cli/stdio-frames"; +import { handleReverseRequest, handleRuntimeEvent } from "../../src/adapters/step-cli/events"; +import { endTurn } from "../../src/adapters/step-cli/registry"; + +export const provider: OcxProviderConfig = { adapter: "step-cli", baseUrl: "https://api.stepfun.com/step_plan", authMode: "key" }; +export const incoming = { headers: new Headers({ "thread-id": "shared" }) } as IncomingMeta; +export const user: OcxMessage[] = [{ role: "user", content: "synthetic request", timestamp: 0 }]; +export function parsed(principal: string, messages = user): OcxParsedRequest { + return { + modelId: "step-5-preview", context: { messages, tools: [{ name: "shell", description: "run", parameters: { type: "object" } }] }, + options: {}, _reasoningReplayScope: { clientPrincipalId: principal, clientThreadId: "shared" }, + }; +} +export function event(queryId: string | undefined, message: Record): StepFrame { + return { protocol: "step-agent-sdk", version: 1, kind: "event", id: "evt", method: "query.message", sequence: 1, payload: { queryId, message } }; +} +export function request(id: string, payload: Record, method = "sdk_tool.invoke"): StepFrame { + return { protocol: "step-agent-sdk", version: 1, kind: "request", id, method, sessionId: "synthetic-session", payload }; +} +export class Session implements StepConversationSession { + sessionId = "synthetic-session"; + closed = false; + delivered: Array<{ frame: StepFrame; result: unknown }> = []; + inputs: Array<{ queryId: string; text: string }> = []; + allowed: string[] = []; + denied: string[] = []; + refused: string[] = []; + next = 0; + capture = true; + async handshake(): Promise { return { protocol: "step-agent-sdk", version: 1, kind: "response", id: "init" }; } + async startQuery() { return { queryId: `q_${++this.next}`, sessionId: this.sessionId }; } + async sendInput(queryId: string, text: string) { + this.inputs.push({ queryId, text }); + queueMicrotask(() => { + if (this.capture) handleReverseRequest(this, request("req_10", { serverName: "ocx", toolName: "shell", toolUseId: "call-1", input: {}, timeoutMs: 120_000 })); + else handleRuntimeEvent(this, event(queryId, { type: "status", status: "turn_complete" })); + }); + } + async endInput() {} + async interrupt() {} + async close() { this.closed = true; endTurn(this); } + allowPermission(frame: StepFrame) { this.allowed.push(frame.id); } + denyPermission(frame: StepFrame) { this.denied.push(frame.id); } + refuseToolCall(frame: StepFrame) { this.refused.push(frame.id); } + resolveHeldToolResult(frame: StepFrame, result: unknown) { + this.delivered.push({ frame, result }); + queueMicrotask(() => handleRuntimeEvent(this, event("q_1", { type: "status", status: "turn_complete" }))); + return true; + } +} +export function host(): StepConversationHost & { entries: Map } { + const entries = new Map(); + const held = new Map(); + return { + entries, get: ref => ref ? entries.get(ref.handle) : undefined, + open: async ref => { + let session = entries.get(ref.handle); + if (!session) { session = new Session(); entries.set(ref.handle, session); } + return session; + }, + nextRef: () => ({ handle: `fresh-${entries.size}`, sessionId: "" }), + rememberHeldTool: (ref, value) => { held.set(ref.handle, value); }, + takeHeldTool: ref => { const value = held.get(ref.handle); held.delete(ref.handle); return value; }, + closeAll: async () => { for (const session of entries.values()) await session.close(); }, + }; +} +export function attachTurn(session: Session, emit: (event: AdapterEvent) => void) { + return { ref: { handle: "test", sessionId: "" }, pool: host(), emit, settle: () => {}, emittedNames: new Map([["ocx__shell", "shell"]]), catalogKey: "catalog" }; +} diff --git a/tests/lib/optional-shutdown-hooks.test.ts b/tests/lib/optional-shutdown-hooks.test.ts index 58129a55295..c4ff5ea7833 100644 --- a/tests/lib/optional-shutdown-hooks.test.ts +++ b/tests/lib/optional-shutdown-hooks.test.ts @@ -9,6 +9,7 @@ import { isLabAutomationSchedulerRunning, } from "../../src/lab/automation/orchestrator"; import { + registerAsyncOptionalShutdownHook, registerOptionalShutdownHook, runOptionalShutdownHooks, resetOptionalShutdownHooksForTests, @@ -17,6 +18,37 @@ import { describe("optional shutdown hooks", () => { beforeEach(() => resetOptionalShutdownHooksForTests()); + test("joins asynchronous siblings even when one reports failure", async () => { + const receipt = Promise.withResolvers(); + let joined = false; + registerAsyncOptionalShutdownHook("failure", async () => { throw new Error("synthetic cleanup failure"); }); + registerAsyncOptionalShutdownHook("cleanup", () => receipt.promise); + const shutdown = runOptionalShutdownHooks().then(result => { joined = true; return result; }); + await Promise.resolve(); + expect(joined).toBe(false); + receipt.resolve(); + expect(await shutdown).toBe(false); + }); + + test("reports timeout for an asynchronous hook with no cleanup receipt", async () => { + const receipt = Promise.withResolvers(); + const deadlineMs = Date.now() + 20; + const fallbacks: string[] = []; + let receivedDeadline: number | undefined; + registerAsyncOptionalShutdownHook("pending", deadline => { + receivedDeadline = deadline; + return receipt.promise; + }, () => { fallbacks.push("pending"); }); + registerAsyncOptionalShutdownHook("complete", async () => {}, () => { fallbacks.push("complete"); }); + try { + expect(await runOptionalShutdownHooks({ deadlineMs })).toBe(false); + expect(receivedDeadline).toBe(deadlineMs); + expect(fallbacks).toEqual(["pending"]); + } finally { + receipt.resolve(); + } + }); + test("running with nothing registered is a no-op", () => { expect(() => runOptionalShutdownHooks()).not.toThrow(); }); diff --git a/tests/providers/provider-registry-parity.test.ts b/tests/providers/provider-registry-parity.test.ts index 1db71d3348e..580eea9fb89 100644 --- a/tests/providers/provider-registry-parity.test.ts +++ b/tests/providers/provider-registry-parity.test.ts @@ -1212,7 +1212,7 @@ describe("provider registry parity", () => { // claude-cli joins them as the first CLI-backed member: its row is `key` because the turn // leaves this machine, and keyless because the Claude Code CLI reads the operator's sign-in. // antigravity-acp follows claude-cli for the same reason: the official agy CLI owns the Google sign-in. - expect(optionalKeyProviders).toEqual(["litellm", "mimo-free", "claude-cli", "antigravity-acp"]); + expect(optionalKeyProviders).toEqual(["litellm", "mimo-free", "step-cli", "claude-cli", "antigravity-acp"]); }); test("NVIDIA NIM is free-tier priced but still requires an API key", () => { diff --git a/tests/providers/step-cli-provider.test.ts b/tests/providers/step-cli-provider.test.ts new file mode 100644 index 00000000000..a0262a3e57b --- /dev/null +++ b/tests/providers/step-cli-provider.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, test } from "bun:test"; +import { join, resolve } from "node:path"; + +import { createStepCliAdapter } from "../../src/adapters/step-cli/adapter"; +import { buildStepCliArgs, findStepCliBinary, resolveStepCliProfile, STEP_CLI_PROFILE } from "../../src/adapters/step-cli/profiles"; +import { resolveAdapter } from "../../src/server"; +import { deriveProviderPresets, providerConfigSeed } from "../../src/providers/derive"; +import { PROVIDER_REGISTRY } from "../../src/providers/registry"; +import { + STEP_CLI_MODEL_CONTEXT_WINDOWS, + STEP_CLI_MODELS, + STEP_CLI_NO_VISION_MODELS, + STEP_CLI_REASONING_EFFORTS, +} from "../../src/providers/registry/model-seeds"; +import type { OcxParsedRequest, OcxProviderConfig } from "../../src/types"; + +const BASE_URL = "https://api.stepfun.com/step_plan"; + +function registryEntry() { + const entry = PROVIDER_REGISTRY.find(provider => provider.id === "step-cli"); + if (!entry) throw new Error("StepCode registry entry not found"); + return entry; +} + +function providerConfig(overrides: Partial = {}): OcxProviderConfig { + return { adapter: "step-cli", baseUrl: BASE_URL, authMode: "key", ...overrides } as OcxProviderConfig; +} + +function parsed(overrides: Partial = {}): OcxParsedRequest { + return { + modelId: "step-5-preview", + context: { messages: [{ role: "user", content: "hello", timestamp: 0 }], tools: [] }, + options: {}, + ...overrides, + } as unknown as OcxParsedRequest; +} + +describe("StepCode provider", () => { + test("is registered as a keyless-but-key-classified subscription route", () => { + expect(registryEntry()).toMatchObject({ + id: "step-cli", + label: "StepCode CLI (subscription)", + adapter: "step-cli", + baseUrl: BASE_URL, + authKind: "key", + keyOptional: true, + defaultModel: "step-5-preview", + liveModels: false, + }); + // The traffic leaves the machine, so `local` would misreport the row's credential class; it is + // keyless because the CLI reads the operator's own `step login`. + expect(registryEntry().authKind).not.toBe("local"); + }); + + test("publishes the Step Plan roster with its measured windows and a text-only contract", () => { + const entry = registryEntry(); + expect(entry.models).toEqual([...STEP_CLI_MODELS]); + // Speech models the same endpoint returns are absent: a row that routed a text turn into one + // answers `model_invalid`. + expect(entry.models?.some(id => id.startsWith("stepaudio"))).toBe(false); + expect(entry.modelContextWindows).toEqual(STEP_CLI_MODEL_CONTEXT_WINDOWS); + expect(STEP_CLI_MODEL_CONTEXT_WINDOWS["step-5-preview"]).toBe(1_024_000); + // Even the models that accept images upstream are published text-only on this route. + expect(entry.noVisionModels).toEqual(STEP_CLI_NO_VISION_MODELS); + expect(entry.noVisionModels).toContain("step-5-preview"); + }); + + test("advertises only the three reasoning rungs Step actually serves", () => { + expect(registryEntry().reasoningEfforts).toEqual(STEP_CLI_REASONING_EFFORTS); + // `xhigh`/`max` are mapped server-side onto `high`; publishing them would let the client believe + // it chose a depth it did not. + expect(registryEntry().reasoningEfforts).not.toContain("xhigh"); + expect(registryEntry().reasoningEfforts).not.toContain("max"); + }); + + test("is reachable from the derived preset catalog and seeds a usable config", () => { + const preset = deriveProviderPresets().find(provider => provider.id === "step-cli"); + expect(preset).toMatchObject({ id: "step-cli", adapter: "step-cli", baseUrl: BASE_URL }); + const seed = providerConfigSeed(registryEntry()); + expect(seed.baseUrl).toBe(BASE_URL); + expect(seed.keyOptional).toBe(true); + }); + + test("resolves through the adapter registry to the step-cli adapter", () => { + expect(resolveAdapter(providerConfig()).name).toBe("step-cli"); + }); + + test("fails closed when the row is pointed away from StepCode's own destination", () => { + // The CLI owns the credential, so a row repointed elsewhere would spend it against a host the + // adapter cannot speak to. Refusing is the only safe answer. + expect(resolveStepCliProfile("https://evil.example/v1")).toBeUndefined(); + expect(resolveStepCliProfile(BASE_URL)).toBe(STEP_CLI_PROFILE); + expect(resolveStepCliProfile(`${BASE_URL}/`)).toBe(STEP_CLI_PROFILE); + }); + + test("refuses a mismatched destination before any request is built", async () => { + const adapter = createStepCliAdapter(providerConfig({ baseUrl: "https://evil.example/v1" })); + const events: unknown[] = []; + await adapter.runTurn!(parsed(), { headers: new Headers() } as never, event => events.push(event)); + expect(events).toEqual([ + expect.objectContaining({ type: "error", code: "step_cli_profile_mismatch", status: 400 }), + ]); + }); + + test("refuses image input rather than answering a picture blind", async () => { + const adapter = createStepCliAdapter(providerConfig()); + const events: Array> = []; + const withImage = parsed({ + context: { + messages: [ + { role: "user", content: [{ type: "image", imageUrl: "data:image/png;base64,AAAA" }], timestamp: 0 }, + ], + tools: [], + }, + }); + await adapter.runTurn!(withImage, { headers: new Headers() } as never, event => events.push(event as never)); + expect(events[0]).toMatchObject({ type: "error", code: "unsupported_input_modality", status: 400 }); + }); + + test("spawns the CLI with every host-config switch disabled", () => { + const args = buildStepCliArgs("step-3.7-flash", "medium"); + expect(args[0]).toBe("--sdk-stdio"); + for (const flag of [ + "--no-tools", + "--no-extensions", + "--no-skills", + "--no-prompt-templates", + "--no-themes", + "--no-context-files", + "--no-session", + "--no-update-check", + ]) { + expect(args).toContain(flag); + } + expect(args).toContain("--model"); + expect(args).toContain("step-3.7-flash"); + expect(args).toContain("--thinking"); + expect(args).toContain("medium"); + }); + + test("finds the self-installed CLI when PATH does not carry it", () => { + const absent = findStepCliBinary("step", () => undefined, "/nonexistent-home"); + expect(absent).toBeUndefined(); + // A PATH hit always wins, so an operator who installed it elsewhere keeps their own binary. + const absolute = resolve("opt", "bin", "step"); + expect(findStepCliBinary("step", () => absolute, "/nonexistent-home")).toBe(absolute); + }); + + test("resolves a relative PATH hit before the child changes directory", () => { + const relative = join("relative-cli", "step"); + expect(findStepCliBinary("step", () => relative)).toBe(resolve(relative)); + }); +}); diff --git a/tests/service/shutdown-drain.test.ts b/tests/service/shutdown-drain.test.ts index dbd30829ad1..9680d962e0f 100644 --- a/tests/service/shutdown-drain.test.ts +++ b/tests/service/shutdown-drain.test.ts @@ -4,7 +4,12 @@ import { repoPath } from "../helpers/repo-root"; import { PassThrough } from "node:stream"; import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { create } from "@bufbuild/protobuf"; -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; +import { + registerAsyncOptionalShutdownHook, + registerDrainStartHook, + resetOptionalShutdownHooksForTests, +} from "../../src/lib/optional-shutdown-hooks"; import { drainAndShutdown, registerTurn, @@ -83,6 +88,24 @@ function fakeServer(stopImpl?: (closeActiveConnections?: boolean) => void | Prom } describe("server listener shutdown", () => { + test.each([0, 5_000, 30_000])("does not give cleanup a fresh budget after the %ims drain and stop window", async timeoutMs => { + const fake = fakeServer(); + const start = Date.now(); + const clock = spyOn(Date, "now").mockReturnValue(start); + const exhaustStopWindow = registerDrainStartHook("exhaust-stop-window", () => { + clock.mockReturnValue(start + timeoutMs + 3_000); + }); + registerAsyncOptionalShutdownHook("delayed-receipt", () => Bun.sleep(5)); + try { + expect(await drainAndShutdown(fake.server, timeoutMs)).toBe(false); + expect(fake.stops()).toBe(1); + } finally { + clock.mockRestore(); + exhaustStopWindow(); + resetOptionalShutdownHooksForTests(); + } + }); + test("single-flights stop(true) and keeps every waiter pending until close completes", async () => { let resolveStop!: () => void; const fake = fakeServer(() => new Promise(resolve => { resolveStop = resolve; })); From 3bc34e67acdf25f1d03ddad639e858bdc55587a1 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 21 Nov 2026 03:21:04 +0900 Subject: [PATCH 03/57] fix(gui): collapse account pool settings to title and switch; stack quota rows again (#9004) * test(gui): pool settings collapse to header and quota rows stack (failing) Red first: 7 of 10 disclosure cases and both quota-row cases fail on d61cca122d. * feat(gui): pool settings collapse to title and switch; quota rows stack again Claude, Claude Pool 2 and Codex usage-based switching cards show only their title and on/off switch; the title is an APG disclosure button that remembers per card whether it was opened. Closing settles an in-progress threshold edit and remounts the details so a portaled Select menu cannot outlive them. A load failure or the two-account requirement stays visible because it is why the switch is disabled. AccountQuotaTable's card layout lists each pool's name, 5-hour bar and weekly bar on separate lines again, as v2.100.5 did before #8740 put them side by side. * docs(structure): stacked quota rows and collapsed pool settings cards * test(gui): pool card survives a localStorage getter that throws (failing) * fix(gui): collapse store tolerates a localStorage getter that throws Resolving the global inside read()/write()'s try keeps blocked site storage (SecurityError from the getter) a missing preference instead of a render crash; PoolSettingsDisclosure reads the store in a useState initializer. --- .../src/content/docs/guides/web-dashboard.md | 2 +- gui/src/components/CodexAutoSwitchSetting.tsx | 235 ++++++------- gui/src/components/PoolSettingsDisclosure.tsx | 85 +++++ .../provider-workspace/AccountQuotaTable.tsx | 6 +- .../AnthropicAccountPoolSettings.tsx | 320 +++++++++--------- .../account-quota-table.css | 39 +-- gui/src/pages/collapse-store.ts | 14 +- gui/src/styles/pool-settings-disclosure.css | 44 +++ .../account-quota-table-stacked.test.tsx | 102 ++++++ gui/tests/anthropic-pool-conditions.test.tsx | 9 +- gui/tests/pool-settings-disclosure.test.tsx | 292 ++++++++++++++++ structure/gui-and-management-api.md | 2 +- 12 files changed, 840 insertions(+), 310 deletions(-) create mode 100644 gui/src/components/PoolSettingsDisclosure.tsx create mode 100644 gui/src/styles/pool-settings-disclosure.css create mode 100644 gui/tests/account-quota-table-stacked.test.tsx create mode 100644 gui/tests/pool-settings-disclosure.test.tsx diff --git a/docs-site/src/content/docs/guides/web-dashboard.md b/docs-site/src/content/docs/guides/web-dashboard.md index df6f28f1925..41627bfc1aa 100644 --- a/docs-site/src/content/docs/guides/web-dashboard.md +++ b/docs-site/src/content/docs/guides/web-dashboard.md @@ -200,7 +200,7 @@ is visible) and never forces an upstream refresh. | **Windows tray** | Install a per-user login tray for one-click proxy start, stop, restart, dashboard access, and status. The tray is a controller, not a proxy restart service. | | **Codex autostart** | Allow an already-installed Codex launcher shim to run `ocx ensure`. This toggle does not install a shim or background service. | | **Telemetry** | Toggle **Share anonymous usage statistics** and inspect **Preview the JSON** under **Proxy details** (`#proxy-telemetry`). On first run or after an update while undecided, the consent popup saves a choice only when **Continue** is clicked (`PUT /api/telemetry`); dismissing it records nothing. See [Telemetry and Privacy](/guides/telemetry/). | -| **Providers** | Add, edit, set the default (enabled providers only), enable/disable, and remove providers; manage OAuth account pools and API-key pools where supported. Removing the current default switches to the first remaining enabled provider when one exists; otherwise deletion is refused and the current default is kept. Provider Settings can disable live model discovery for endpoints with missing, slow, or oversized `/models` catalogs. For Claude (Anthropic) OAuth pools, each logged-in account shows its own 5-hour and weekly rate-limit bars (usage is per credential); a failed probe keeps the last-known bars and marks them unavailable until the next successful refresh. Refreshing quota skips paused OAuth accounts and disabled API keys; skipped rows without a cached reading remain unavailable but do not affect the refresh result. Refreshing reports failure when an unpaused OAuth account or enabled API key that supports quota reads has an unavailable reading. The Provider Overview shown when no provider is selected carries a **Refresh all quotas** control that forces one server-side re-read of every configured provider; a provider whose upstream probe fails keeps its last-good row, so the status line reports that the check completed rather than claiming every value is fresh, and each row's own age stays the per-provider freshness signal. Unsaved Settings and JSON edits are kept in memory per logical dashboard server: switching servers parks the draft, saving writes only to the server where editing began, and a changed saved configuration asks you to keep your draft or use the saved values. Keeping a JSON draft merges only your changes into the latest config and names any field changed on both sides; Settings saves only the fields you changed. On a relay that predates target-bound saves, the dashboard checks the target immediately before sending but cannot verify it atomically, and says so once; update the proxy for the stronger guarantee. Closing or reloading the dashboard discards these drafts. | +| **Providers** | Add, edit, set the default (enabled providers only), enable/disable, and remove providers; manage OAuth account pools and API-key pools where supported. Removing the current default switches to the first remaining enabled provider when one exists; otherwise deletion is refused and the current default is kept. Provider Settings can disable live model discovery for endpoints with missing, slow, or oversized `/models` catalogs. For Claude (Anthropic) OAuth pools, each logged-in account shows its own 5-hour and weekly rate-limit bars (usage is per credential); a failed probe keeps the last-known bars and marks them unavailable until the next successful refresh. An account pool settings card (Claude, Claude Pool 2, and Codex usage-based switching) shows only its title and on/off switch; select the title to show its other settings, and the dashboard remembers which cards you opened. Each account's quota lists the pool name, then its 5-hour bar, then its weekly bar, each on its own line with the percentage left and the reset countdown. Refreshing quota skips paused OAuth accounts and disabled API keys; skipped rows without a cached reading remain unavailable but do not affect the refresh result. Refreshing reports failure when an unpaused OAuth account or enabled API key that supports quota reads has an unavailable reading. The Provider Overview shown when no provider is selected carries a **Refresh all quotas** control that forces one server-side re-read of every configured provider; a provider whose upstream probe fails keeps its last-good row, so the status line reports that the check completed rather than claiming every value is fresh, and each row's own age stays the per-provider freshness signal. Unsaved Settings and JSON edits are kept in memory per logical dashboard server: switching servers parks the draft, saving writes only to the server where editing began, and a changed saved configuration asks you to keep your draft or use the saved values. Keeping a JSON draft merges only your changes into the latest config and names any field changed on both sides; Settings saves only the fields you changed. On a relay that predates target-bound saves, the dashboard checks the target immediately before sending but cannot verify it atomically, and says so once; update the proxy for the stronger guarantee. Closing or reloading the dashboard discards these drafts. | | **Add provider** | One search above the tabs reaches all four at once — Accounts, Free, Local, Paid. While a query is live the results are grouped by tab with a count each, and the selected tab stays put rather than jumping. Press ArrowDown in the search box to focus the first available result action, skipping disabled buttons; if no action is available, focus stays in the search box. Local runtimes (Ollama, vLLM, LM Studio, LiteLLM) have their own tab, and a long provider note clamps to two lines with the full text one click away. Claude Code CLI (subscription) sits under Paid with a Subscription CLI badge, and selecting it warns that it bills the signed-in Claude subscription through `claude -p` and never uses an API key (use `anthropic-apikey` for key billing). | | **Codex Auth** | Add ChatGPT/Codex pool accounts, select the next-session account, refresh 5h / weekly / 30d quotas, enable or disable quota auto-switch, set its 1–100% threshold, and configure transient-failure failover. | | **Subagents** | Set the first five `spawn_agent` priorities through `subagentModels`, using bare native or namespaced routed models. This is not an allowlist: unused positions may be filled from visible catalog rows. The **Workflow limits for subagents** panel sets how many turns one task may run in parallel and how many model requests and distinct subagents it may use per 10-minute window. See [workflow limits](/reference/configuration/server/#workflow-limits). | diff --git a/gui/src/components/CodexAutoSwitchSetting.tsx b/gui/src/components/CodexAutoSwitchSetting.tsx index 3ee30c2e56e..b5bea9522c9 100644 --- a/gui/src/components/CodexAutoSwitchSetting.tsx +++ b/gui/src/components/CodexAutoSwitchSetting.tsx @@ -3,6 +3,7 @@ import { useT } from "../i18n/shared"; import { clampNumberDraft } from "../clamp-draft"; import type { AccountPoolStrategy } from "../account-pool-strategy"; import { NumberStepper } from "./NumberStepper"; +import PoolSettingsDisclosure from "./PoolSettingsDisclosure"; export type AutoSwitchFeedback = { tone: "ok" | "err"; message: string } | null; @@ -71,128 +72,130 @@ export function CodexAutoSwitchSetting({ const describedBy = feedbackMessage ? "codex-auto-switch-desc codex-auto-switch-feedback" : "codex-auto-switch-desc"; + // Leaving the card settles an edit, exactly as leaving the threshold field and switch did when + // they shared one container. The disclosure button now sits between them, so the boundary is + // the whole card: moving focus from the field to the switch or the title commits nothing. + const settleEdit = () => { + onEditingChange(false); + if (togglePointerIntentRef.current) { + togglePointerIntentRef.current = false; + return; + } + if (enabled && !controlsDisabled) void onCommit(); + }; + const description = ( +
+ {loadError ? t("codexAuth.autoSwitchLoadFailed") : t(descriptionKey, { threshold })} +
+ ); return (
{ + if (event.currentTarget.contains(event.relatedTarget as Node | null)) return; + settleEdit(); + }} > -
- {t("codexAuth.autoSwitch")} -
- {loadError - ? t("codexAuth.autoSwitchLoadFailed") - : t(descriptionKey, { threshold })} -
-
{t("codexAuth.failureRecoveryNote")}
-
{t("codexAuth.cacheWarning")}
-
-
{ - if (event.currentTarget.contains(event.relatedTarget as Node | null)) return; - onEditingChange(false); - if (togglePointerIntentRef.current) { - togglePointerIntentRef.current = false; - return; - } - if (enabled && !controlsDisabled) void onCommit(); - }} - > - {loadError && ( - - )} - {enabled && ( - + + {description} + +
)} - {/* - The toggle sits in a slot as tall as the threshold field so the two controls share a - center line. The row is bottom-aligned (a 20px toggle against a 32px number compound - offset their centers by 6px, which is what read as a height bug), and the slot fixes - that without flipping the container to center — the mobile breakpoint deliberately - keeps bottom alignment. - - Rendered outside the `enabled` branch on purpose: if the slot came and went with the - threshold field, the toggle would shift every time auto-switch was turned off. - */} - - - -
+ control={ + + + + } + > +
+
+ {!loadError && description} +
{t("codexAuth.failureRecoveryNote")}
+
{t("codexAuth.cacheWarning")}
+
+ {enabled && ( + + )} +
+ {feedbackMessage && (
and would otherwise outlive its hidden trigger. + * + * Which cards a person opened is remembered per card id. Only open ids are stored, so a card nobody + * opened starts closed. Each toggle re-reads the stored set before writing it: two cards on one page + * would otherwise each write back the set they read at mount and drop the other's entry. + */ +import { useId, useRef, useState, type ReactNode } from "react"; +import { IconChevron } from "../icons"; +import { makeCollapseStore } from "../pages/collapse-store"; +import "../styles/pool-settings-disclosure.css"; + +const OPEN_CARDS = makeCollapseStore("ocx.accountPool.openSettings.v1"); + +export default function PoolSettingsDisclosure({ + cardId, + title, + control, + notice, + onCollapse, + children, +}: { + /** Remembers the open state: the provider id for a Claude card, a fixed name for a Codex one. */ + cardId: string; + title: ReactNode; + /** The card's switch, shown beside the title whether or not the details are open. */ + control?: ReactNode; + /** Lines that must stay visible while closed, such as why the switch is disabled. */ + notice?: ReactNode; + /** Runs before the details close, so a field inside can settle an edit in progress. */ + onCollapse?: () => void; + children: ReactNode; +}) { + const bodyId = useId(); + const buttonRef = useRef(null); + const [open, setOpen] = useState(() => OPEN_CARDS.read()?.has(cardId) ?? false); + const [closings, setClosings] = useState(0); + + const toggle = () => { + const next = !open; + if (!next) { + onCollapse?.(); + setClosings(count => count + 1); + } + const stored = new Set(OPEN_CARDS.read() ?? []); + if (next) stored.add(cardId); + else stored.delete(cardId); + OPEN_CARDS.write(stored); + setOpen(next); + // Safari does not focus a clicked button; focus left inside the details would be lost. + if (!next) buttonRef.current?.focus(); + }; + + return ( + <> +
+ + {control} +
+ {notice} + + + ); +} diff --git a/gui/src/components/provider-workspace/AccountQuotaTable.tsx b/gui/src/components/provider-workspace/AccountQuotaTable.tsx index 45e60915e89..99d759f542a 100644 --- a/gui/src/components/provider-workspace/AccountQuotaTable.tsx +++ b/gui/src/components/provider-workspace/AccountQuotaTable.tsx @@ -127,7 +127,11 @@ export function AccountQuotaTable({ accounts, strategy, renderRowContent }: Acco : table.pools.map(pool => { const cell = row.cells[pool.key]; return ( - + + {/* The card layout hides the table header, so each pool names itself on its + own line above its 5-hour and weekly bars, as v2.100.5 stacked them. The + header still names the column for assistive technology. */} + {cell ? <> {cell.fiveHour && } {cell.weekly && } diff --git a/gui/src/components/provider-workspace/AnthropicAccountPoolSettings.tsx b/gui/src/components/provider-workspace/AnthropicAccountPoolSettings.tsx index 837fc8c43a8..f623730b7d8 100644 --- a/gui/src/components/provider-workspace/AnthropicAccountPoolSettings.tsx +++ b/gui/src/components/provider-workspace/AnthropicAccountPoolSettings.tsx @@ -24,6 +24,7 @@ import { type AccountPoolStrategy, } from "../../account-pool-strategy"; import AccountPoolStrategyControls from "../AccountPoolStrategyControls"; +import PoolSettingsDisclosure from "../PoolSettingsDisclosure"; import { Select } from "../../ui"; /** The public guide section that explains pool selection, failover and its limits. */ @@ -257,187 +258,198 @@ export default function AnthropicAccountPoolSettings({ // Always allow turning the pool off; only block enabling when fewer than 2 accounts. const controlsDisabled = loading || saving || loadError || reloadRequired; const toggleDisabled = controlsDisabled || (!enabled && accountCount < 2); + // Collapsed, the card is its title and switch. A disabled switch still says why: a failed load, + // or too few accounts to turn the pool on. The rest of the status line waits behind the title. + const switchBlockedByLoad = loadError && !reloadRequired; + const switchBlockedByAccounts = !controlsDisabled && !enabled && accountCount < 2; return (
-
-
- {t("anthropicPool.title")} -
+ + {switchBlockedByLoad ? t("anthropicPool.loadFailed") : t("anthropicPool.needTwoAccounts")} +
+ )} + control={ + + } + > + {!switchBlockedByLoad && ( +
{reloadRequired ? t("anthropicPool.saveStateUnknown") - : loadError - ? t("anthropicPool.loadFailed") : loading ? t("common.loading") : enabled ? enabledStatus(t, strategy, threshold, quotaWindow) : t("anthropicPool.disabledDesc")}
-
- -
+ )} -

- {t("anthropicPool.experimentalWarning")} -

- - {accountCount < 2 && ( -
{t("anthropicPool.needTwoAccounts")}
- )} - -
- {t("anthropicPool.detailsSummary")} -

{t("anthropicPool.detailsEnabling")}

-

{t("anthropicPool.detailsFailover")}

-

{t("anthropicPool.detailsActivity")}

- -

- {t("anthropicPool.detailsGuide")} +

+ {t("anthropicPool.experimentalWarning")}

-
- {enabled && state && ( - <> - {usesConfigurableQuotaWindow &&