@bitkyc08/opencodex 2.100.6 → 2.100.7

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-BfoDjNBU.js +65 -0
  2. package/gui/dist/assets/App-hklyKJR5.css +1 -0
  3. package/gui/dist/assets/{Tray-CVqm4S4W.js → Tray-BN6pxM_V.js} +1 -1
  4. package/gui/dist/assets/brand-mark-CDZQ-wa9.js +1 -0
  5. package/gui/dist/assets/index-B85uU8rK.css +2 -0
  6. package/gui/dist/assets/index-Bt9ze3XN.js +138 -0
  7. package/gui/dist/assets/{segment-thumb-features-COdzmORE.js → segment-thumb-features-BM5n8NMX.js} +1 -1
  8. package/gui/dist/classic/assets/App-D4cjNg2I.js +64 -0
  9. package/gui/dist/classic/assets/App-DSivR528.css +1 -0
  10. package/gui/dist/classic/assets/{Tray-BDlcOLDK.js → Tray-DTgGR7wt.js} +1 -1
  11. package/gui/dist/classic/assets/index-ALDeKRg9.js +138 -0
  12. package/gui/dist/classic/assets/usage-companion-chart-BC-Nos9Q.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,76 @@
1
+ import type { AdapterEvent } from "../../types";
2
+ import type { StepProtocolErrorPayload } from "./stdio-frames";
3
+
4
+ type StepSessionErrorCode =
5
+ | "step_cli_session_failed"
6
+ | "step_cli_session_busy"
7
+ | "step_cli_binary_missing"
8
+ | "step_cli_capability_missing"
9
+ | "step_cli_protocol_violation"
10
+ | "step_cli_cleanup_failed"
11
+ | "step_cli_workspace_unavailable"
12
+ | "step_cli_not_logged_in"
13
+ | "step_cli_subscription_cooldown"
14
+ | "timeout";
15
+
16
+ export class StepSessionError extends Error {
17
+ constructor(message: string, readonly code: StepSessionErrorCode = "step_cli_session_failed") {
18
+ super(message);
19
+ this.name = "StepSessionError";
20
+ }
21
+ }
22
+
23
+ const SESSION_FAILURE = "StepCode could not complete the request.";
24
+
25
+ /** Child diagnostics are classifier input only. The resulting error is safe to publish. */
26
+ export function classifyStepChildError({ code, message }: StepProtocolErrorPayload): StepSessionError {
27
+ if (code === "SESSION_BUSY") {
28
+ return new StepSessionError("StepCode is still finishing its previous query.", "step_cli_session_busy");
29
+ }
30
+ if (/not signed in|please run \/login|未登录/i.test(message)) {
31
+ return new StepSessionError("StepCode is not signed in. Run `step login` once and retry.", "step_cli_not_logged_in");
32
+ }
33
+ if (/quota|credit|429|rate limit/i.test(message)) {
34
+ return new StepSessionError("StepCode subscription temporarily rate limited or out of quota.", "step_cli_subscription_cooldown");
35
+ }
36
+ if (/did not answer .* in time|timed out/i.test(message)) {
37
+ return new StepSessionError("StepCode timed out while processing the request.", "timeout");
38
+ }
39
+ return new StepSessionError(SESSION_FAILURE);
40
+ }
41
+
42
+ /**
43
+ * Failure text for this route.
44
+ *
45
+ * Every other failure on a CLI-backed provider becomes an event on the client stream rather than a
46
+ * thrown error, so a refusal is what the operator actually reads. Keeping the mapping in one module
47
+ * means the wording and the status a client can retry on are decided in one place.
48
+ */
49
+
50
+ export function refusal(
51
+ message: string,
52
+ status: number,
53
+ code: string,
54
+ errorType = "invalid_request_error",
55
+ retryable = false,
56
+ ): AdapterEvent {
57
+ return { type: "error", message, status, errorType, code, retryable };
58
+ }
59
+
60
+ /** Translate a transport failure into the actionable error an operator can act on. */
61
+ export function mapSessionFailure(error: unknown): AdapterEvent {
62
+ const failure = error instanceof StepSessionError ? error : new StepSessionError(SESSION_FAILURE);
63
+ switch (failure.code) {
64
+ case "step_cli_binary_missing":
65
+ case "step_cli_capability_missing":
66
+ return refusal(failure.message, 400, failure.code);
67
+ case "step_cli_not_logged_in":
68
+ return refusal(failure.message, 401, failure.code, "authentication_error");
69
+ case "step_cli_subscription_cooldown":
70
+ return refusal(failure.message, 429, failure.code, "rate_limit_error");
71
+ case "timeout":
72
+ return refusal(failure.message, 504, failure.code, "upstream_error", true);
73
+ default:
74
+ return refusal(failure.message, 502, failure.code, "upstream_error", true);
75
+ }
76
+ }
@@ -0,0 +1,227 @@
1
+ import type { AdapterEvent } from "../../types";
2
+ import type { StepSessionEvent } from "./session";
3
+ import type { StepConversationSession } from "./session-pool";
4
+ import { asRecord, continuationFor, toUsage } from "./projection";
5
+ import {
6
+ assistantUsage,
7
+ currentQuery,
8
+ currentTurn,
9
+ endTurn,
10
+ forgetQuery,
11
+ recordAssistantUsage,
12
+ } from "./registry";
13
+ import { resolveStepToolName } from "./tool-bridge";
14
+ import type { StepFrame } from "./stdio-frames";
15
+
16
+ /**
17
+ * What the CLI says, and what this peer owes it in return.
18
+ *
19
+ * Every reverse request is ANSWERED, including when no turn is registered or the hold already
20
+ * expired: a dropped reverse request leaves the runtime waiting out its own 60s/120s window with no
21
+ * diagnostic and nothing for the client to act on.
22
+ */
23
+
24
+ /**
25
+ * A reverse request the CLI is waiting on this peer to answer.
26
+ *
27
+ * `permission.request` is allowed only for the owning query's declared catalog. A
28
+ * `sdk_tool.invoke` is deliberately NOT answered here: its result only exists once the
29
+ * client has executed the tool and sent its next request, and answering it is how that result reaches
30
+ * the model inside the query the model is already running.
31
+ */
32
+ /**
33
+ * Exported for its regression tests: every reverse request must be ANSWERED, and the tests drive this
34
+ * exact function rather than a mirror of it.
35
+ */
36
+ export function handleReverseRequest(session: StepConversationSession, frame: StepFrame): void {
37
+ const payload = asRecord(frame.payload);
38
+ const expired = payload.__expired === true;
39
+ const turn = currentTurn(session);
40
+ const queryId = turn?.queryId;
41
+ // The SDK host sends a sessionId and allocates req_<n> and q_<n> from the same counter.
42
+ // A callback from before this query cannot acquire it, even though SDK callbacks omit queryId.
43
+ const requestSerial = /^req_(\d+)$/.exec(frame.id)?.[1];
44
+ const querySerial = queryId && /^q_(\d+)$/.exec(queryId)?.[1];
45
+ const ownsQuery = queryId !== undefined && currentQuery(session) === queryId
46
+ && session.sessionId !== undefined && frame.sessionId === session.sessionId
47
+ && (payload.queryId === undefined || payload.queryId === queryId)
48
+ && requestSerial !== undefined && querySerial !== undefined
49
+ && Number.isSafeInteger(Number(requestSerial)) && Number.isSafeInteger(Number(querySerial))
50
+ && Number(requestSerial) > Number(querySerial);
51
+
52
+ if (expired) {
53
+ // The hold elapsed, so the client can never answer this call. Refuse it so StepCode stops waiting
54
+ // instead of burning its own window, and do NOT re-dispatch: the client already received this tool
55
+ // call, and a second `tool_call_start` for the same id would be a duplicate.
56
+ session.refuseToolCall(
57
+ frame,
58
+ "The client did not return a tool result inside the window this transport holds a call for.",
59
+ );
60
+ return;
61
+ }
62
+
63
+ // Even with no turn registered, a reverse request must be ANSWERED. Dropping it leaves the runtime
64
+ // waiting out its own 60s/120s window with nothing to show for it, and the client has no way to
65
+ // learn that the call was silently dropped.
66
+ if (frame.method === "permission.request") {
67
+ const toolName = typeof payload.toolName === "string" ? payload.toolName : "";
68
+ if (ownsQuery && turn && resolveStepToolName(toolName, turn.emittedNames)) session.allowPermission(frame);
69
+ else session.denyPermission(frame, "No active query owns this declared tool permission.");
70
+ return;
71
+ }
72
+
73
+ if (frame.method === "sdk_tool.invoke" && (!turn || !ownsQuery)) {
74
+ session.refuseToolCall(
75
+ frame,
76
+ "OpenCodex is not expecting a tool call for this conversation right now, so it was not executed.",
77
+ );
78
+ return;
79
+ }
80
+
81
+ if (!turn) {
82
+ session.denyPermission(frame, `OpenCodex cannot handle ${frame.method ?? "this request"} outside a turn.`);
83
+ return;
84
+ }
85
+
86
+ if (frame.method === "sdk_tool.invoke") {
87
+ const payload = (frame.payload ?? {}) as {
88
+ input?: unknown;
89
+ toolUseId?: string;
90
+ serverName?: string;
91
+ toolName?: string;
92
+ };
93
+ // The descriptor's `toolName` is BARE; the name StepCode registered is
94
+ // `${serverName}__${toolName}`. Recomposing the wire name from both fields is what makes the
95
+ // lookup work, and a lookup that misses has to refuse rather than guess.
96
+ const serverName = typeof payload.serverName === "string" ? payload.serverName : "";
97
+ const bareName = typeof payload.toolName === "string" ? payload.toolName : "";
98
+ const wireName = serverName && bareName ? `${serverName}__${bareName}` : bareName;
99
+ const resolved = resolveStepToolName(wireName, turn.emittedNames);
100
+ if (!resolved) {
101
+ session.refuseToolCall(
102
+ frame,
103
+ `OpenCodex did not declare ${wireName || "this tool"} for this turn, so the call was not executed.`,
104
+ );
105
+ return;
106
+ }
107
+ const callId =
108
+ typeof payload.toolUseId === "string" && payload.toolUseId.length > 0
109
+ ? payload.toolUseId
110
+ : `call_${frame.id}`;
111
+ turn.pool.rememberHeldTool(turn.ref, { frameId: frame.id, callId, queryId: queryId!, catalogKey: turn.catalogKey });
112
+ turn.emit({ type: "tool_call_start", id: callId, name: resolved });
113
+ turn.emit({ type: "tool_call_delta", arguments: JSON.stringify(asRecord(payload.input)) });
114
+ turn.emit({ type: "tool_call_end" });
115
+ turn.emit({
116
+ type: "done",
117
+ stopReason: "tool_use",
118
+ providerState: continuationFor(turn.ref, session.sessionId),
119
+ });
120
+ endTurn(session);
121
+ turn.settle();
122
+ return;
123
+ }
124
+
125
+ // An unrecognised reverse method still needs an answer rather than being left to expire inside the
126
+ // model's context.
127
+ session.denyPermission(frame, `OpenCodex does not handle ${frame.method ?? "this request"}.`);
128
+ }
129
+
130
+ /**
131
+ * Map one runtime frame onto the client's event stream.
132
+ *
133
+ * The framed protocol nests the projected message: a frame is `{queryId, message: {...}}` and the
134
+ * event type lives at `message.type`, NOT at `payload.type` the way `step --mode json` prints it.
135
+ * Reading the wrong level makes every turn look idle until it times out, so the nesting is resolved
136
+ * once here and every branch below works off the inner message.
137
+ */
138
+ /**
139
+ * Exported with `handleReverseRequest` for the same reason: the CLI's event vocabulary is the other
140
+ * half of this transport, and the terminal-event mapping had no test at all until the suite pointed
141
+ * out that it was the one thing a fake process must be able to deliver.
142
+ */
143
+
144
+ /**
145
+ * Map one runtime frame onto the client's event stream.
146
+ *
147
+ * The framed protocol nests the projected message: a frame is `{queryId, message: {...}}` and the
148
+ * event type lives at `message.type`, NOT at `payload.type` the way `step --mode json` prints it.
149
+ * Reading the wrong level makes every turn look idle until it times out, so the nesting is resolved
150
+ * once here and every branch below works off the inner message.
151
+ */
152
+ /**
153
+ * Exported with `handleReverseRequest` for the same reason: the CLI's event vocabulary is the other
154
+ * half of this transport, and the terminal-event mapping had no test at all until the suite pointed
155
+ * out that it was the one thing a fake process must be able to deliver.
156
+ */
157
+ export function handleRuntimeEvent(session: StepConversationSession, frame: StepFrame): void {
158
+ const turn = currentTurn(session);
159
+ if (!turn) return;
160
+ const payload = asRecord(frame.payload);
161
+ if (!turn.queryId || payload.queryId !== turn.queryId || currentQuery(session) !== turn.queryId) return;
162
+ const message = asRecord(payload.message ?? payload);
163
+ const type = typeof message.type === "string" ? message.type : undefined;
164
+
165
+ if (type === "stream_event") {
166
+ const event = asRecord(message.event);
167
+ const delta = asRecord(event.delta);
168
+ if (delta.type === "text_delta" && typeof delta.text === "string") {
169
+ turn.emit({ type: "text_delta", text: delta.text });
170
+ return;
171
+ }
172
+ if (delta.type === "thinking_delta" && typeof delta.thinking === "string") {
173
+ turn.emit({ type: "thinking_delta", thinking: delta.thinking });
174
+ }
175
+ return;
176
+ }
177
+
178
+ if (type === "assistant") {
179
+ const usage = toUsage(asRecord(asRecord(message.message).usage));
180
+ if (usage) recordAssistantUsage(session, usage);
181
+ return;
182
+ }
183
+
184
+ if (type === "status" && (message.status === "turn_complete" || message.status === "done")) {
185
+ const usage = assistantUsage(session);
186
+ turn.emit({
187
+ type: "done",
188
+ ...(usage ? { usage } : {}),
189
+ stopReason: "stop",
190
+ providerState: continuationFor(turn.ref, session.sessionId),
191
+ });
192
+ endTurn(session);
193
+ turn.settle();
194
+ // Release the runtime's single query slot for this conversation's next turn. Skipped when a tool
195
+ // call was captured, which ends the turn earlier and keeps the query alive on purpose.
196
+ const queryId = currentQuery(session);
197
+ if (queryId) {
198
+ forgetQuery(session);
199
+ // Observe the derived rejection here. The pool can still await the session's cleanup receipt.
200
+ void session.endInput(queryId).catch(() => session.close()).catch(() => {});
201
+ }
202
+ return;
203
+ }
204
+
205
+ if (type === "permission_denied") {
206
+ turn.emit({
207
+ type: "error",
208
+ message: "StepCode refused a tool call.",
209
+ status: 400,
210
+ errorType: "invalid_request_error",
211
+ code: "step_cli_permission_denied",
212
+ retryable: false,
213
+ });
214
+ endTurn(session);
215
+ turn.settle();
216
+ }
217
+ }
218
+
219
+ export const sessionHandlers = {
220
+ onEvent(event: StepSessionEvent): void {
221
+ if (event.type === "reverse_request") {
222
+ handleReverseRequest(event.session, event.frame);
223
+ return;
224
+ }
225
+ handleRuntimeEvent(event.session, event.frame);
226
+ },
227
+ };
@@ -0,0 +1,134 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir, tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+
5
+ import {
6
+ clearCodingAgentBinaryCache,
7
+ resolveProfileByBaseUrl,
8
+ whichFromPath,
9
+ type CodingAgentProviderProfile,
10
+ type WhichFn,
11
+ } from "../coding-agent/profile";
12
+
13
+ /**
14
+ * Official StepCode CLI (阶跃星辰) as a transport for a Step Plan subscription.
15
+ *
16
+ * StepCode has no region-scoped variants in this registry: `step login` records one profile
17
+ * (`step_plan`, `step_plan_oversea`, `platform_cn`, `platform_oversea`) inside the CLI's own
18
+ * `auth.json`, and the CLI is the only component that reads it. The registry therefore selects the
19
+ * profile by provider id, not by URL, and fails closed on any destination the CLI does not own.
20
+ */
21
+ export interface StepCliProfile extends CodingAgentProviderProfile {
22
+ family: "step";
23
+ }
24
+
25
+ export const STEP_CLI_PROFILE: StepCliProfile = {
26
+ providerId: "step-cli",
27
+ family: "step",
28
+ region: "global",
29
+ label: "StepCode CLI (subscription)",
30
+ /**
31
+ * The destination the subscription's traffic actually reaches. OpenCodex never sends this host:
32
+ * the CLI performs every request, so the value exists to fail closed when a row is repointed at
33
+ * something this adapter cannot speak to.
34
+ */
35
+ canonicalBaseUrl: "https://api.stepfun.com/step_plan",
36
+ /**
37
+ * StepCode installs itself to `~/.stepcode/bin/step` rather than onto PATH, so the PATH scan is
38
+ * only the first attempt — see {@link findStepCliBinary}.
39
+ */
40
+ binaryCandidates: ["step"],
41
+ /**
42
+ * Deliberately absent: the CLI owns its sign-in (`step login`), so this provider neither requires
43
+ * nor injects a credential and has no secret to redact. Mirrors the `claude-cli` row.
44
+ */
45
+ installHint: "install the StepCode CLI, then sign in once with `step login`",
46
+ documentationUrl: "https://platform.stepfun.com/docs/zh/step-plan/quick-start",
47
+ };
48
+
49
+ export const STEP_CLI_PROFILES: readonly StepCliProfile[] = [STEP_CLI_PROFILE];
50
+
51
+ export function resolveStepCliProfile(baseUrl: string | undefined): StepCliProfile | undefined {
52
+ return resolveProfileByBaseUrl(STEP_CLI_PROFILES, baseUrl) as StepCliProfile | undefined;
53
+ }
54
+
55
+ export const clearStepCliBinaryCache = clearCodingAgentBinaryCache;
56
+
57
+ /**
58
+ * Locate the StepCode executable before any request is dispatched.
59
+ *
60
+ * The self-install location is checked after PATH and only for the bare `step` candidate: a PATH
61
+ * entry an operator added by hand wins, while a service or GUI launch with a stale PATH still finds
62
+ * the install it owns. Mirrors {@link findClaudeCliBinary}'s ordering.
63
+ */
64
+ export function findStepCliBinary(
65
+ candidate: string,
66
+ pathLookup: WhichFn = whichFromPath,
67
+ userHome = homedir(),
68
+ platform: NodeJS.Platform = process.platform,
69
+ ): string | undefined {
70
+ const onPath = pathLookup(candidate);
71
+ if (onPath) return resolve(onPath);
72
+ if (candidate !== "step") return undefined;
73
+ const installed = join(userHome, ".stepcode", "bin", platform === "win32" ? "step.exe" : "step");
74
+ return existsSync(installed) ? installed : undefined;
75
+ }
76
+
77
+ /**
78
+ * Flags that make one headless turn independent of the operator's StepCode setup.
79
+ *
80
+ * The contract is deliberately total rather than selective. StepCode otherwise loads the user's
81
+ * extensions, skills, prompt templates, themes, `AGENTS.md`/`CLAUDE.md` context files and every MCP
82
+ * server in `~/.stepcode/config.toml` — a 40-server host config turns a proxied turn into a
83
+ * multi-second startup whose tools and prompts are not part of this provider's advertised contract.
84
+ * Tool ownership is the reason for the whole route, so `--no-tools` is not a limitation here: the
85
+ * client's catalog is declared over the SDK stdio protocol instead.
86
+ */
87
+ export const STEP_CLI_ISOLATION_ARGS: readonly string[] = Object.freeze([
88
+ "--no-tools",
89
+ "--no-extensions",
90
+ "--no-skills",
91
+ "--no-prompt-templates",
92
+ "--no-themes",
93
+ "--no-context-files",
94
+ "--no-session",
95
+ "--no-update-check",
96
+ ]);
97
+
98
+ /** Spawn arguments for one `step` process. Isolated by construction, not by post-hoc filtering. */
99
+ export function buildStepCliArgs(model: string | undefined, thinkingLevel: string | undefined): string[] {
100
+ const args = ["--sdk-stdio", ...STEP_CLI_ISOLATION_ARGS];
101
+ if (model) args.push("--model", model);
102
+ if (thinkingLevel) args.push("--thinking", thinkingLevel);
103
+ return args;
104
+ }
105
+
106
+ /**
107
+ * Per-turn working directory for the state this proxy owns.
108
+ *
109
+ * Only session files are redirected. The CLI's own config directory — and with it `auth.json` — is
110
+ * deliberately left where StepCode put it: copying a credential into `~/.opencodex` to satisfy a
111
+ * convenience would put a second copy of a live subscription token on disk and hand this adapter a
112
+ * secret to redact, which is the exact posture the `claude-cli` row refuses (§三十一). Host MCP
113
+ * servers in the operator's config may therefore still initialize; `--no-tools` is what makes them
114
+ * unreachable, and permission mode and model are set per query regardless of what the file says.
115
+ */
116
+ export function stepCliStateRoot(openCodexHome: string): string {
117
+ return join(openCodexHome, "step-cli");
118
+ }
119
+
120
+ /**
121
+ * Directory holding proxied session files.
122
+ *
123
+ * Redirecting this keeps proxied turns out of the operator's own `~/.stepcode/agent/sessions`
124
+ * tree, so a conversation driven through the proxy is never mistaken for a local `step` session and
125
+ * can be reaped without touching real history.
126
+ */
127
+ export function stepCliSessionDir(openCodexHome: string): string {
128
+ return join(stepCliStateRoot(openCodexHome), "sessions");
129
+ }
130
+
131
+ /** Default state root when the proxy has not published one. */
132
+ export function defaultStepCliStateRoot(): string {
133
+ return join(tmpdir(), "opencodex-step-cli");
134
+ }
@@ -0,0 +1,242 @@
1
+ import type { OcxParsedRequest, OcxUsage } from "../../types";
2
+ import type { IncomingMeta } from "../base";
3
+ import { buildSystemPrompt } from "../coding-agent/protocol";
4
+ import { CODING_AGENT_TOOL_LIMITS } from "../coding-agent/tool-catalog";
5
+ import { STEP_CLI_CONTINUATION_KEY, STEP_CLI_TOOL_SERVER } from "./constants";
6
+ import type { StepConversationRef } from "./session-pool";
7
+
8
+ /**
9
+ * Everything between "what the client sent" and "what the CLI is told".
10
+ *
11
+ * Kept apart from the transport on purpose: these are pure functions over a parsed request, so the
12
+ * awkward parts of this route — a tool result carrying an image, a model id with a namespace, an
13
+ * effort that has to become a token budget — can be read and tested without a session in the picture.
14
+ */
15
+
16
+ /** `providerState` slot carrying the conversation handle between requests. */
17
+ export type StepProviderState = { [STEP_CLI_CONTINUATION_KEY]: { handle: string; sessionId: string } };
18
+
19
+ /**
20
+ * How long a conversation's process survives without traffic.
21
+ *
22
+ * Long enough that a Codex thread's pauses between turns do not tear the conversation down, short
23
+ * enough that an abandoned thread does not leave a StepCode process running.
24
+ */
25
+
26
+ export function continuationFor(ref: StepConversationRef, sessionId: string | undefined): StepProviderState | undefined {
27
+ if (!ref) return undefined;
28
+ return { [STEP_CLI_CONTINUATION_KEY]: { handle: ref.handle, sessionId: sessionId ?? ref.sessionId } };
29
+ }
30
+
31
+ /** The newest tool result in the request, with the call it answers. */
32
+
33
+ /** A `data:` URL split into the base64 payload and media type StepCode's image block expects. */
34
+
35
+ /** A `data:` URL split into the base64 payload and media type StepCode's image block expects. */
36
+ export function parseInlineImageDataUrl(imageUrl: string): { data: string; mimeType: string } | undefined {
37
+ const match = /^data:([^;,]+);base64,(.+)$/s.exec(imageUrl);
38
+ if (!match) return undefined;
39
+ return { mimeType: match[1]!, data: match[2]! };
40
+ }
41
+
42
+ /**
43
+ * Project a client tool result into the content blocks StepCode's SDK tool accepts.
44
+ *
45
+ * A tool result is not necessarily text. Codex's `view_image` returns an image part, and collapsing
46
+ * that to an empty text block is the same misleading-empty-result failure the wrong-call path already
47
+ * had: the model reports a tool that "returned nothing" instead of saying it could not read the image.
48
+ * Inline `data:` images are forwarded; a remote URL cannot be, so it is replaced by a note the model can
49
+ * act on rather than dropped in silence.
50
+ */
51
+
52
+ /**
53
+ * Project a client tool result into the content blocks StepCode's SDK tool accepts.
54
+ *
55
+ * A tool result is not necessarily text. Codex's `view_image` returns an image part, and collapsing
56
+ * that to an empty text block is the same misleading-empty-result failure the wrong-call path already
57
+ * had: the model reports a tool that "returned nothing" instead of saying it could not read the image.
58
+ * Inline `data:` images are forwarded; a remote URL cannot be, so it is replaced by a note the model can
59
+ * act on rather than dropped in silence.
60
+ */
61
+ export function projectToolResultContent(
62
+ raw: string | readonly unknown[],
63
+ ): Array<Record<string, unknown>> {
64
+ if (typeof raw === "string") return raw.length > 0 ? [{ type: "text", text: raw }] : [];
65
+ const blocks: Array<Record<string, unknown>> = [];
66
+ const notes: string[] = [];
67
+ for (const part of raw) {
68
+ const block = asRecord(part);
69
+ if (block.type === "text" && typeof block.text === "string") {
70
+ blocks.push({ type: "text", text: block.text });
71
+ continue;
72
+ }
73
+ if (block.type === "image" && typeof block.imageUrl === "string") {
74
+ const inline = parseInlineImageDataUrl(block.imageUrl);
75
+ if (inline) {
76
+ blocks.push({ type: "image", data: inline.data, mimeType: inline.mimeType });
77
+ continue;
78
+ }
79
+ notes.push(`an image at ${block.imageUrl} could not be inlined; fetch it yourself if you need it`);
80
+ continue;
81
+ }
82
+ notes.push(`a ${typeof block.type === "string" ? block.type : "unknown"} result part was dropped`);
83
+ }
84
+ for (const note of notes) blocks.push({ type: "text", text: note });
85
+ if (blocks.length === 0) {
86
+ return [{ type: "text", text: "the tool returned no readable content" }];
87
+ }
88
+ return blocks;
89
+ }
90
+
91
+ export function latestToolResult(
92
+ parsed: OcxParsedRequest,
93
+ ): { content: readonly unknown[]; isError?: boolean; toolCallId: string } | undefined {
94
+ for (let index = parsed.context.messages.length - 1; index >= 0; index -= 1) {
95
+ const message = parsed.context.messages[index];
96
+ if (!message || message.role !== "toolResult") continue;
97
+ return {
98
+ content: projectToolResultContent(message.content),
99
+ toolCallId: message.toolCallId,
100
+ ...(message.isError ? { isError: true } : {}),
101
+ };
102
+ }
103
+ return undefined;
104
+ }
105
+
106
+ export function toUsage(usage: Record<string, unknown>): OcxUsage | undefined {
107
+ const input = typeof usage.input === "number" ? usage.input : undefined;
108
+ const output = typeof usage.output === "number" ? usage.output : undefined;
109
+ if (input === undefined && output === undefined) return undefined;
110
+ return {
111
+ inputTokens: input ?? 0,
112
+ outputTokens: output ?? 0,
113
+ ...(typeof usage.cacheRead === "number" ? { cachedInputTokens: usage.cacheRead } : {}),
114
+ };
115
+ }
116
+
117
+ /**
118
+ * StepCode model ids carry no provider prefix; the CLI owns its own default provider.
119
+ */
120
+
121
+ /**
122
+ * StepCode model ids carry no provider prefix; the CLI owns its own default provider.
123
+ */
124
+ export function stepModelId(modelId: string): string {
125
+ return modelId.startsWith(`${STEP_CLI_TOOL_SERVER}/`)
126
+ ? modelId.slice(STEP_CLI_TOOL_SERVER.length + 1)
127
+ : modelId;
128
+ }
129
+
130
+ /**
131
+ * StepCode's per-query thinking control is a token budget, so an effort has to be converted.
132
+ *
133
+ * The mapping is deliberately lossy and the registry only advertises the three rungs Step actually
134
+ * serves, so a client never believes it chose a depth it did not.
135
+ */
136
+
137
+ /**
138
+ * StepCode's per-query thinking control is a token budget, so an effort has to be converted.
139
+ *
140
+ * The mapping is deliberately lossy and the registry only advertises the three rungs Step actually
141
+ * serves, so a client never believes it chose a depth it did not.
142
+ */
143
+ export function stepThinkingTokens(parsed: OcxParsedRequest): number | undefined {
144
+ const effort = parsed.options.reasoning;
145
+ if (typeof effort !== "string" || effort === "none") return undefined;
146
+ const table: Record<string, number> = {
147
+ minimal: 1_024,
148
+ low: 4_096,
149
+ medium: 16_384,
150
+ high: 32_768,
151
+ xhigh: 65_536,
152
+ max: 65_536,
153
+ };
154
+ return table[effort] ?? table.high!;
155
+ }
156
+
157
+ /**
158
+ * Fold the caller's instructions into the one user message this hop can carry.
159
+ *
160
+ * StepCode cannot replace its session system prompt, so its own coding instructions stay in front of
161
+ * the model's answers. Prepending the client's own instructions keeps the turn answerable under the
162
+ * contract the client believes it set.
163
+ */
164
+
165
+ /**
166
+ * Fold the caller's instructions into the one user message this hop can carry.
167
+ *
168
+ * StepCode cannot replace its session system prompt, so its own coding instructions stay in front of
169
+ * the model's answers. Prepending the client's own instructions keeps the turn answerable under the
170
+ * contract the client believes it set.
171
+ */
172
+ export function composePrompt(parsed: OcxParsedRequest, userText: string): string {
173
+ const system = buildSystemPrompt(parsed);
174
+ return system ? `${system}\n\n${userText}` : userText;
175
+ }
176
+
177
+ /** Resolves when the client aborts, so a turn in flight does not outlive its request. */
178
+ export function abortSignal(incoming: IncomingMeta): Promise<void> {
179
+ const signal = incoming.abortSignal;
180
+ if (!signal) return new Promise<void>(() => undefined);
181
+ if (signal.aborted) return Promise.resolve();
182
+ return new Promise<void>(resolve => {
183
+ signal.addEventListener("abort", () => resolve(), { once: true });
184
+ });
185
+ }
186
+
187
+ export function asRecord(value: unknown): Record<string, unknown> {
188
+ return value !== null && typeof value === "object" && !Array.isArray(value)
189
+ ? (value as Record<string, unknown>)
190
+ : {};
191
+ }
192
+
193
+ /** Translate a transport failure into the actionable error an operator can act on. */
194
+
195
+ /**
196
+ * The text StepCode should be asked for on this turn.
197
+ *
198
+ * Only the final user message crosses `query.input`; earlier turns live in the process' session,
199
+ * because the wire reduces every message to text and images.
200
+ */
201
+ export function pendingUserText(parsed: OcxParsedRequest): string | undefined {
202
+ for (let index = parsed.context.messages.length - 1; index >= 0; index -= 1) {
203
+ const message = parsed.context.messages[index];
204
+ if (!message || message.role !== "user") continue;
205
+ if (!Array.isArray(message.content)) {
206
+ return typeof message.content === "string" && message.content.length > 0
207
+ ? message.content
208
+ : undefined;
209
+ }
210
+ const text = message.content
211
+ .filter(part => part.type === "text")
212
+ .map(part => (part as { text: string }).text)
213
+ .join("")
214
+ .trim();
215
+ if (text.length > 0) return text;
216
+ }
217
+ return undefined;
218
+ }
219
+
220
+ /**
221
+ * Refuse image input the way the Qoder and Claude Code rows do.
222
+ *
223
+ * `query.input` does carry an image block to the model, but this route publishes text-only models,
224
+ * and an image the harness silently drops produces a confident answer to the wrong question. An
225
+ * operator with the vision sidecar on the request path still gets pictures captioned into text.
226
+ */
227
+ export function hasImageInput(parsed: OcxParsedRequest): boolean {
228
+ return parsed.context.messages.some(message =>
229
+ Array.isArray(message.content) && message.content.some(part => part.type === "image"),
230
+ );
231
+ }
232
+
233
+ /**
234
+ * Identify the conversation this request belongs to.
235
+ *
236
+ * StepCode keeps a conversation only inside one process, so every request of a Codex thread has to
237
+ * land on the same session. The thread identity is what Codex already sends on EVERY request —
238
+ * `thread-id`, then the session-affinity headers — which is the resolution `devin`, `zed`, `cursor`
239
+ * and `google` use, and it works on the first request of a conversation. `previous_response_id` and
240
+ * the proxy's continuation store are only fallbacks: depending on persisted provider state would mean
241
+ * a conversation silently restarting whenever that store misses an entry.
242
+ */