@bitkyc08/opencodex 2.100.6 → 2.100.7-preview.20261120.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/gui/dist/assets/App-Te21Q-Fv.js +65 -0
  2. package/gui/dist/assets/App-hklyKJR5.css +1 -0
  3. package/gui/dist/assets/{Tray-CVqm4S4W.js → Tray-Bto-DJ6b.js} +1 -1
  4. package/gui/dist/assets/brand-mark-CCRs3Ywg.js +1 -0
  5. package/gui/dist/assets/index-B85uU8rK.css +2 -0
  6. package/gui/dist/assets/index-Befqr0m8.js +138 -0
  7. package/gui/dist/assets/{segment-thumb-features-COdzmORE.js → segment-thumb-features-CKFf9DaQ.js} +1 -1
  8. package/gui/dist/classic/assets/App-BPkhxI3i.js +64 -0
  9. package/gui/dist/classic/assets/App-DSivR528.css +1 -0
  10. package/gui/dist/classic/assets/{Tray-BDlcOLDK.js → Tray-CSRN8p3a.js} +1 -1
  11. package/gui/dist/classic/assets/index-BHM1aTF8.js +138 -0
  12. package/gui/dist/classic/assets/usage-companion-chart-DC8ve7g8.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/package.json +2 -2
  16. package/src/adapters/coding-agent/process-tree.ts +30 -0
  17. package/src/adapters/coding-agent/profile.ts +1 -1
  18. package/src/adapters/coding-agent/turn.ts +2 -9
  19. package/src/adapters/command-code-decision-guard.ts +25 -0
  20. package/src/adapters/cursor/catalog.ts +14 -0
  21. package/src/adapters/cursor/effort-map.ts +3 -0
  22. package/src/adapters/google-usage.ts +28 -0
  23. package/src/adapters/google.ts +9 -26
  24. package/src/adapters/qoder/adapter.ts +197 -13
  25. package/src/adapters/registry.ts +13 -0
  26. package/src/adapters/step-cli/adapter.ts +401 -0
  27. package/src/adapters/step-cli/constants.ts +11 -0
  28. package/src/adapters/step-cli/conversation.ts +159 -0
  29. package/src/adapters/step-cli/env.ts +49 -0
  30. package/src/adapters/step-cli/errors.ts +76 -0
  31. package/src/adapters/step-cli/events.ts +227 -0
  32. package/src/adapters/step-cli/profiles.ts +134 -0
  33. package/src/adapters/step-cli/projection.ts +242 -0
  34. package/src/adapters/step-cli/registry.ts +181 -0
  35. package/src/adapters/step-cli/session-pool.ts +225 -0
  36. package/src/adapters/step-cli/session.ts +842 -0
  37. package/src/adapters/step-cli/stdio-frames.ts +330 -0
  38. package/src/adapters/step-cli/tool-bridge.ts +92 -0
  39. package/src/cli/claude.ts +5 -2
  40. package/src/client/link-management-relay.ts +11 -0
  41. package/src/client/machine-listener.ts +6 -2
  42. package/src/codex/account-label.ts +1 -1
  43. package/src/codex/catalog/gather-capture.ts +2 -1
  44. package/src/codex/catalog/metadata.ts +48 -2
  45. package/src/codex/catalog/model-hints.ts +19 -5
  46. package/src/codex/catalog/model-visibility.ts +4 -7
  47. package/src/codex/catalog/native-ultrafast.ts +8 -6
  48. package/src/generated/compatibility-version.json +137 -61
  49. package/src/generated/model-metadata.ts +1 -1
  50. package/src/lib/client-error-body.ts +2 -0
  51. package/src/lib/messages-error-body.ts +3 -1
  52. package/src/lib/optional-shutdown-hooks.ts +55 -5
  53. package/src/lib/process-control.ts +3 -2
  54. package/src/lib/shutdown-budget.ts +5 -0
  55. package/src/link/remote-platform.ts +24 -9
  56. package/src/link/ssh-argv.ts +8 -2
  57. package/src/link/ssh-runner.ts +15 -2
  58. package/src/oauth/m365-copilot-web-session.ts +28 -4
  59. package/src/protocols/dto.ts +24 -12
  60. package/src/protocols/settings.ts +20 -16
  61. package/src/protocols/shadow.ts +2 -3
  62. package/src/protocols/trace.ts +24 -2
  63. package/src/providers/command-code-decision-models.ts +65 -0
  64. package/src/providers/quota.ts +4 -4
  65. package/src/providers/registry/entries-core.ts +18 -7
  66. package/src/providers/registry/entries-extended.ts +41 -0
  67. package/src/providers/registry/model-seeds.ts +42 -0
  68. package/src/providers/resolved-model-policy-merge.ts +8 -0
  69. package/src/providers/resolved-model-policy.ts +185 -165
  70. package/src/providers/slug-codec.ts +5 -0
  71. package/src/server/chat-native-eligibility.ts +5 -0
  72. package/src/server/credential-recovery-attempt.ts +2 -2
  73. package/src/server/gemini-inbound.ts +15 -11
  74. package/src/server/gemini-native-catalog.ts +27 -2
  75. package/src/server/gemini-native-wire.ts +71 -6
  76. package/src/server/gemini-native.ts +129 -34
  77. package/src/server/index/gemini-routes.ts +6 -1
  78. package/src/server/lifecycle.ts +2 -1
  79. package/src/server/management/agent-settings-routes.ts +26 -28
  80. package/src/server/management/api-access.ts +5 -3
  81. package/src/server/management/protocol-routes.ts +3 -1
  82. package/src/server/management/protocol-settings-patch.ts +25 -10
  83. package/src/server/management/shared.ts +20 -5
  84. package/src/server/messages-native-eligibility.ts +4 -0
  85. package/src/server/messages-native-tool-guard.ts +18 -5
  86. package/src/server/request-log-generation-window.ts +7 -2
  87. package/src/server/responses/command-code-decision-refusal.ts +24 -0
  88. package/src/server/responses/compact.ts +2 -2
  89. package/src/server/responses/core-combo.ts +18 -3
  90. package/src/server/responses/core-pipeline.ts +6 -0
  91. package/src/server/responses/sidecar-execution.ts +10 -7
  92. package/src/types/config.ts +2 -0
  93. package/src/usage/expected-prices.ts +17 -0
  94. package/src/usage/telemetry-contract.ts +3 -0
  95. package/gui/dist/assets/App-BI8LQ7Qk.css +0 -1
  96. package/gui/dist/assets/App-CsZ1Gr7S.js +0 -60
  97. package/gui/dist/assets/brand-mark-BebhnAtV.js +0 -1
  98. package/gui/dist/assets/index-BtwVlpeQ.css +0 -2
  99. package/gui/dist/assets/index-CEeMegqE.js +0 -138
  100. package/gui/dist/classic/assets/App-BJgUWNJ8.js +0 -59
  101. package/gui/dist/classic/assets/App-CoiVLRW3.css +0 -1
  102. package/gui/dist/classic/assets/index-B9Jgli_W.js +0 -138
  103. package/gui/dist/classic/assets/usage-companion-chart-vbzDcND0.js +0 -1
@@ -0,0 +1,401 @@
1
+ import type { AdapterEvent, OcxParsedRequest, OcxProviderConfig } from "../../types";
2
+ import type { AdapterRequest, IncomingMeta, ProviderAdapter } from "../base";
3
+ import { getConfigDir } from "../../config/paths";
4
+ import { CODING_AGENT_TOOL_LIMITS } from "../coding-agent/tool-catalog";
5
+ import { ConversationQueueFullError, ownedConversationHandle, withConversationLock } from "./conversation";
6
+ import { STEP_CLI_HOST, STEP_CLI_TOOL_SERVER } from "./constants";
7
+ import { sessionHandlers } from "./events";
8
+ import { mapSessionFailure, refusal } from "./errors";
9
+ import {
10
+ abortSignal,
11
+ composePrompt,
12
+ hasImageInput,
13
+ latestToolResult,
14
+ pendingUserText,
15
+ stepModelId,
16
+ stepThinkingTokens,
17
+ type StepProviderState,
18
+ } from "./projection";
19
+ import { resolveStepCliProfile, STEP_CLI_PROFILE, type StepCliProfile } from "./profiles";
20
+ import {
21
+ beginTurn,
22
+ clearStepCliSessions,
23
+ currentQuery,
24
+ currentTurn,
25
+ endTurn,
26
+ forgetQuery,
27
+ poolFor,
28
+ rememberQuery,
29
+ } from "./registry";
30
+ import { StepSessionError, type StepSessionDeps } from "./session";
31
+ import type { StepConversationHost, StepConversationRef, StepConversationSession } from "./session-pool";
32
+ import { buildStepSdkTools, StepToolCatalogError } from "./tool-bridge";
33
+ import type { StepFrame } from "./stdio-frames";
34
+
35
+ /**
36
+ * Codex turns against a Step Plan subscription.
37
+ *
38
+ * This module is the ORCHESTRATION layer and nothing else: it decides what one turn is, in what order
39
+ * it runs, and when it has produced a terminal event. Converting between the client's request shape
40
+ * and the CLI's is `projection`, mapping the CLI's frames back is `events`, conversation identity and
41
+ * turn ordering are `conversation`, and everything that must outlive a request is `registry`.
42
+ */
43
+ export interface StepCliAdapterDeps extends StepSessionDeps {
44
+ /** Injection seam so tests drive the real `runTurn` path without a CLI. */
45
+ openSession?: StepConversationHost;
46
+ }
47
+
48
+ /**
49
+ * Per-request turn state, keyed by the process that owns it.
50
+ *
51
+ * `createStepCliAdapter` runs once per request, so nothing that has to survive a request boundary can
52
+ * live in its closure: a reverse request arriving during request N+1 would be routed to an instance
53
+ * that no longer exists, and the conversation would silently restart. `devin/trajectory.ts` keeps its
54
+ * conversation map at module scope for the same reason.
55
+ */
56
+
57
+ /**
58
+ * Hard ceiling on waiting for a terminal event from the CLI.
59
+ *
60
+ * The turn would otherwise wait for the client's abort, and a client that never aborts (or a CLI that
61
+ * went quiet) would hold the conversation lock for the life of the process. Set well above
62
+ * StepCode's own 120s tool window so a legitimate slow tool is never cut short.
63
+ */
64
+ const STEP_CLI_TERMINAL_DEADLINE_MS = 10 * 60_000;
65
+
66
+ /**
67
+ * Backoff for re-opening a query the runtime still considers busy.
68
+ *
69
+ * A turn settles when the CLI reports `turn_complete`, which can be a moment before the runtime frees
70
+ * its single query slot. Measured on the real CLI: the very next request on the same conversation then
71
+ * failed with `SESSION_BUSY`. The conversation lock means no other turn of ours is in flight while this
72
+ * runs, so retrying here cannot collide with our own work — it is only bridging the runtime's own
73
+ * handover delay.
74
+ */
75
+ const STEP_CLI_QUERY_RETRY_DELAYS_MS = [200, 600, 1500] as const;
76
+
77
+ /**
78
+ * Run Codex turns against a StepCode subscription.
79
+ *
80
+ * One StepCode process serves one conversation, and this adapter never executes a tool itself: it
81
+ * declares the client's catalog as StepCode SDK tools, allows the permission check the client's own
82
+ * request already implies, and holds the tool call open so the result the client computes on its next
83
+ * request is delivered back into the query the model is running.
84
+ */
85
+ export function createStepCliAdapter(
86
+ provider: OcxProviderConfig,
87
+ deps: StepCliAdapterDeps = {},
88
+ ): ProviderAdapter {
89
+ const profile: StepCliProfile | undefined = resolveStepCliProfile(provider.baseUrl);
90
+
91
+ return {
92
+ name: STEP_CLI_HOST,
93
+
94
+ buildRequest(): AdapterRequest {
95
+ return { url: provider.baseUrl, method: "POST", headers: {}, body: "" };
96
+ },
97
+ async *parseStream(): AsyncGenerator<AdapterEvent> {
98
+ yield {
99
+ type: "error",
100
+ message: "StepCode CLI adapter uses runTurn; the fetch/parseStream path is disabled.",
101
+ };
102
+ },
103
+
104
+ async runTurn(parsed, incoming, emit): Promise<void> {
105
+ if (!profile) {
106
+ emit(
107
+ refusal(
108
+ "This provider row is not pointed at StepCode's canonical destination, so the CLI's own account is never reached.",
109
+ 400,
110
+ "step_cli_profile_mismatch",
111
+ ),
112
+ );
113
+ return;
114
+ }
115
+ if (incoming.abortSignal?.aborted) return emitPreDispatchAbort(emit);
116
+ if (hasImageInput(parsed)) {
117
+ emit(
118
+ refusal(
119
+ "StepCode image input is not enabled because this CLI route has no verified multimodal contract.",
120
+ 400,
121
+ "unsupported_input_modality",
122
+ ),
123
+ );
124
+ return;
125
+ }
126
+
127
+ let tools: ReturnType<typeof buildStepSdkTools>;
128
+ try {
129
+ tools = buildStepSdkTools(parsed, STEP_CLI_TOOL_SERVER);
130
+ } catch (error) {
131
+ if (!(error instanceof StepToolCatalogError)) throw error;
132
+ // Name the numbers. Codex with many MCP servers flattens every remote tool into the function
133
+ // catalog (measured on a real Codex 0.162.0 client: 1749 tools, 2.5 MB), and the shared
134
+ // CLI-family ceiling is 128 tools / 2 MiB — the same bound `qoder`, `codebuddy` and
135
+ // `claude-cli` enforce. An operator seeing only "exceeds tool count limit" cannot tell a
136
+ // malformed catalog from an oversized one.
137
+ const declared = parsed.context.tools?.length ?? 0;
138
+ emit(
139
+ refusal(
140
+ `This request declares ${declared} tools, over the ${CODING_AGENT_TOOL_LIMITS.maxTools}-tool ceiling ` +
141
+ `every CLI-backed provider shares. Codex flattens each MCP server's tools into this catalog, so an ` +
142
+ `MCP-heavy setup reaches the ceiling; drop or disable MCP servers for this provider, or narrow the ` +
143
+ `tool set in the request. Detail: ${error.message}`,
144
+ 400,
145
+ "tool_catalog_invalid",
146
+ ),
147
+ );
148
+ return;
149
+ }
150
+
151
+ let sessions: StepConversationHost;
152
+ try { sessions = deps.openSession ?? poolFor(getConfigDir(), deps, sessionHandlers); }
153
+ catch (error) { emit(mapSessionFailure(error)); return; }
154
+ // Admission owns the namespace; thread headers only select a conversation within it.
155
+ // Requests without caller ownership receive a private process.
156
+ const identified = ownedConversationHandle(parsed, incoming, provider);
157
+ const ref: StepConversationRef = identified
158
+ ? { handle: identified, sessionId: "" }
159
+ : sessions.nextRef();
160
+
161
+ let session!: StepConversationSession;
162
+ try {
163
+ session = await sessions.open(ref);
164
+ await session.handshake();
165
+ } catch (error) {
166
+ await session?.close();
167
+ emit(mapSessionFailure(error));
168
+ return;
169
+ }
170
+
171
+ // From here on this turn owns the conversation's process and its turn state, so anything else
172
+ // arriving for the same conversation waits rather than corrupting it.
173
+ try {
174
+ await withConversationLock(ref.handle, () =>
175
+ driveTurn(parsed, incoming, emit, {
176
+ sessions,
177
+ session,
178
+ ref,
179
+ tools,
180
+ setTimer: deps.setTimeout ?? setTimeout,
181
+ clearTimer: deps.clearTimeout ?? clearTimeout,
182
+ }),
183
+ );
184
+ } catch (error) {
185
+ if (error instanceof ConversationQueueFullError) {
186
+ // The queue cap is a refusal, not a crash, and this caller never owned the conversation: the
187
+ // session it was handed is the one serving the accepted turn and its queue. Closing it here
188
+ // would disconnect every one of them to turn away a single extra request.
189
+ emit(
190
+ refusal(error.message, 409, "step_cli_conversation_busy", "rate_limit_error", true),
191
+ );
192
+ return;
193
+ }
194
+ // Anything else was raised by this turn after it owned the conversation, so the session state
195
+ // is no longer trustworthy and is closed.
196
+ emit(mapSessionFailure(error));
197
+ await session.close();
198
+ } finally {
199
+ // Keyless callers have no cross-request ownership proof. Their process is request-local.
200
+ if (!identified) await session.close();
201
+ }
202
+ },
203
+ };
204
+ }
205
+
206
+ /**
207
+ * Open a query, retrying only while the runtime reports its single slot is still busy.
208
+ *
209
+ * Every other failure propagates immediately: a capability or transport problem must not be turned
210
+ * into three silent attempts.
211
+ */
212
+ async function startQueryWithBusyRetry(
213
+ session: StepConversationSession,
214
+ options: { model: string | undefined; maxThinkingTokens: number | undefined; sdkTools: readonly unknown[]; streamingInput: boolean },
215
+ signal: AbortSignal | undefined,
216
+ delay: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms)),
217
+ ): Promise<{ queryId: string; sessionId: string } | undefined> {
218
+ let attempt = 0;
219
+ while (!signal?.aborted) {
220
+ try {
221
+ return await session.startQuery(options);
222
+ } catch (error) {
223
+ const busy = error instanceof StepSessionError && error.code === "step_cli_session_busy";
224
+ if (!busy || attempt >= STEP_CLI_QUERY_RETRY_DELAYS_MS.length) throw error;
225
+ if (signal?.aborted) return;
226
+ await delay(STEP_CLI_QUERY_RETRY_DELAYS_MS[attempt]!);
227
+ attempt += 1;
228
+ }
229
+ }
230
+ }
231
+
232
+ function emitPreDispatchAbort(emit: (event: AdapterEvent) => void): void {
233
+ emit({ type: "error", message: "StepCode turn was aborted before start.", retryable: false });
234
+ }
235
+
236
+ async function driveTurn(
237
+ parsed: OcxParsedRequest,
238
+ incoming: IncomingMeta,
239
+ emit: (event: AdapterEvent) => void,
240
+ context: {
241
+ sessions: StepConversationHost;
242
+ session: StepConversationSession;
243
+ ref: StepConversationRef;
244
+ tools: ReturnType<typeof buildStepSdkTools>;
245
+ setTimer: typeof setTimeout;
246
+ clearTimer: typeof clearTimeout;
247
+ },
248
+ ): Promise<void> {
249
+ if (incoming.abortSignal?.aborted) return emitPreDispatchAbort(emit);
250
+ const { sessions, session, ref, tools, setTimer, clearTimer } = context;
251
+ // A matching held result resumes its original query. An abandoned call must finish
252
+ // unwinding without a turn before the replacement is registered.
253
+ const held = sessions.takeHeldTool(ref);
254
+ const heldResult = held ? latestToolResult(parsed) : undefined;
255
+ // Matched by CALL ID, never by position: a client may follow a tool call with a new user
256
+ // message instead of a result, in which case the newest result in the transcript belongs to an
257
+ // earlier call and delivering it would answer the wrong question.
258
+ // A client that cancels the call and sends only new user text has no tool result in its
259
+ // transcript at all, so `heldResult` can be undefined while `held` exists.
260
+ const heldMatches = held !== undefined && heldResult !== undefined && heldResult.toolCallId === held.callId;
261
+ // This turn IS the answer to a captured call: the model already has the instruction and is
262
+ // mid-query, so nothing is prompted again.
263
+ const continuedQuery = Boolean(held) && heldMatches;
264
+ // The client sent something other than the held call's result — typically a new user message.
265
+ // The query that owned the call is unwinding; leaving it running would make this request's own
266
+ // text unstartable, and swallowing that text would lose the user's turn entirely.
267
+ const abandonedQueryId = Boolean(held) && !heldMatches;
268
+
269
+ const catalogKey = JSON.stringify(tools.sdkTools);
270
+ if (held && (held.queryId !== currentQuery(session) || held.catalogKey !== catalogKey)) {
271
+ emit(refusal("The held StepCode call belongs to a different query or tool catalog.", 409, "step_cli_tool_owner_mismatch"));
272
+ await session.close();
273
+ return;
274
+ }
275
+
276
+ // Text is suppressed ONLY when this turn really is the answer to the held call; a turn that
277
+ // abandoned the call still carries the user's message and must keep it.
278
+ const userText = continuedQuery ? undefined : pendingUserText(parsed);
279
+ if (!continuedQuery && !userText) {
280
+ emit(
281
+ refusal(
282
+ "StepCode carries conversation history inside its own process, so a turn must end with either user text or a tool result.",
283
+ 400,
284
+ "step_cli_no_user_text",
285
+ ),
286
+ );
287
+ return;
288
+ }
289
+
290
+ if (abandonedQueryId && held) {
291
+ // Detach the old owner before releasing its hold: completion can arrive synchronously.
292
+ endTurn(session);
293
+ forgetQuery(session);
294
+ session.resolveHeldToolResult(
295
+ { id: held.frameId, method: "sdk_tool.invoke" } as StepFrame,
296
+ { content: [{ type: "text", text: "" }], isError: true },
297
+ );
298
+ await session.interrupt(held.queryId);
299
+ await session.endInput(held.queryId);
300
+ }
301
+
302
+ let settle!: () => void;
303
+ const done = new Promise<void>(resolve => {
304
+ settle = resolve;
305
+ });
306
+ beginTurn(session, {
307
+ ref,
308
+ pool: sessions,
309
+ emit,
310
+ settle,
311
+ emittedNames: tools.emittedNameMap,
312
+ catalogKey,
313
+ ...(continuedQuery && held ? { queryId: held.queryId } : {}),
314
+ });
315
+
316
+ // Registered FIRST, delivered second. See the comment above: the CLI can answer the moment it
317
+ // receives the result.
318
+ if (held && continuedQuery) {
319
+ const delivered = session.resolveHeldToolResult(
320
+ { id: held.frameId, method: "sdk_tool.invoke" } as StepFrame,
321
+ heldResult!,
322
+ );
323
+ if (!delivered) {
324
+ endTurn(session);
325
+ emit(
326
+ refusal(
327
+ "The held StepCode tool call expired before the tool result arrived; StepCode only waits two minutes for one.",
328
+ 504,
329
+ "step_cli_tool_result_too_late",
330
+ "upstream_error",
331
+ ),
332
+ );
333
+ await session.close();
334
+ return;
335
+ }
336
+ }
337
+
338
+ let queryId: string | undefined;
339
+ let deadlineTimer: unknown;
340
+ try {
341
+ if (!continuedQuery) {
342
+ const started = await startQueryWithBusyRetry(session, {
343
+ model: stepModelId(parsed.modelId),
344
+ maxThinkingTokens: stepThinkingTokens(parsed),
345
+ sdkTools: tools.sdkTools,
346
+ streamingInput: true,
347
+ }, incoming.abortSignal);
348
+ if (!started) {
349
+ endTurn(session);
350
+ settle();
351
+ return emitPreDispatchAbort(emit);
352
+ }
353
+ queryId = started.queryId;
354
+ rememberQuery(session, queryId);
355
+ if (!incoming.abortSignal?.aborted) {
356
+ await session.sendInput(queryId, composePrompt(parsed, userText ?? ""));
357
+ }
358
+ }
359
+ } catch (error) {
360
+ endTurn(session);
361
+ settle();
362
+ emit(mapSessionFailure(error));
363
+ await session.close();
364
+ return;
365
+ }
366
+
367
+ // The turn owns the response until it settles: text, a captured tool call, a completion, the
368
+ // client's abort, or the hard deadline. Returning before that leaves the stream without a
369
+ // terminal event; never returning would hold the conversation lock forever.
370
+ await Promise.race([
371
+ done,
372
+ abortSignal(incoming),
373
+ new Promise<void>(resolve => {
374
+ deadlineTimer = setTimer(resolve, STEP_CLI_TERMINAL_DEADLINE_MS);
375
+ }),
376
+ ]);
377
+ clearTimer(deadlineTimer as never);
378
+ if (currentTurn(session) === undefined) return;
379
+
380
+ // The turn is still registered, so nothing terminated it: either the client aborted, or the CLI
381
+ // went quiet. Either way the query is still running inside StepCode, and since it serves one
382
+ // query at a time the NEXT request for this conversation would be rejected or blocked by it.
383
+ // Interrupt it, and close the session when the interrupt cannot be confirmed.
384
+ endTurn(session);
385
+ emit({
386
+ type: "error",
387
+ message: "The StepCode turn ended without a terminal event.",
388
+ status: 502,
389
+ errorType: "upstream_error",
390
+ code: "step_cli_turn_abandoned",
391
+ retryable: true,
392
+ });
393
+ settle();
394
+ if (queryId) {
395
+ await session.interrupt(queryId);
396
+ if (session.closed) return;
397
+ }
398
+ await session.close();
399
+ }
400
+
401
+ export { STEP_CLI_PROFILE, clearStepCliSessions };
@@ -0,0 +1,11 @@
1
+ /** Adapter identity used in telemetry and in `providerConfig.adapter`. */
2
+ export const STEP_CLI_HOST = "step-cli";
3
+
4
+ /** Registry provider id. Kept separate from the adapter name so a future second adapter can coexist. */
5
+ export const STEP_CLI_PROVIDER_ID = "step-cli";
6
+
7
+ /** Namespace StepCode registers this proxy's declared tools under. */
8
+ export const STEP_CLI_TOOL_SERVER = "ocx";
9
+
10
+ /** `providerState` slot carrying the conversation handle between requests. */
11
+ export const STEP_CLI_CONTINUATION_KEY = "step";
@@ -0,0 +1,159 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { OcxParsedRequest, OcxProviderConfig } from "../../types";
3
+ import type { IncomingMeta } from "../base";
4
+
5
+ /**
6
+ * Conversation identity and turn ordering.
7
+ *
8
+ * Both live together because they answer one question: which turn may run, and on whose state. A
9
+ * conversation is neither a model id nor a request — it is the thing that owns a StepCode process.
10
+ */
11
+
12
+ /**
13
+ * Identify the conversation this request belongs to.
14
+ *
15
+ * StepCode keeps a conversation only inside one process, so every request of a Codex thread has to
16
+ * land on the same session. The thread identity is what Codex already sends on EVERY request —
17
+ * `thread-id`, then the session-affinity headers — which is the resolution `devin`, `zed`, `cursor`
18
+ * and `google` use, and it works on the first request of a conversation. `previous_response_id` and
19
+ * the proxy's continuation store are only fallbacks: depending on persisted provider state would mean
20
+ * a conversation silently restarting whenever that store misses an entry.
21
+ */
22
+ export function conversationHandle(parsed: OcxParsedRequest, incoming: IncomingMeta): string | undefined {
23
+ const own = incoming.headers.get("thread-id")?.trim() || parsed._codexOwnThreadId?.trim();
24
+ if (own) return `own:${own}`;
25
+ const affinity =
26
+ incoming.headers.get("session_id")?.trim() ||
27
+ incoming.headers.get("session-id")?.trim() ||
28
+ incoming.headers.get("x-session-affinity")?.trim();
29
+ if (affinity) return `session:${affinity}`;
30
+ // A parent thread id belongs to the SUB-agent it spawned, so it must not be read as this turn's own
31
+ // conversation; it is only consulted when no parent is present.
32
+ if (!incoming.headers.has("x-codex-parent-thread-id")) {
33
+ const client = parsed._clientThreadId?.trim();
34
+ if (client) return `client:${client}`;
35
+ }
36
+ if (parsed.previousResponseId) return `response:${parsed.previousResponseId}`;
37
+ // Deliberately undefined rather than a shared "default": Claude Code, Grok Build and generic Chat
38
+ // clients all send requests with no identity, and collapsing them onto one handle would let one
39
+ // client read another's context and deliver its tool result into another's query. The caller mints
40
+ // a private ref instead, so an identity-less request gets its own process and forgets it.
41
+ return undefined;
42
+ }
43
+
44
+ /** Headers select a conversation only inside the admission principal's provider namespace. */
45
+ export function ownedConversationHandle(
46
+ parsed: OcxParsedRequest,
47
+ incoming: IncomingMeta,
48
+ provider: OcxProviderConfig,
49
+ ): string | undefined {
50
+ const principal = parsed._reasoningReplayScope?.clientPrincipalId;
51
+ const conversation = conversationHandle(parsed, incoming);
52
+ if (!principal || !conversation) return undefined;
53
+ const identity = parsed._reasoningReplayScope?.current;
54
+ // Reuse the server-owned replay principal and physical provider identity. Never accept a
55
+ // principal, provider name or continuation handle from request headers/providerState.
56
+ return createHash("sha256").update(JSON.stringify([
57
+ "step-cli", principal, incoming.providerName ?? identity?.providerName ?? "",
58
+ provider.adapter, provider.baseUrl, identity?.providerDestinationIdentity ?? "",
59
+ identity?.credentialIdentity ?? "", conversation,
60
+ ])).digest("hex");
61
+ }
62
+
63
+ /** How many turns may queue behind one conversation before a caller is told to retry. */
64
+ export const MAX_QUEUED_TURNS = 2;
65
+
66
+ /**
67
+ * Hard ceiling on waiting for a terminal event from the CLI.
68
+ *
69
+ * The turn would otherwise wait for the client's abort, and a client that never aborts (or a CLI that
70
+ * went quiet) would hold the conversation lock for the life of the process. Set well above
71
+ * StepCode's own 120s tool window so a legitimate slow tool is never cut short.
72
+ */
73
+
74
+ interface ConversationLock {
75
+ /** Settles when every queued turn ahead of this one has finished. */
76
+ readonly chain: Promise<void>;
77
+ /** Turns waiting or running; used to refuse an unbounded pile-up. */
78
+ waiters: number;
79
+ }
80
+
81
+ /**
82
+ * Per-conversation serialisation.
83
+ *
84
+ * StepCode serves ONE query per process, and this proxy's turn state is keyed by that process, so two
85
+ * overlapping turns on one conversation overwrite each other's runtime, interrupt each other's query
86
+ * and close each other's session — which is exactly what two clients sharing a `thread-id` produce,
87
+ * and it was measured as both requests failing with `SESSION_NOT_FOUND` and `step_cli_session_closed`.
88
+ * Turns are therefore queued in arrival order.
89
+ *
90
+ * Sequential traffic is unaffected: a turn that finishes before the next arrives takes an empty chain
91
+ * and completes without yielding.
92
+ */
93
+
94
+ /**
95
+ * Per-conversation serialisation.
96
+ *
97
+ * StepCode serves ONE query per process, and this proxy's turn state is keyed by that process, so two
98
+ * overlapping turns on one conversation overwrite each other's runtime, interrupt each other's query
99
+ * and close each other's session — which is exactly what two clients sharing a `thread-id` produce,
100
+ * and it was measured as both requests failing with `SESSION_NOT_FOUND` and `step_cli_session_closed`.
101
+ * Turns are therefore queued in arrival order.
102
+ *
103
+ * Sequential traffic is unaffected: a turn that finishes before the next arrives takes an empty chain
104
+ * and completes without yielding.
105
+ */
106
+ const conversationLocks = new Map<string, ConversationLock>();
107
+
108
+ /**
109
+ * The caller was turned away at the queue cap and never owned the conversation.
110
+ *
111
+ * A distinct class so the adapter can tell an admission refusal (the current owner and its queue are
112
+ * untouched and must stay that way) from a failure raised by a turn that did own the conversation.
113
+ */
114
+ export class ConversationQueueFullError extends Error {
115
+ override readonly name = "ConversationQueueFullError";
116
+ }
117
+
118
+ /**
119
+ * Exported for its regression test: the queue cap is the only path in this adapter that refuses
120
+ * rather than degrades, and it has to be observable to be trusted.
121
+ */
122
+
123
+ /**
124
+ * Exported for its regression test: the queue cap is the only path in this adapter that refuses
125
+ * rather than degrades, and it has to be observable to be trusted.
126
+ */
127
+ export async function withConversationLock<T>(handle: string, task: () => Promise<T>): Promise<T> {
128
+ const existing = conversationLocks.get(handle);
129
+ if (existing && existing.waiters >= MAX_QUEUED_TURNS + 1) {
130
+ throw new ConversationQueueFullError(
131
+ `StepCode serves one turn per conversation at a time and ${existing.waiters} are already queued for this one.`,
132
+ );
133
+ }
134
+ const previous = existing?.chain ?? Promise.resolve();
135
+ let release!: () => void;
136
+ const gate = new Promise<void>(resolve => {
137
+ release = resolve;
138
+ });
139
+ const chain = previous.then(
140
+ () => gate,
141
+ () => gate,
142
+ );
143
+ const entry: ConversationLock = { chain, waiters: (existing?.waiters ?? 0) + 1 };
144
+ conversationLocks.set(handle, entry);
145
+ void chain.finally(() => {
146
+ // Drop the entry once this turn's chain drains, unless a later turn already replaced it — otherwise
147
+ // the map would retain one settled promise per conversation handle for the life of the process.
148
+ if (conversationLocks.get(handle) === entry) conversationLocks.delete(handle);
149
+ });
150
+ await previous.catch(() => undefined);
151
+ try {
152
+ return await task();
153
+ } finally {
154
+ entry.waiters -= 1;
155
+ release();
156
+ }
157
+ }
158
+
159
+ /** One pool per OpenCodex home, so two homes in one process never share a StepCode session. */
@@ -0,0 +1,49 @@
1
+ import { baseScopedEnv } from "../coding-agent/turn";
2
+ import { stepCliSessionDir } from "./profiles";
3
+
4
+ /**
5
+ * Scoped child-process environment for one StepCode session (§六/§十四).
6
+ *
7
+ * `baseScopedEnv` already drops every inherited variable outside a short key allowlist, so the CLI
8
+ * cannot be steered by a stray `STEP_*` value in the operator's shell. Two StepCode-specific rules
9
+ * are layered on top:
10
+ *
11
+ * 1. `USER` is restored because StepCode resolves its own sign-in by account name. Measured with
12
+ * `env -i`: `USER` alone reports a signed-in machine, `LOGNAME` alone or neither does not. Without
13
+ * it a signed-in host answers "not logged in" and this provider has no account to spend.
14
+ * 2. The session directory is redirected into state this proxy owns, so a proxied conversation never
15
+ * lands in the operator's `~/.stepcode/agent/sessions` tree.
16
+ *
17
+ * No credential is layered here on purpose. StepCode reads its own `auth.json`, which is the
18
+ * property this provider exists for: the token never enters OpenCodex's config, key store, or any
19
+ * child environment. There is deliberately no `STEPCODE_AUTH_PATH` here for the same reason — an
20
+ * explicit auth path would be a second credential reference for this adapter to keep correct.
21
+ */
22
+ export function buildStepCliEnv(
23
+ openCodexHome: string,
24
+ hostEnv: NodeJS.ProcessEnv = process.env,
25
+ ): Record<string, string> {
26
+ const env: Record<string, string> = { ...baseScopedEnv() };
27
+ const user = hostEnv.USER;
28
+ if (user) env.USER = user;
29
+ env.STEP_CODING_AGENT_SESSION_DIR = stepCliSessionDir(openCodexHome);
30
+ return env;
31
+ }
32
+
33
+ /**
34
+ * Keep the operator's StepCode profile (`step_plan`, `step_plan_oversea`, …) intact.
35
+ *
36
+ * The profile lives in `auth.json` beside the credential and decides both the model endpoint and the
37
+ * region. It is never overridden here: a preset that picked a region for this adapter would be a
38
+ * second source of truth for exactly the thing the CLI already owns.
39
+ */
40
+ export const STEP_CLI_FORBIDDEN_ENV_PREFIXES: readonly string[] = Object.freeze([
41
+ "STEP_",
42
+ "STEPCODE_",
43
+ "OPENCODEX_",
44
+ ]);
45
+
46
+ /** Report any env key a caller is about to pass that the scoped builder must never forward. */
47
+ export function forbiddenStepCliEnvKeys(keys: readonly string[]): string[] {
48
+ return keys.filter(key => STEP_CLI_FORBIDDEN_ENV_PREFIXES.some(prefix => key.startsWith(prefix)));
49
+ }