@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,842 @@
1
+ import { spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from "node:child_process";
2
+ import { mkdir } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+
5
+ import { commandInvocation } from "../../lib/win-exec";
6
+ import { killWindowsProcessTreeAsync } from "../coding-agent/process-tree";
7
+ import type { WhichFn } from "../coding-agent/profile";
8
+ import { buildStepCliEnv } from "./env";
9
+ import { classifyStepChildError, StepSessionError } from "./errors";
10
+ import {
11
+ findStepCliBinary,
12
+ stepCliSessionDir,
13
+ STEP_CLI_PROFILE,
14
+ type StepCliProfile,
15
+ } from "./profiles";
16
+ import {
17
+ encodeStepFrame,
18
+ stepErrorResponse,
19
+ stepRequest,
20
+ stepResponse,
21
+ StepFrameDecoder,
22
+ StepProtocolViolation,
23
+ STEP_MAX_FRAME_BYTES,
24
+ STEP_PROTOCOL_VERSION,
25
+ type StepFrame,
26
+ } from "./stdio-frames";
27
+
28
+ export type StepSpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;
29
+
30
+ /**
31
+ * Capabilities this route cannot work without.
32
+ *
33
+ * Without `sdk-tools` the runtime answers text only while looking healthy, which is the one failure
34
+ * this provider must never present as success: the client would conclude the model simply chose not
35
+ * to call its tools, and a routed coding session would silently degrade into a chat.
36
+ */
37
+ const REQUIRED_CAPABILITIES = ["streaming-input", "sdk-tools"] as const;
38
+ const CLEANUP_ATTEMPTS = 2;
39
+ const MAX_PARALLEL_CLEANUPS = 4;
40
+ const KILL_CONFIRMATION_MS = 2_000;
41
+ const SHUTDOWN_KILL_MARGIN_MS = 250;
42
+ const PROCESS_EXIT_POLL_MS = 20;
43
+ const POSIX_LEADER_EXITED = "StepCode POSIX process cleanup is incomplete because the process group leader exited before group termination.";
44
+ const WINDOWS_PID_UNCONFIRMED = "StepCode Windows process cleanup is incomplete because ownership of the wrapper PID could not be confirmed.";
45
+
46
+ // Share slots across pools and all close paths, including idle and late-opening sessions.
47
+ let activeCleanups = 0;
48
+ const cleanupWaiters = new Set<() => void>();
49
+
50
+ function withCleanupSlot(cleanup: () => Promise<void>, urgent: AbortSignal): Promise<void> {
51
+ return new Promise((resolve, reject) => {
52
+ const start = (): void => {
53
+ cleanupWaiters.delete(start);
54
+ urgent.removeEventListener("abort", start);
55
+ if (urgent.aborted) {
56
+ // At the shutdown margin a queued tree kill must start even if every slot is busy.
57
+ void cleanup().then(resolve, reject);
58
+ return;
59
+ }
60
+ activeCleanups++;
61
+ const release = (): void => {
62
+ activeCleanups--;
63
+ cleanupWaiters.values().next().value?.();
64
+ };
65
+ void cleanup().finally(release).then(resolve, reject);
66
+ };
67
+ if (urgent.aborted || activeCleanups < MAX_PARALLEL_CLEANUPS) start();
68
+ else {
69
+ cleanupWaiters.add(start);
70
+ urgent.addEventListener("abort", start, { once: true });
71
+ }
72
+ });
73
+ }
74
+
75
+ function processIsGone(pid: number): boolean {
76
+ try {
77
+ process.kill(pid, 0);
78
+ return false;
79
+ } catch (error) {
80
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") return true;
81
+ throw error;
82
+ }
83
+ }
84
+
85
+ export interface StepSessionDeps {
86
+ spawn?: StepSpawnFn;
87
+ which?: WhichFn;
88
+ /** Injectable timer primitives so tests never sleep. */
89
+ setTimeout?: typeof setTimeout;
90
+ clearTimeout?: typeof clearTimeout;
91
+ now?: () => number;
92
+ /** Test seam for Windows command-shim invocation. */
93
+ platform?: NodeJS.Platform;
94
+ killWindowsProcessTree?: (pid: number) => Promise<void>;
95
+ }
96
+
97
+ export interface StepSessionOptions {
98
+ binary: string;
99
+ args: readonly string[];
100
+ env: Record<string, string>;
101
+ /** Working directory; the session directory is created beneath it. */
102
+ cwd: string;
103
+ /** Wall-clock ceiling for `initialize`, in ms. */
104
+ handshakeTimeoutMs: number;
105
+ /** Ceiling on a request the runtime has not answered, in ms. */
106
+ requestTimeoutMs: number;
107
+ /**
108
+ * Ceiling on a reverse request this peer holds.
109
+ *
110
+ * StepCode's own `SDK_TOOL_TIMEOUT_MS` is 120s and answering late produces a `permission_denied`
111
+ * message inside the model's context rather than a transport error. Bounding the hold shorter than
112
+ * that turns a too-slow tool into a clean failed turn instead of a session the model believes was
113
+ * denied.
114
+ */
115
+ reverseRequestHoldMs: number;
116
+ /** Reap a session with no activity for this long, in ms. */
117
+ idleTimeoutMs: number;
118
+ /** SIGTERM-to-SIGKILL window, in ms. */
119
+ killGraceMs: number;
120
+ }
121
+
122
+ /** A request awaiting an answer from the runtime. */
123
+ interface PendingRequest {
124
+ readonly method: string;
125
+ readonly timer: ReturnType<typeof setTimeout>;
126
+ readonly resolve: (frame: StepFrame) => void;
127
+ readonly reject: (error: Error) => void;
128
+ answered: boolean;
129
+ }
130
+
131
+ /** A reverse request the runtime is waiting on this peer to answer. */
132
+ interface HeldReverseRequest {
133
+ readonly method: string;
134
+ readonly frame: StepFrame;
135
+ readonly timer: ReturnType<typeof setTimeout>;
136
+ answered: boolean;
137
+ }
138
+
139
+ export { StepSessionError } from "./errors";
140
+
141
+ /**
142
+ * What the adapter needs to hear while a session is live.
143
+ *
144
+ * Every event carries the session that produced it: the handler is shared across every conversation,
145
+ * so the origin is the only way to route a frame to the turn that is waiting for it.
146
+ */
147
+ export type StepSessionEvent =
148
+ | { type: "event"; frame: StepFrame; session: StepCliSession }
149
+ | { type: "reverse_request"; frame: StepFrame; session: StepCliSession };
150
+
151
+ export interface StepSessionHandlers {
152
+ onEvent(event: StepSessionEvent): void;
153
+ }
154
+
155
+ /**
156
+ * One long-lived `step --sdk-stdio` process, keyed by client conversation.
157
+ *
158
+ * StepCode carries conversation context only in process memory: `query.input` reduces every message
159
+ * to plain text and images (`readQueryInput`), so an assistant turn, a declared tool call and its
160
+ * result cannot be replayed through the wire. The session therefore has to outlive one proxied
161
+ * request, and the client keeps it alive by echoing back the `providerState` this class mints —
162
+ * the same mechanism Kiro uses for `conversationId`.
163
+ *
164
+ * That constraint is also why a captured tool call is held open rather than answered here. The
165
+ * client executes the tool and reports it on its next request; delivering that result to this
166
+ * reverse request is how it reaches the model, inside the query the model is already running.
167
+ */
168
+ export class StepCliSession {
169
+ readonly #options: StepSessionOptions;
170
+ readonly #deps: StepSessionDeps;
171
+ readonly #handlers: StepSessionHandlers;
172
+ readonly #decoder = new StepFrameDecoder();
173
+ readonly #pending = new Map<string, PendingRequest>();
174
+ readonly #held = new Map<string, HeldReverseRequest>();
175
+ readonly #setTimer: typeof setTimeout;
176
+ readonly #clearTimer: typeof clearTimeout;
177
+ readonly #now: () => number;
178
+ readonly #platform: NodeJS.Platform;
179
+ readonly #killGraceMs: number;
180
+
181
+ #child: ChildProcess | undefined;
182
+ #leaderExited = false;
183
+ #posixGroupSignalState: "pending" | "finished" | "lost" = "pending";
184
+ #windowsTreeKillAttempted = false;
185
+ #closed = false;
186
+ #closePromise: Promise<void> | undefined;
187
+ #cleanupComplete = false;
188
+ #shutdownDeadlineMs = Infinity;
189
+ #shutdownTimer: ReturnType<typeof setTimeout> | undefined;
190
+ readonly #urgentCleanup = new AbortController();
191
+ #handshake: Promise<StepFrame> | undefined;
192
+ #sessionId: string | undefined;
193
+ #lastActivityAt: number;
194
+ #requestSeq = 0;
195
+ #stderrTail = "";
196
+ #idleTimer: ReturnType<typeof setTimeout> | undefined;
197
+ readonly #exitListeners = new Set<() => void>();
198
+
199
+ /**
200
+ * Register a callback fired once the owned process cleanup is confirmed.
201
+ *
202
+ * The pool needs this to drop a conversation whose process died: a restart would come back with no
203
+ * memory of the tool results the client already delivered, and those are not recoverable from the
204
+ * transcript this route cannot replay.
205
+ */
206
+ onExit(listener: () => void): () => void {
207
+ if (this.#cleanupComplete) {
208
+ listener();
209
+ return () => undefined;
210
+ }
211
+ this.#exitListeners.add(listener);
212
+ return () => this.#exitListeners.delete(listener);
213
+ }
214
+
215
+ #announceExit(): void {
216
+ if (this.#exitListeners.size === 0) return;
217
+ const listeners = [...this.#exitListeners];
218
+ this.#exitListeners.clear();
219
+ for (const listener of listeners) {
220
+ try {
221
+ listener();
222
+ } catch {
223
+ // An owner's bookkeeping must never keep a dead session from being reported.
224
+ }
225
+ }
226
+ }
227
+
228
+ private constructor(options: StepSessionOptions, deps: StepSessionDeps, handlers: StepSessionHandlers) {
229
+ this.#options = options;
230
+ this.#deps = deps;
231
+ this.#handlers = handlers;
232
+ this.#setTimer = deps.setTimeout ?? setTimeout;
233
+ this.#clearTimer = deps.clearTimeout ?? clearTimeout;
234
+ this.#now = deps.now ?? Date.now;
235
+ this.#platform = deps.platform ?? process.platform;
236
+ this.#killGraceMs = options.killGraceMs;
237
+ this.#lastActivityAt = this.#now();
238
+ }
239
+
240
+ static async open(
241
+ options: StepSessionOptions,
242
+ handlers: StepSessionHandlers,
243
+ deps: StepSessionDeps = {},
244
+ own?: (session: StepCliSession) => void,
245
+ ): Promise<StepCliSession> {
246
+ const session = new StepCliSession(options, deps, handlers);
247
+ own?.(session);
248
+ try {
249
+ await session.#start();
250
+ } catch (error) {
251
+ void session.close();
252
+ throw error;
253
+ }
254
+ return session;
255
+ }
256
+
257
+ get sessionId(): string | undefined {
258
+ return this.#sessionId;
259
+ }
260
+
261
+ get closed(): boolean {
262
+ return this.#closed;
263
+ }
264
+
265
+ /** Bounded stderr tail, for diagnostics. Never logged wholesale. */
266
+ get stderrTail(): string {
267
+ return this.#stderrTail;
268
+ }
269
+
270
+ /** Milliseconds since the last frame in either direction. */
271
+ idleMs(): number {
272
+ return this.#now() - this.#lastActivityAt;
273
+ }
274
+
275
+ #touch(): void {
276
+ this.#lastActivityAt = this.#now();
277
+ }
278
+
279
+ #nextId(): string {
280
+ this.#requestSeq += 1;
281
+ return `ocx_${this.#requestSeq}`;
282
+ }
283
+
284
+ async #start(): Promise<void> {
285
+ const invocation = commandInvocation(this.#options.binary, this.#options.args, this.#platform);
286
+ try {
287
+ await mkdir(this.#options.cwd, { recursive: true });
288
+ } catch {
289
+ throw new StepSessionError("StepCode could not create its workspace.", "step_cli_workspace_unavailable");
290
+ }
291
+ // A deadline-aware close can take ownership while workspace creation is pending.
292
+ if (this.#closed) return;
293
+ const spawn = this.#deps.spawn ?? nodeSpawn;
294
+ const child = spawn(invocation.file, invocation.args, {
295
+ ...invocation.options,
296
+ env: this.#options.env,
297
+ stdio: ["pipe", "pipe", "pipe"],
298
+ windowsHide: true,
299
+ detached: this.#platform !== "win32",
300
+ cwd: this.#options.cwd,
301
+ });
302
+ this.#child = child;
303
+ child.once("exit", () => { this.#leaderExited = true; });
304
+
305
+ // stderr must be drained continuously: an unread pipe fills and blocks the child mid-turn. Only a
306
+ // bounded tail is retained, and it is never logged as content.
307
+ //
308
+ // `setEncoding("utf8")` rather than decoding each chunk: StepCode prints CJK diagnostics (未登录),
309
+ // and a multibyte character split across two chunks would decode to U+FFFD on both halves, so the
310
+ // not-signed-in detection that matches on that text would stop firing.
311
+ child.stderr?.setEncoding("utf8");
312
+ child.stderr?.on("data", (chunk: string) => {
313
+ this.#touch();
314
+ this.#stderrTail = (this.#stderrTail + chunk).slice(-2000);
315
+ });
316
+ child.stdout?.on("data", (chunk: Buffer) => this.#absorbStdout(chunk));
317
+ child.on("error", error => {
318
+ // A spawn failure such as ENOENT can emit `error` without a following `close`, so the sweep has to
319
+ // be stopped here too or it lingers on a session that no longer exists.
320
+ this.#stopIdleSweep();
321
+ this.#failAll(error instanceof Error ? error : new Error(String(error)));
322
+ if (child.pid === undefined) this.#child = undefined;
323
+ void this.close();
324
+ });
325
+ child.on("close", () => {
326
+ this.#leaderExited = true;
327
+ this.#failAll(new StepSessionError("StepCode exited before the turn settled."));
328
+ this.#stopIdleSweep();
329
+ void this.close();
330
+ });
331
+ this.#installIdleSweep();
332
+ }
333
+
334
+ #absorbStdout(chunk: Buffer): void {
335
+ this.#touch();
336
+ let frames: StepFrame[];
337
+ try {
338
+ frames = this.#decoder.push(chunk);
339
+ } catch (error) {
340
+ // The runtime answers a frame it cannot parse with silence, so writing on into it would hang the
341
+ // client for the whole request timeout. Fail every waiter and tear the process down instead.
342
+ this.#failAll(error instanceof StepProtocolViolation ? error : new Error(String(error)));
343
+ void this.close();
344
+ return;
345
+ }
346
+ for (const frame of frames) this.#route(frame);
347
+ }
348
+
349
+ #route(frame: StepFrame): void {
350
+ if (frame.kind === "response") {
351
+ const replyTo = frame.replyTo;
352
+ if (!replyTo) return;
353
+ const pending = this.#pending.get(replyTo);
354
+ if (!pending) return;
355
+ this.#pending.delete(replyTo);
356
+ this.#settle(pending, frame);
357
+ return;
358
+ }
359
+ if (frame.kind === "request") {
360
+ this.#holdReverse(frame);
361
+ return;
362
+ }
363
+ this.#handlers.onEvent({ type: "event", frame, session: this });
364
+ }
365
+
366
+ #holdReverse(frame: StepFrame): void {
367
+ const timer = this.#setTimer(() => {
368
+ if (!this.#held.delete(frame.id)) return;
369
+ // The expiry is surfaced so the peer can answer the runtime. Without an answer here StepCode
370
+ // waits out its own 120s window, and a later turn registered for this session would see the same
371
+ // frame again and re-emit the tool call the client already received.
372
+ this.#handlers.onEvent({
373
+ type: "reverse_request",
374
+ frame: { ...frame, payload: { ...(frame.payload as object ?? {}), __expired: true } } as StepFrame,
375
+ session: this,
376
+ });
377
+ }, this.#options.reverseRequestHoldMs);
378
+ this.#held.set(frame.id, {
379
+ method: frame.method ?? "unknown",
380
+ frame,
381
+ timer,
382
+ answered: false,
383
+ });
384
+ this.#handlers.onEvent({ type: "reverse_request", frame, session: this });
385
+ }
386
+
387
+ #settle(pending: PendingRequest, frame: StepFrame): void {
388
+ if (pending.answered) return;
389
+ pending.answered = true;
390
+ this.#clearTimer(pending.timer as never);
391
+ if (frame.error) {
392
+ pending.reject(classifyStepChildError(frame.error));
393
+ return;
394
+ }
395
+ pending.resolve(frame);
396
+ }
397
+
398
+ #failAll(error: Error): void {
399
+ for (const pending of this.#pending.values()) {
400
+ if (pending.answered) continue;
401
+ pending.answered = true;
402
+ this.#clearTimer(pending.timer as never);
403
+ pending.reject(error);
404
+ }
405
+ this.#pending.clear();
406
+ }
407
+
408
+ #write(frame: StepFrame): void {
409
+ const stdin = this.#child?.stdin;
410
+ if (this.#closed || !stdin?.writable) {
411
+ throw new StepSessionError("StepCode session is not writable.");
412
+ }
413
+ stdin.write(encodeStepFrame(frame, STEP_MAX_FRAME_BYTES));
414
+ }
415
+
416
+ #send(id: string, method: string, payload?: unknown, timeoutMs?: number): Promise<StepFrame> {
417
+ if (this.#closed) return Promise.reject(new StepSessionError("StepCode session is closed."));
418
+ let pending!: PendingRequest;
419
+ const timer = this.#setTimer(() => {
420
+ if (this.#pending.delete(id)) pending.reject(new StepSessionError(`StepCode did not answer ${method} in time.`, "timeout"));
421
+ }, timeoutMs ?? this.#options.requestTimeoutMs);
422
+ const promise = new Promise<StepFrame>((resolve, reject) => {
423
+ pending = { method, timer, resolve, reject, answered: false };
424
+ });
425
+ this.#pending.set(id, pending);
426
+ try {
427
+ this.#write(stepRequest(id, method, payload));
428
+ } catch (error) {
429
+ this.#pending.delete(id);
430
+ this.#clearTimer(timer as never);
431
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
432
+ }
433
+ return promise;
434
+ }
435
+
436
+ #respondOk(replyTo: string, payload: unknown): void {
437
+ try {
438
+ this.#write(stepResponse(replyTo, payload));
439
+ } catch {
440
+ // A peer that has gone away cannot be told; the session is already failing closed.
441
+ }
442
+ }
443
+
444
+ #respondError(replyTo: string, code: string, message: string): void {
445
+ try {
446
+ this.#write(stepErrorResponse(replyTo, code, message));
447
+ } catch {
448
+ /* see #respondOk */
449
+ }
450
+ }
451
+
452
+ /**
453
+ * Negotiate the protocol and verify this route can actually keep tool ownership.
454
+ */
455
+ async handshake(): Promise<StepFrame> {
456
+ this.#handshake ??= this.#negotiate();
457
+ return this.#handshake;
458
+ }
459
+
460
+ async #negotiate(): Promise<StepFrame> {
461
+ const response = await this.#send(
462
+ this.#nextId(),
463
+ "initialize",
464
+ { protocolRange: { min: STEP_PROTOCOL_VERSION, max: STEP_PROTOCOL_VERSION } },
465
+ this.#options.handshakeTimeoutMs,
466
+ );
467
+ const payload = (response.payload ?? {}) as Record<string, unknown>;
468
+ const capabilities = Array.isArray(payload.capabilities)
469
+ ? payload.capabilities.filter((value): value is string => typeof value === "string")
470
+ : [];
471
+ const missing = REQUIRED_CAPABILITIES.filter(capability => !capabilities.includes(capability));
472
+ if (missing.length > 0) {
473
+ throw new StepSessionError(
474
+ `This StepCode build does not advertise ${missing.join(", ")}, so it cannot keep tool ownership for a proxied turn.`,
475
+ "step_cli_capability_missing",
476
+ );
477
+ }
478
+ return response;
479
+ }
480
+
481
+ /**
482
+ * Open one query and return its ids.
483
+ *
484
+ * `hasPermissionCallback` is what disables StepCode's fail-closed default: without it an
485
+ * approval-requiring tool is blocked and the run terminated before this peer is ever consulted.
486
+ * `permissionMode` is sent explicitly for the same reason — the CLI otherwise starts in
487
+ * "Full Access (auto-resume)".
488
+ */
489
+ async startQuery(options: {
490
+ model: string | undefined;
491
+ maxThinkingTokens: number | undefined;
492
+ sdkTools: readonly unknown[];
493
+ streamingInput: boolean;
494
+ }): Promise<{ queryId: string; sessionId: string }> {
495
+ const response = await this.#send(this.#nextId(), "query.start", {
496
+ streamingInput: options.streamingInput,
497
+ options: {
498
+ ...(options.model ? { model: options.model } : {}),
499
+ ...(typeof options.maxThinkingTokens === "number"
500
+ ? { maxThinkingTokens: options.maxThinkingTokens }
501
+ : {}),
502
+ permissionMode: "default",
503
+ hasPermissionCallback: true,
504
+ includePartialMessages: true,
505
+ sdkTools: options.sdkTools,
506
+ },
507
+ });
508
+ const payload = (response.payload ?? {}) as Record<string, unknown>;
509
+ if (typeof payload.sessionId === "string") this.#sessionId = payload.sessionId;
510
+ const queryId = typeof payload.queryId === "string" ? payload.queryId : undefined;
511
+ if (!queryId) throw new StepSessionError("query.start returned no queryId.", "step_cli_protocol_violation");
512
+ return { queryId, sessionId: this.#sessionId ?? "" };
513
+ }
514
+
515
+ /**
516
+ * Queue one user message.
517
+ *
518
+ * Only text and images survive this hop, which is exactly why the session must outlive a request
519
+ * instead of being rebuilt from a replayed transcript.
520
+ */
521
+ async sendInput(queryId: string, text: string): Promise<void> {
522
+ await this.#send(this.#nextId(), "query.input", {
523
+ queryId,
524
+ message: { type: "user", message: { role: "user", content: [{ type: "text", text }] } },
525
+ });
526
+ }
527
+
528
+ /** Answer a permission already checked against the owning turn and catalog. */
529
+ allowPermission(frame: StepFrame): void {
530
+ this.#respondOk(frame.id, { behavior: "allow" });
531
+ this.#releaseReverse(frame.id);
532
+ }
533
+
534
+ /**
535
+ * Refuse a tool call with a reason the model can act on.
536
+ *
537
+ * A tool result frame carrying only `{message}` is not a refusal: StepCode reads `payload.content`
538
+ * and renders an absent content list as an EMPTY result, which the model reports as a tool that ran
539
+ * and produced nothing. Only an `error` envelope throws inside the SDK tool wrapper.
540
+ */
541
+ refuseToolCall(frame: StepFrame, reason: string): void {
542
+ this.#respondError(frame.id, "TOOL_NOT_AVAILABLE", reason);
543
+ this.#releaseReverse(frame.id);
544
+ }
545
+
546
+ #releaseReverse(id: string): void {
547
+ const held = this.#held.get(id);
548
+ if (held) {
549
+ held.answered = true;
550
+ this.#clearTimer(held.timer as never);
551
+ this.#held.delete(id);
552
+ }
553
+ }
554
+
555
+ /** Refuse a `permission.request` with a reason the model can act on. */
556
+ denyPermission(frame: StepFrame, reason: string): void {
557
+ this.#respondOk(frame.id, { message: reason });
558
+ this.#releaseReverse(frame.id);
559
+ }
560
+
561
+ /**
562
+ * Deliver a client-executed tool result to the call this session is holding open.
563
+ *
564
+ * Returns false when nothing is held for that frame — the runtime's own timer already fired, or
565
+ * the session was reaped — so the caller reports a too-slow tool instead of continuing against a
566
+ * call the model has already been told was denied.
567
+ */
568
+ resolveHeldToolResult(frame: StepFrame, result: { content: readonly unknown[]; isError?: boolean }): boolean {
569
+ const held = this.#held.get(frame.id);
570
+ if (!held || held.answered || held.method !== "sdk_tool.invoke") return false;
571
+ held.answered = true;
572
+ this.#clearTimer(held.timer as never);
573
+ this.#held.delete(frame.id);
574
+ this.#respondOk(frame.id, {
575
+ content: result.content,
576
+ ...(result.isError === true ? { isError: true } : {}),
577
+ });
578
+ this.#touch();
579
+ return true;
580
+ }
581
+
582
+ /** Reverse requests still waiting on this peer, in arrival order. */
583
+ heldReverseRequests(): StepFrame[] {
584
+ return [...this.#held.values()].filter(entry => !entry.answered).map(entry => entry.frame);
585
+ }
586
+
587
+ /**
588
+ * Close this query's input stream with `query.input_end`.
589
+ *
590
+ * Not optional housekeeping: StepCode's `#maybeFinish` refuses to finish a query whose input has
591
+ * not ended, so without this the runtime's single query slot is never released and the NEXT
592
+ * `query.start` on the same process fails with SESSION_BUSY. A multi-turn text conversation would
593
+ * therefore work for exactly one turn.
594
+ *
595
+ * Deliberately not sent when a tool call was captured: that query is still owed the client's tool
596
+ * result, and ending its input would let the runtime finish it before the model continues.
597
+ */
598
+ async endInput(queryId: string): Promise<void> {
599
+ if (this.#closed) return;
600
+ await this.#send(this.#nextId(), "query.input_end", { queryId }, this.#options.requestTimeoutMs);
601
+ }
602
+
603
+ /** StepCode's `query.interrupt`, used when the client aborts a turn mid-flight. */
604
+ async interrupt(queryId: string): Promise<void> {
605
+ if (this.#closed) return;
606
+ await this.#send(this.#nextId(), "query.interrupt", { queryId });
607
+ }
608
+
609
+ #installIdleSweep(): void {
610
+ const interval = Math.max(1_000, Math.min(this.#options.idleTimeoutMs, 60_000));
611
+ const sweep = (): void => {
612
+ if (this.#closed) return;
613
+ if (this.idleMs() >= this.#options.idleTimeoutMs) {
614
+ void this.close();
615
+ return;
616
+ }
617
+ this.#idleTimer = this.#setTimer(sweep, interval);
618
+ };
619
+ this.#idleTimer = this.#setTimer(sweep, interval);
620
+ }
621
+
622
+ #stopIdleSweep(): void {
623
+ if (!this.#idleTimer) return;
624
+ this.#clearTimer(this.#idleTimer as never);
625
+ this.#idleTimer = undefined;
626
+ }
627
+
628
+ closeBy(deadlineMs: number): void {
629
+ if (deadlineMs < this.#shutdownDeadlineMs && !this.#cleanupComplete) {
630
+ this.#shutdownDeadlineMs = deadlineMs;
631
+ clearTimeout(this.#shutdownTimer);
632
+ const delayMs = deadlineMs - SHUTDOWN_KILL_MARGIN_MS - Date.now();
633
+ if (delayMs <= 0) this.#urgentCleanup.abort();
634
+ else this.#shutdownTimer = setTimeout(() => this.#urgentCleanup.abort(), delayMs);
635
+ }
636
+ void this.close();
637
+ }
638
+
639
+ /** Start queued tree kills and signal any still-owned POSIX group before returning. */
640
+ forceShutdown(): void {
641
+ this.#urgentCleanup.abort();
642
+ const child = this.#child;
643
+ if (this.#platform === "win32" || child?.pid === undefined) return;
644
+ try {
645
+ this.#signalPosixGroup(child, child.pid, "SIGKILL");
646
+ } catch (error) {
647
+ // If the group operation failed, the child handle can still stop the leader.
648
+ // Preserve the failure receipt because the descendants are unconfirmed.
649
+ if (this.#hasLiveLeader(child)) child.kill("SIGKILL");
650
+ throw error;
651
+ }
652
+ }
653
+
654
+ /**
655
+ * Reap the owned process tree before releasing this session. Concurrent callers share cleanup.
656
+ */
657
+ close(code = 0): Promise<void> {
658
+ if (this.#closePromise) return this.#closePromise;
659
+ this.#closed = true;
660
+ this.#stopIdleSweep();
661
+ const child = this.#child;
662
+ this.#failAll(new StepSessionError(`StepCode session closed (${code}).`));
663
+ for (const held of this.#held.values()) this.#clearTimer(held.timer as never);
664
+ this.#held.clear();
665
+ // Publish the receipt before termination can emit close or notify pool bookkeeping.
666
+ const receipt = Promise.withResolvers<void>();
667
+ this.#closePromise = receipt.promise;
668
+ // Timer/protocol-initiated closes have no awaiting caller. Keep the rejection in the cached
669
+ // receipt for close()/pool shutdown, while observing it here to avoid an unhandled rejection.
670
+ void this.#closePromise.catch(() => {});
671
+ const terminate = async (): Promise<void> => {
672
+ if (child) await withCleanupSlot(() => this.#terminateWithRetry(child), this.#urgentCleanup.signal);
673
+ this.#cleanupComplete = true;
674
+ this.#announceExit();
675
+ };
676
+ void terminate().finally(() => clearTimeout(this.#shutdownTimer)).then(receipt.resolve, receipt.reject);
677
+ return this.#closePromise;
678
+ }
679
+
680
+ async #terminateWithRetry(child: ChildProcess): Promise<void> {
681
+ const failures: unknown[] = [];
682
+ const usesTaskkill = this.#platform === "win32" && child.pid !== undefined;
683
+ const recordWindowsOwnershipLoss = (): void => {
684
+ console.warn(WINDOWS_PID_UNCONFIRMED);
685
+ failures.push(new StepSessionError(WINDOWS_PID_UNCONFIRMED, "step_cli_cleanup_failed"));
686
+ };
687
+ for (let attempt = 0; attempt < CLEANUP_ATTEMPTS; attempt++) {
688
+ if (usesTaskkill && !this.#hasLiveLeader(child)) {
689
+ recordWindowsOwnershipLoss();
690
+ break;
691
+ }
692
+ try { await this.#terminate(child); return; }
693
+ catch (error) {
694
+ failures.push(error);
695
+ if (usesTaskkill && this.#windowsTreeKillAttempted) {
696
+ recordWindowsOwnershipLoss();
697
+ break;
698
+ }
699
+ if (this.#posixGroupSignalState === "lost") break;
700
+ }
701
+ }
702
+ throw Object.assign(new StepSessionError(
703
+ "StepCode process cleanup failed; conversation handle is quarantined.", "step_cli_cleanup_failed",
704
+ ), { cause: new AggregateError(failures, "StepCode tree termination attempts failed.") });
705
+ }
706
+
707
+ async #terminate(child: ChildProcess): Promise<void> {
708
+ if (this.#platform !== "win32" && child.pid !== undefined) {
709
+ await this.#terminatePosixGroup(child, child.pid);
710
+ } else {
711
+ await this.#terminateChild(child);
712
+ }
713
+ child.stdin?.destroy();
714
+ child.stdout?.destroy();
715
+ child.stderr?.destroy();
716
+ child.unref?.();
717
+ this.#child = undefined;
718
+ }
719
+
720
+ #hasLiveLeader(child: ChildProcess): boolean {
721
+ return !this.#leaderExited && child.exitCode === null && child.signalCode === null;
722
+ }
723
+
724
+ #signalPosixGroup(child: ChildProcess, pid: number, signal: "SIGTERM" | "SIGKILL"): void {
725
+ if (this.#posixGroupSignalState === "finished") return;
726
+ // The detached leader anchors the PGID only until exit. Check on every signal.
727
+ if (!this.#hasLiveLeader(child)) {
728
+ if (this.#posixGroupSignalState === "pending") {
729
+ this.#posixGroupSignalState = "lost";
730
+ console.warn(POSIX_LEADER_EXITED);
731
+ }
732
+ throw new StepSessionError(POSIX_LEADER_EXITED, "step_cli_cleanup_failed");
733
+ }
734
+ try {
735
+ process.kill(-pid, signal);
736
+ if (signal === "SIGKILL") this.#posixGroupSignalState = "finished";
737
+ } catch (error) {
738
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
739
+ this.#posixGroupSignalState = "finished";
740
+ }
741
+ }
742
+
743
+ async #terminatePosixGroup(child: ChildProcess, pid: number): Promise<void> {
744
+ const escalateAt = performance.now() + this.#killGraceMs;
745
+ const deadline = escalateAt + KILL_CONFIRMATION_MS;
746
+ if (!this.#urgentCleanup.signal.aborted && this.#shutdownDeadlineMs - Date.now() > SHUTDOWN_KILL_MARGIN_MS) {
747
+ this.#signalPosixGroup(child, pid, "SIGTERM");
748
+ while (this.#posixGroupSignalState === "pending" && this.#hasLiveLeader(child) && !this.#urgentCleanup.signal.aborted) {
749
+ const untilKill = Math.min(escalateAt - performance.now(), this.#shutdownDeadlineMs - Date.now() - SHUTDOWN_KILL_MARGIN_MS);
750
+ if (untilKill <= 0) break;
751
+ await Bun.sleep(Math.min(PROCESS_EXIT_POLL_MS, untilKill));
752
+ }
753
+ }
754
+ this.#signalPosixGroup(child, pid, "SIGKILL");
755
+ // Confirm the leader's exit using its child handle. The numeric PGID can be reused.
756
+ while (this.#hasLiveLeader(child)) {
757
+ const untilConfirm = Math.min(deadline - performance.now(), this.#shutdownDeadlineMs - Date.now());
758
+ if (untilConfirm <= 0) {
759
+ throw new StepSessionError("StepCode process group cleanup could not be confirmed.", "step_cli_cleanup_failed");
760
+ }
761
+ await Bun.sleep(Math.min(PROCESS_EXIT_POLL_MS, untilConfirm));
762
+ }
763
+ }
764
+
765
+ async #terminateChild(child: ChildProcess): Promise<void> {
766
+ if ((child.exitCode !== null || child.signalCode !== null)
767
+ && child.pid === undefined) return;
768
+ let cancelWait = (): void => {};
769
+ const exited = new Promise<void>(resolve => {
770
+ const finish = (): void => { cancelWait(); resolve(); };
771
+ child.once("close", finish);
772
+ cancelWait = () => child.removeListener("close", finish);
773
+ });
774
+ let timer: ReturnType<typeof setTimeout> | undefined;
775
+ let deadline: ReturnType<typeof setTimeout> | undefined;
776
+ let failCleanup!: (error: unknown) => void;
777
+ const cleanupFailed = new Promise<never>((_, reject) => { failCleanup = reject; });
778
+ const gone = (): boolean => {
779
+ return !this.#hasLiveLeader(child) || (child.pid !== undefined && processIsGone(child.pid));
780
+ };
781
+ const signal = (kind: NodeJS.Signals): void => {
782
+ try {
783
+ child.kill(kind);
784
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
785
+ };
786
+ try {
787
+ if (child.pid !== undefined) {
788
+ this.#windowsTreeKillAttempted = true;
789
+ try {
790
+ await (this.#deps.killWindowsProcessTree ?? killWindowsProcessTreeAsync)(child.pid);
791
+ } catch (error) {
792
+ // After a failed or timed-out taskkill, the wrapper may already have exited and Bun
793
+ // may have released its handle. Retry only when taskkill itself failed to start.
794
+ const failure = error instanceof Error ? error as NodeJS.ErrnoException : undefined;
795
+ if ((failure?.code === "ENOENT" || failure?.code === "EACCES") && failure.syscall?.startsWith("spawn ")) {
796
+ this.#windowsTreeKillAttempted = false;
797
+ }
798
+ throw error;
799
+ }
800
+ // Bun on Windows can retain null exit/signal fields after taskkill has reaped the tree.
801
+ // Check the OS only when Bun has not already observed the original wrapper's exit.
802
+ if (gone()) return;
803
+ } else {
804
+ signal("SIGTERM");
805
+ timer = this.#setTimer(() => {
806
+ try { signal("SIGKILL"); } catch (error) { failCleanup(error); }
807
+ }, this.#killGraceMs);
808
+ }
809
+ await Promise.race([exited, cleanupFailed, new Promise<void>((resolve, reject) => {
810
+ deadline = this.#setTimer(() => {
811
+ try {
812
+ if (gone()) resolve();
813
+ else reject(new StepSessionError("StepCode process cleanup could not be confirmed.", "step_cli_cleanup_failed"));
814
+ } catch (error) { reject(error); }
815
+ }, this.#killGraceMs + KILL_CONFIRMATION_MS);
816
+ })]);
817
+ } finally {
818
+ if (timer !== undefined) this.#clearTimer(timer as never);
819
+ if (deadline !== undefined) this.#clearTimer(deadline as never);
820
+ cancelWait();
821
+ }
822
+ }
823
+ }
824
+
825
+ /** Resolve this route's binary, or explain how to install it. */
826
+ export function resolveStepCliBinaryPath(which?: WhichFn): string {
827
+ const found = findStepCliBinary(STEP_CLI_PROFILE.binaryCandidates[0]!, which);
828
+ if (found) return found;
829
+ throw new StepSessionError(
830
+ `${STEP_CLI_PROFILE.label} is not installed. ${STEP_CLI_PROFILE.installHint}.`,
831
+ "step_cli_binary_missing",
832
+ );
833
+ }
834
+
835
+ /** Env and working directory for one session process. */
836
+ export function stepCliProcessEnvironment(openCodexHome: string): { env: Record<string, string>; cwd: string } {
837
+ const sessions = stepCliSessionDir(openCodexHome);
838
+ return { env: buildStepCliEnv(openCodexHome), cwd: dirname(sessions) };
839
+ }
840
+
841
+ export { buildStepCliEnv } from "./env";
842
+ export type { StepCliProfile };