@kodelyth/codex 2026.5.42 → 2026.6.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 (138) hide show
  1. package/package.json +16 -1
  2. package/doctor-contract-api.test.ts +0 -44
  3. package/doctor-contract-api.ts +0 -68
  4. package/harness.ts +0 -72
  5. package/index.test.ts +0 -230
  6. package/index.ts +0 -66
  7. package/media-understanding-provider.test.ts +0 -486
  8. package/media-understanding-provider.ts +0 -521
  9. package/prompt-overlay-runtime-contract.test.ts +0 -48
  10. package/prompt-overlay.ts +0 -21
  11. package/provider-catalog.ts +0 -83
  12. package/provider-discovery.ts +0 -45
  13. package/provider.test.ts +0 -384
  14. package/provider.ts +0 -243
  15. package/src/app-server/app-inventory-cache.test.ts +0 -176
  16. package/src/app-server/app-inventory-cache.ts +0 -324
  17. package/src/app-server/approval-bridge.test.ts +0 -1471
  18. package/src/app-server/approval-bridge.ts +0 -1211
  19. package/src/app-server/auth-bridge.test.ts +0 -1449
  20. package/src/app-server/auth-bridge.ts +0 -614
  21. package/src/app-server/auth-profile-runtime-contract.test.ts +0 -239
  22. package/src/app-server/capabilities.ts +0 -27
  23. package/src/app-server/client-factory.ts +0 -24
  24. package/src/app-server/client.test.ts +0 -563
  25. package/src/app-server/client.ts +0 -715
  26. package/src/app-server/compact.test.ts +0 -710
  27. package/src/app-server/compact.ts +0 -500
  28. package/src/app-server/computer-use.test.ts +0 -788
  29. package/src/app-server/computer-use.ts +0 -683
  30. package/src/app-server/config.test.ts +0 -879
  31. package/src/app-server/config.ts +0 -1038
  32. package/src/app-server/context-engine-projection.test.ts +0 -252
  33. package/src/app-server/context-engine-projection.ts +0 -403
  34. package/src/app-server/delivery-no-reply-runtime-contract.test.ts +0 -80
  35. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  36. package/src/app-server/dynamic-tool-profile.ts +0 -69
  37. package/src/app-server/dynamic-tools.test.ts +0 -1302
  38. package/src/app-server/dynamic-tools.ts +0 -623
  39. package/src/app-server/elicitation-bridge.test.ts +0 -1056
  40. package/src/app-server/elicitation-bridge.ts +0 -783
  41. package/src/app-server/event-projector.test.ts +0 -2668
  42. package/src/app-server/event-projector.ts +0 -2057
  43. package/src/app-server/image-payload-sanitizer.test.ts +0 -49
  44. package/src/app-server/image-payload-sanitizer.ts +0 -167
  45. package/src/app-server/klaw-owned-tool-runtime-contract.test.ts +0 -456
  46. package/src/app-server/local-runtime-attribution.ts +0 -39
  47. package/src/app-server/managed-binary.test.ts +0 -139
  48. package/src/app-server/managed-binary.ts +0 -193
  49. package/src/app-server/models.test.ts +0 -246
  50. package/src/app-server/models.ts +0 -172
  51. package/src/app-server/native-hook-relay.test.ts +0 -271
  52. package/src/app-server/native-hook-relay.ts +0 -150
  53. package/src/app-server/native-subagent-task-mirror.test.ts +0 -573
  54. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  55. package/src/app-server/outcome-fallback-runtime-contract.test.ts +0 -404
  56. package/src/app-server/plugin-activation.test.ts +0 -336
  57. package/src/app-server/plugin-activation.ts +0 -283
  58. package/src/app-server/plugin-app-cache-key.ts +0 -74
  59. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  60. package/src/app-server/plugin-inventory.test.ts +0 -355
  61. package/src/app-server/plugin-inventory.ts +0 -357
  62. package/src/app-server/plugin-thread-config.test.ts +0 -865
  63. package/src/app-server/plugin-thread-config.ts +0 -455
  64. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  65. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  66. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  67. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  68. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  69. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  70. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  71. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  72. package/src/app-server/protocol-validators.test.ts +0 -75
  73. package/src/app-server/protocol-validators.ts +0 -203
  74. package/src/app-server/protocol.ts +0 -520
  75. package/src/app-server/rate-limit-cache.ts +0 -48
  76. package/src/app-server/rate-limits.test.ts +0 -202
  77. package/src/app-server/rate-limits.ts +0 -583
  78. package/src/app-server/request.ts +0 -73
  79. package/src/app-server/run-attempt.context-engine.test.ts +0 -1004
  80. package/src/app-server/run-attempt.test.ts +0 -9477
  81. package/src/app-server/run-attempt.ts +0 -4683
  82. package/src/app-server/run-attempt.vision-tools.test.ts +0 -35
  83. package/src/app-server/schema-normalization-runtime-contract.test.ts +0 -206
  84. package/src/app-server/session-binding.test.ts +0 -303
  85. package/src/app-server/session-binding.ts +0 -398
  86. package/src/app-server/session-history.ts +0 -44
  87. package/src/app-server/shared-client.test.ts +0 -589
  88. package/src/app-server/shared-client.ts +0 -289
  89. package/src/app-server/side-question.test.ts +0 -1175
  90. package/src/app-server/side-question.ts +0 -1007
  91. package/src/app-server/test-support.ts +0 -48
  92. package/src/app-server/thread-lifecycle.test.ts +0 -447
  93. package/src/app-server/thread-lifecycle.ts +0 -939
  94. package/src/app-server/thread-lifecycle.user-mcp-servers.test.ts +0 -442
  95. package/src/app-server/timeout.ts +0 -9
  96. package/src/app-server/tool-progress-normalization.ts +0 -77
  97. package/src/app-server/trajectory.test.ts +0 -205
  98. package/src/app-server/trajectory.ts +0 -365
  99. package/src/app-server/transcript-mirror.test.ts +0 -524
  100. package/src/app-server/transcript-mirror.ts +0 -208
  101. package/src/app-server/transcript-repair-runtime-contract.test.ts +0 -44
  102. package/src/app-server/transport-stdio.test.ts +0 -171
  103. package/src/app-server/transport-stdio.ts +0 -107
  104. package/src/app-server/transport-websocket.test.ts +0 -69
  105. package/src/app-server/transport-websocket.ts +0 -90
  106. package/src/app-server/transport.ts +0 -117
  107. package/src/app-server/user-input-bridge.test.ts +0 -249
  108. package/src/app-server/user-input-bridge.ts +0 -316
  109. package/src/app-server/version.ts +0 -4
  110. package/src/app-server/vision-tools.ts +0 -12
  111. package/src/command-account.ts +0 -544
  112. package/src/command-formatters.ts +0 -425
  113. package/src/command-handlers.ts +0 -2004
  114. package/src/command-rpc.test.ts +0 -16
  115. package/src/command-rpc.ts +0 -142
  116. package/src/commands.test.ts +0 -3312
  117. package/src/commands.ts +0 -65
  118. package/src/conversation-binding-data.ts +0 -124
  119. package/src/conversation-binding.test.ts +0 -599
  120. package/src/conversation-binding.ts +0 -561
  121. package/src/conversation-control.test.ts +0 -126
  122. package/src/conversation-control.ts +0 -303
  123. package/src/conversation-turn-collector.test.ts +0 -191
  124. package/src/conversation-turn-collector.ts +0 -186
  125. package/src/conversation-turn-input.test.ts +0 -141
  126. package/src/conversation-turn-input.ts +0 -106
  127. package/src/manifest.test.ts +0 -20
  128. package/src/migration/apply.ts +0 -501
  129. package/src/migration/helpers.ts +0 -55
  130. package/src/migration/plan.ts +0 -461
  131. package/src/migration/provider.test.ts +0 -1741
  132. package/src/migration/provider.ts +0 -41
  133. package/src/migration/source.ts +0 -643
  134. package/src/migration/targets.ts +0 -25
  135. package/src/node-cli-sessions.test.ts +0 -180
  136. package/src/node-cli-sessions.ts +0 -711
  137. package/test-api.ts +0 -82
  138. package/tsconfig.json +0 -16
@@ -1,715 +0,0 @@
1
- import { createInterface, type Interface as ReadlineInterface } from "node:readline";
2
- import { embeddedAgentLog, KLAW_VERSION } from "klaw/plugin-sdk/agent-harness-runtime";
3
- import { resolveCodexAppServerRuntimeOptions, type CodexAppServerStartOptions } from "./config.js";
4
- import {
5
- type CodexAppServerRequestMethod,
6
- type CodexAppServerRequestParams,
7
- type CodexAppServerRequestResult,
8
- type CodexInitializeParams,
9
- type CodexInitializeResponse,
10
- isRpcResponse,
11
- type CodexServerNotification,
12
- type JsonValue,
13
- type RpcMessage,
14
- type RpcRequest,
15
- type RpcResponse,
16
- } from "./protocol.js";
17
- import { createStdioTransport } from "./transport-stdio.js";
18
- import { createWebSocketTransport } from "./transport-websocket.js";
19
- import {
20
- closeCodexAppServerTransport,
21
- closeCodexAppServerTransportAndWait,
22
- type CodexAppServerTransport,
23
- } from "./transport.js";
24
- import { MIN_CODEX_APP_SERVER_VERSION } from "./version.js";
25
-
26
- export { MIN_CODEX_APP_SERVER_VERSION } from "./version.js";
27
- const CODEX_APP_SERVER_PARSE_LOG_MAX = 500;
28
- const CODEX_APP_SERVER_PARSE_BUFFER_MAX = 1_000_000;
29
- const CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES = 1_000;
30
- const CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS = 600_000;
31
- const CODEX_APP_SERVER_STDERR_TAIL_MAX = 2_000;
32
- const UNPAIRED_SURROGATE_RE =
33
- /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
34
-
35
- type PendingRequest = {
36
- method: string;
37
- resolve: (value: unknown) => void;
38
- reject: (error: Error) => void;
39
- cleanup: () => void;
40
- };
41
-
42
- export class CodexAppServerRpcError extends Error {
43
- readonly code?: number;
44
- readonly data?: JsonValue;
45
-
46
- constructor(error: { code?: number; message: string; data?: JsonValue }, method: string) {
47
- super(formatCodexAppServerRpcErrorMessage(error, method));
48
- this.name = "CodexAppServerRpcError";
49
- this.code = error.code;
50
- this.data = error.data;
51
- }
52
- }
53
-
54
- function formatCodexAppServerRpcErrorMessage(
55
- error: { message: string; data?: JsonValue },
56
- method: string,
57
- ): string {
58
- const message = error.message || `${method} failed`;
59
- const detail = readCodexAppServerRpcReloginDetail(error.data);
60
- return detail && !message.includes(detail) ? `${message}: ${detail}` : message;
61
- }
62
-
63
- function readCodexAppServerRpcReloginDetail(data: JsonValue | undefined): string | undefined {
64
- const record = isJsonObject(data) ? data : undefined;
65
- const nested = isJsonObject(record?.error) ? record.error : record;
66
- if (!nested) {
67
- return undefined;
68
- }
69
- const isRelogin =
70
- nested.action === "relogin" ||
71
- (nested.reason === "cloudRequirements" && nested.errorCode === "Auth");
72
- const detail = typeof nested.detail === "string" ? nested.detail.trim() : "";
73
- return isRelogin && detail ? detail : undefined;
74
- }
75
-
76
- function isJsonObject(value: unknown): value is { [key: string]: JsonValue } {
77
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
78
- }
79
-
80
- export function isCodexAppServerConnectionClosedError(error: unknown): boolean {
81
- if (!(error instanceof Error)) {
82
- return false;
83
- }
84
- return (
85
- error.message === "codex app-server client is closed" ||
86
- error.message.startsWith("codex app-server exited:")
87
- );
88
- }
89
-
90
- type CodexServerRequestHandler = (
91
- request: Required<Pick<RpcRequest, "id" | "method">> & { params?: JsonValue },
92
- ) => Promise<JsonValue | undefined> | JsonValue | undefined;
93
-
94
- export type CodexServerNotificationHandler = (
95
- notification: CodexServerNotification,
96
- ) => Promise<void> | void;
97
-
98
- export class CodexAppServerClient {
99
- private readonly child: CodexAppServerTransport;
100
- private readonly lines: ReadlineInterface;
101
- private readonly pending = new Map<number | string, PendingRequest>();
102
- private readonly requestHandlers = new Set<CodexServerRequestHandler>();
103
- private readonly notificationHandlers = new Set<CodexServerNotificationHandler>();
104
- private readonly closeHandlers = new Set<(client: CodexAppServerClient) => void>();
105
- private nextId = 1;
106
- private initialized = false;
107
- private closed = false;
108
- private closeError: Error | undefined;
109
- private stderrTail = "";
110
- private pendingParse:
111
- | {
112
- text: string;
113
- lineCount: number;
114
- firstError: unknown;
115
- }
116
- | undefined;
117
-
118
- private constructor(child: CodexAppServerTransport) {
119
- this.child = child;
120
- this.lines = createInterface({ input: child.stdout });
121
- this.lines.on("line", (line) => this.handleLine(line));
122
- child.stderr.on("data", (chunk: Buffer | string) => {
123
- const text = chunk.toString("utf8");
124
- this.stderrTail = appendBoundedTail(this.stderrTail, text, CODEX_APP_SERVER_STDERR_TAIL_MAX);
125
- const trimmed = text.trim();
126
- if (trimmed) {
127
- embeddedAgentLog.debug(`codex app-server stderr: ${trimmed}`);
128
- }
129
- });
130
- child.once("error", (error) =>
131
- this.closeWithError(error instanceof Error ? error : new Error(String(error))),
132
- );
133
- child.once("exit", (code, signal) => {
134
- this.closeWithError(buildCodexAppServerExitError(code, signal, this.stderrTail));
135
- });
136
- // Guard against unhandled EPIPE / write-after-close errors on the stdin
137
- // stream. When the child process terminates abruptly the pipe can break
138
- // before the "exit" event fires, so a pending writeMessage() produces an
139
- // asynchronous error on stdin that would otherwise crash the gateway.
140
- child.stdin.on?.("error", (error) =>
141
- this.closeWithError(error instanceof Error ? error : new Error(String(error))),
142
- );
143
- }
144
-
145
- static start(options?: Partial<CodexAppServerStartOptions>): CodexAppServerClient {
146
- const defaults = resolveCodexAppServerRuntimeOptions().start;
147
- const startOptions = {
148
- ...defaults,
149
- ...options,
150
- headers: options?.headers ?? defaults.headers,
151
- };
152
- if (startOptions.transport === "stdio" && startOptions.commandSource === "managed") {
153
- throw new Error("Managed Codex app-server start options must be resolved before spawn.");
154
- }
155
- if (startOptions.transport === "websocket") {
156
- return new CodexAppServerClient(createWebSocketTransport(startOptions));
157
- }
158
- return new CodexAppServerClient(createStdioTransport(startOptions));
159
- }
160
-
161
- static fromTransportForTests(child: CodexAppServerTransport): CodexAppServerClient {
162
- return new CodexAppServerClient(child);
163
- }
164
-
165
- async initialize(): Promise<void> {
166
- if (this.initialized) {
167
- return;
168
- }
169
- // The handshake identifies the exact app-server process we will keep using,
170
- // which matters when callers override the binary or app-server args.
171
- const response = await this.request("initialize", {
172
- clientInfo: {
173
- name: "klaw",
174
- title: "Klaw",
175
- version: KLAW_VERSION,
176
- },
177
- capabilities: {
178
- experimentalApi: true,
179
- },
180
- } satisfies CodexInitializeParams);
181
- assertSupportedCodexAppServerVersion(response);
182
- this.notify("initialized");
183
- this.initialized = true;
184
- }
185
-
186
- request<M extends CodexAppServerRequestMethod>(
187
- method: M,
188
- params: CodexAppServerRequestParams<M>,
189
- options?: { timeoutMs?: number; signal?: AbortSignal },
190
- ): Promise<CodexAppServerRequestResult<M>>;
191
- request<T = JsonValue | undefined>(
192
- method: string,
193
- params?: unknown,
194
- options?: { timeoutMs?: number; signal?: AbortSignal },
195
- ): Promise<T>;
196
- request<T = JsonValue | undefined>(
197
- method: string,
198
- params?: unknown,
199
- options?: { timeoutMs?: number; signal?: AbortSignal },
200
- ): Promise<T> {
201
- options ??= {};
202
- if (this.closed) {
203
- return Promise.reject(this.closeError ?? new Error("codex app-server client is closed"));
204
- }
205
- if (options.signal?.aborted) {
206
- return Promise.reject(new Error(`${method} aborted`));
207
- }
208
- const id = this.nextId++;
209
- const message: RpcRequest = { id, method, params: params as JsonValue | undefined };
210
- return new Promise<T>((resolve, reject) => {
211
- let timeout: ReturnType<typeof setTimeout> | undefined;
212
- let cleanupAbort: (() => void) | undefined;
213
- const cleanup = () => {
214
- if (timeout) {
215
- clearTimeout(timeout);
216
- timeout = undefined;
217
- }
218
- cleanupAbort?.();
219
- cleanupAbort = undefined;
220
- };
221
- const rejectPending = (error: Error) => {
222
- if (!this.pending.has(id)) {
223
- return;
224
- }
225
- this.pending.delete(id);
226
- cleanup();
227
- reject(error);
228
- };
229
- if (options.timeoutMs && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0) {
230
- timeout = setTimeout(
231
- () => rejectPending(new Error(`${method} timed out`)),
232
- Math.max(100, options.timeoutMs),
233
- );
234
- timeout.unref?.();
235
- }
236
- if (options.signal) {
237
- const abortListener = () => rejectPending(new Error(`${method} aborted`));
238
- options.signal.addEventListener("abort", abortListener, { once: true });
239
- cleanupAbort = () => options.signal?.removeEventListener("abort", abortListener);
240
- }
241
- this.pending.set(id, {
242
- method,
243
- resolve: (value) => {
244
- cleanup();
245
- resolve(value as T);
246
- },
247
- reject: (error) => {
248
- cleanup();
249
- reject(error);
250
- },
251
- cleanup,
252
- });
253
- if (options.signal?.aborted) {
254
- rejectPending(new Error(`${method} aborted`));
255
- return;
256
- }
257
- try {
258
- this.writeMessage(message);
259
- } catch (error) {
260
- rejectPending(error instanceof Error ? error : new Error(String(error)));
261
- }
262
- });
263
- }
264
-
265
- notify(method: string, params?: JsonValue): void {
266
- this.writeMessage({ method, params });
267
- }
268
-
269
- addRequestHandler(handler: CodexServerRequestHandler): () => void {
270
- this.requestHandlers.add(handler);
271
- return () => this.requestHandlers.delete(handler);
272
- }
273
-
274
- addNotificationHandler(handler: CodexServerNotificationHandler): () => void {
275
- this.notificationHandlers.add(handler);
276
- return () => this.notificationHandlers.delete(handler);
277
- }
278
-
279
- addCloseHandler(handler: (client: CodexAppServerClient) => void): () => void {
280
- this.closeHandlers.add(handler);
281
- return () => this.closeHandlers.delete(handler);
282
- }
283
-
284
- close(): void {
285
- if (!this.markClosed(new Error("codex app-server client is closed"))) {
286
- return;
287
- }
288
- closeCodexAppServerTransport(this.child);
289
- }
290
-
291
- async closeAndWait(options?: {
292
- exitTimeoutMs?: number;
293
- forceKillDelayMs?: number;
294
- }): Promise<void> {
295
- this.markClosed(new Error("codex app-server client is closed"));
296
- await closeCodexAppServerTransportAndWait(this.child, options);
297
- }
298
-
299
- private writeMessage(message: RpcRequest | RpcResponse): void {
300
- if (this.closed) {
301
- return;
302
- }
303
- const id = "id" in message ? message.id : undefined;
304
- const method = "method" in message ? message.method : undefined;
305
- this.child.stdin.write(
306
- `${stringifyCodexAppServerMessage(message)}\n`,
307
- (error?: Error | null) => {
308
- if (error) {
309
- embeddedAgentLog.warn("codex app-server write failed", { error, id, method });
310
- }
311
- },
312
- );
313
- }
314
-
315
- private handleLine(line: string): void {
316
- const rawLine = line.endsWith("\r") ? line.slice(0, -1) : line;
317
- if (this.pendingParse) {
318
- this.handlePendingParseLine(rawLine);
319
- return;
320
- }
321
- const trimmed = rawLine.trim();
322
- if (!trimmed) {
323
- return;
324
- }
325
- let parsed: unknown;
326
- try {
327
- parsed = JSON.parse(trimmed);
328
- } catch (error) {
329
- if (shouldBufferCodexAppServerParseFailure(trimmed, error)) {
330
- this.pendingParse = { text: trimmed, lineCount: 1, firstError: error };
331
- return;
332
- }
333
- logCodexAppServerParseFailure(trimmed, error, 1);
334
- return;
335
- }
336
- this.handleParsedMessage(parsed);
337
- }
338
-
339
- private handlePendingParseLine(line: string): void {
340
- const pending = this.pendingParse;
341
- if (!pending) {
342
- return;
343
- }
344
- const candidate = `${pending.text}\\n${line}`;
345
- let parsed: unknown;
346
- try {
347
- parsed = JSON.parse(candidate);
348
- } catch (error) {
349
- const lineCount = pending.lineCount + 1;
350
- if (
351
- candidate.length <= CODEX_APP_SERVER_PARSE_BUFFER_MAX &&
352
- lineCount <= CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES
353
- ) {
354
- this.pendingParse = { text: candidate, lineCount, firstError: pending.firstError };
355
- return;
356
- }
357
- this.pendingParse = undefined;
358
- logCodexAppServerParseFailure(candidate, error, lineCount);
359
- return;
360
- }
361
- this.pendingParse = undefined;
362
- this.handleParsedMessage(parsed);
363
- }
364
-
365
- private handleParsedMessage(parsed: unknown): void {
366
- if (!parsed || typeof parsed !== "object") {
367
- return;
368
- }
369
- const message = parsed as RpcMessage;
370
- if (isRpcResponse(message)) {
371
- this.handleResponse(message);
372
- return;
373
- }
374
- if (!("method" in message)) {
375
- return;
376
- }
377
- if ("id" in message && message.id !== undefined) {
378
- void this.handleServerRequest({
379
- id: message.id,
380
- method: message.method,
381
- params: message.params,
382
- });
383
- return;
384
- }
385
- this.handleNotification({
386
- method: message.method,
387
- params: message.params,
388
- });
389
- }
390
-
391
- private handleResponse(response: RpcResponse): void {
392
- const pending = this.pending.get(response.id);
393
- if (!pending) {
394
- return;
395
- }
396
- this.pending.delete(response.id);
397
- if (response.error) {
398
- pending.reject(new CodexAppServerRpcError(response.error, pending.method));
399
- return;
400
- }
401
- pending.resolve(response.result);
402
- }
403
-
404
- private async handleServerRequest(
405
- request: Required<Pick<RpcRequest, "id" | "method">> & { params?: JsonValue },
406
- ): Promise<void> {
407
- try {
408
- const result = await this.runServerRequestHandlers(request);
409
- if (result !== undefined) {
410
- this.writeMessage({ id: request.id, result });
411
- return;
412
- }
413
- this.writeMessage({ id: request.id, result: defaultServerRequestResponse(request) });
414
- } catch (error) {
415
- this.writeMessage({
416
- id: request.id,
417
- error: {
418
- message: error instanceof Error ? error.message : String(error),
419
- },
420
- });
421
- }
422
- }
423
-
424
- private async runServerRequestHandlers(
425
- request: Required<Pick<RpcRequest, "id" | "method">> & { params?: JsonValue },
426
- ): Promise<JsonValue | undefined> {
427
- const timeoutResponse = timeoutServerRequestResponse(request);
428
- if (!timeoutResponse) {
429
- return await this.runServerRequestHandlersWithoutTimeout(request);
430
- }
431
-
432
- let timeout: ReturnType<typeof setTimeout> | undefined;
433
- try {
434
- return await Promise.race([
435
- this.runServerRequestHandlersWithoutTimeout(request),
436
- new Promise<JsonValue>((resolve) => {
437
- timeout = setTimeout(() => {
438
- embeddedAgentLog.warn("codex app-server server request timed out", {
439
- id: request.id,
440
- method: request.method,
441
- timeoutMs: CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS,
442
- });
443
- resolve(timeoutResponse);
444
- }, CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS);
445
- timeout.unref?.();
446
- }),
447
- ]);
448
- } finally {
449
- if (timeout) {
450
- clearTimeout(timeout);
451
- }
452
- }
453
- }
454
-
455
- private async runServerRequestHandlersWithoutTimeout(
456
- request: Required<Pick<RpcRequest, "id" | "method">> & { params?: JsonValue },
457
- ): Promise<JsonValue | undefined> {
458
- for (const handler of this.requestHandlers) {
459
- const result = await handler(request);
460
- if (result !== undefined) {
461
- return result;
462
- }
463
- }
464
- return undefined;
465
- }
466
-
467
- private handleNotification(notification: CodexServerNotification): void {
468
- for (const handler of this.notificationHandlers) {
469
- Promise.resolve(handler(notification)).catch((error: unknown) => {
470
- embeddedAgentLog.warn("codex app-server notification handler failed", { error });
471
- });
472
- }
473
- }
474
-
475
- private closeWithError(error: Error): void {
476
- if (this.markClosed(error)) {
477
- closeCodexAppServerTransport(this.child);
478
- }
479
- }
480
-
481
- private markClosed(error: Error): boolean {
482
- if (this.closed) {
483
- return false;
484
- }
485
- this.closed = true;
486
- this.closeError = error;
487
- this.lines.close();
488
- this.rejectPendingRequests(error);
489
- return true;
490
- }
491
-
492
- private rejectPendingRequests(error: Error): void {
493
- for (const pending of this.pending.values()) {
494
- pending.cleanup();
495
- pending.reject(error);
496
- }
497
- this.pending.clear();
498
- for (const handler of this.closeHandlers) {
499
- handler(this);
500
- }
501
- }
502
- }
503
-
504
- function defaultServerRequestResponse(
505
- request: Required<Pick<RpcRequest, "id" | "method">> & { params?: JsonValue },
506
- ): JsonValue {
507
- if (request.method === "item/tool/call") {
508
- return {
509
- contentItems: [
510
- {
511
- type: "inputText",
512
- text: "Klaw did not register a handler for this app-server tool call.",
513
- },
514
- ],
515
- success: false,
516
- };
517
- }
518
- if (
519
- request.method === "item/commandExecution/requestApproval" ||
520
- request.method === "item/fileChange/requestApproval"
521
- ) {
522
- return { decision: "decline" };
523
- }
524
- if (request.method === "item/permissions/requestApproval") {
525
- return { permissions: {}, scope: "turn" };
526
- }
527
- if (isCodexAppServerApprovalRequest(request.method)) {
528
- return {
529
- decision: "decline",
530
- reason: "Klaw codex app-server bridge does not grant native approvals yet.",
531
- };
532
- }
533
- if (request.method === "item/tool/requestUserInput") {
534
- return {
535
- answers: {},
536
- };
537
- }
538
- if (request.method === "mcpServer/elicitation/request") {
539
- return {
540
- action: "decline",
541
- };
542
- }
543
- return {};
544
- }
545
-
546
- function stringifyCodexAppServerMessage(message: RpcRequest | RpcResponse): string {
547
- return (
548
- JSON.stringify(message, (_key, value) =>
549
- typeof value === "string" ? value.replace(UNPAIRED_SURROGATE_RE, "") : value,
550
- ) ?? "null"
551
- );
552
- }
553
-
554
- function timeoutServerRequestResponse(
555
- request: Required<Pick<RpcRequest, "id" | "method">> & { params?: JsonValue },
556
- ): JsonValue | undefined {
557
- if (request.method !== "item/tool/call") {
558
- return undefined;
559
- }
560
- return {
561
- contentItems: [
562
- {
563
- type: "inputText",
564
- text: `Klaw dynamic tool call timed out after ${CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS}ms before sending a response to Codex.`,
565
- },
566
- ],
567
- success: false,
568
- };
569
- }
570
-
571
- function assertSupportedCodexAppServerVersion(response: CodexInitializeResponse): void {
572
- const detectedVersion = readCodexVersionFromUserAgent(response.userAgent);
573
- if (!detectedVersion) {
574
- throw new Error(
575
- `Codex app-server ${MIN_CODEX_APP_SERVER_VERSION} or newer is required, but Klaw could not determine the running Codex version. Update the configured Codex app-server binary, or remove custom command overrides to use the managed binary.`,
576
- );
577
- }
578
- if (compareVersions(detectedVersion, MIN_CODEX_APP_SERVER_VERSION) < 0) {
579
- throw new Error(
580
- `Codex app-server ${MIN_CODEX_APP_SERVER_VERSION} or newer is required, but detected ${detectedVersion}. Update the configured Codex app-server binary, or remove custom command overrides to use the managed binary.`,
581
- );
582
- }
583
- }
584
-
585
- export function readCodexVersionFromUserAgent(userAgent: string | undefined): string | undefined {
586
- // Codex returns `<originator>/<codex-version> ...`; the originator can be
587
- // Klaw, Codex Desktop, or an env override, so only the slash-delimited
588
- // version in the leading product field is stable.
589
- const match = userAgent?.match(
590
- /^[^/]+\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)(?:[\s(]|$)/,
591
- );
592
- return match?.[1];
593
- }
594
-
595
- function compareVersions(left: string, right: string): number {
596
- const leftVersion = parseVersionForComparison(left);
597
- const rightVersion = parseVersionForComparison(right);
598
- const leftParts = leftVersion.parts;
599
- const rightParts = rightVersion.parts;
600
- for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
601
- const leftPart = leftParts[index] ?? 0;
602
- const rightPart = rightParts[index] ?? 0;
603
- if (leftPart !== rightPart) {
604
- return leftPart < rightPart ? -1 : 1;
605
- }
606
- }
607
- if (leftVersion.unstableSuffix && !rightVersion.unstableSuffix) {
608
- return -1;
609
- }
610
- if (!leftVersion.unstableSuffix && rightVersion.unstableSuffix) {
611
- return 1;
612
- }
613
- return 0;
614
- }
615
-
616
- function parseVersionForComparison(version: string): { parts: number[]; unstableSuffix: boolean } {
617
- // Same-version prerelease or build-suffixed versions do not satisfy a stable
618
- // protocol floor because important app-server contract changes can land
619
- // between alpha cuts and custom builds.
620
- const hasBuildMetadata = version.includes("+");
621
- const [withoutBuild = version] = version.split("+", 1);
622
- const prereleaseIndex = withoutBuild.indexOf("-");
623
- const numeric = prereleaseIndex >= 0 ? withoutBuild.slice(0, prereleaseIndex) : withoutBuild;
624
- return {
625
- parts: numeric
626
- .split(".")
627
- .map((part) => Number.parseInt(part, 10))
628
- .map((part) => (Number.isFinite(part) ? part : 0)),
629
- unstableSuffix: prereleaseIndex >= 0 || hasBuildMetadata,
630
- };
631
- }
632
-
633
- function redactCodexAppServerLinePreview(value: string): string {
634
- const compact = value.replace(/\s+/g, " ").trim();
635
- const redacted = compact
636
- .replace(/(Bearer\s+)[A-Za-z0-9._~+/-]+/gi, "$1<redacted>")
637
- .replace(
638
- /("(?:api_?key|authorization|token|access_token|refresh_token)"\s*:\s*")([^"]+)(")/gi,
639
- "$1<redacted>$3",
640
- )
641
- .replace(
642
- /\b([a-z0-9_]*(?:api_?key|authorization|access_token|refresh_token|token))(\s*=\s*)(["']?)[^\s"']+(\3)/gi,
643
- "$1$2$3<redacted>$4",
644
- );
645
- return redacted.length > CODEX_APP_SERVER_PARSE_LOG_MAX
646
- ? `${redacted.slice(0, CODEX_APP_SERVER_PARSE_LOG_MAX)}...`
647
- : redacted;
648
- }
649
-
650
- function appendBoundedTail(current: string, next: string, maxLength: number): string {
651
- const combined = `${current}${next}`;
652
- return combined.length > maxLength ? combined.slice(combined.length - maxLength) : combined;
653
- }
654
-
655
- function buildCodexAppServerExitError(code: unknown, signal: unknown, stderrTail: string): Error {
656
- const stderrPreview = redactCodexAppServerLinePreview(stderrTail);
657
- const suffix = stderrPreview ? ` stderr=${JSON.stringify(stderrPreview)}` : "";
658
- return new Error(
659
- `codex app-server exited: code=${formatExitValue(code)} signal=${formatExitValue(
660
- signal,
661
- )}${suffix}`,
662
- );
663
- }
664
-
665
- function shouldBufferCodexAppServerParseFailure(value: string, error: unknown): boolean {
666
- if (!value.startsWith("{") && !value.startsWith("[")) {
667
- return false;
668
- }
669
- const message = error instanceof Error ? error.message : String(error);
670
- return (
671
- message.includes("Unterminated string") || message.includes("Unexpected end of JSON input")
672
- );
673
- }
674
-
675
- function logCodexAppServerParseFailure(value: string, error: unknown, fragmentCount: number): void {
676
- const linePreview = redactCodexAppServerLinePreview(value);
677
- const suffix = fragmentCount > 1 ? ` fragments=${fragmentCount}` : "";
678
- embeddedAgentLog.warn("failed to parse codex app-server message", {
679
- error,
680
- errorMessage: error instanceof Error ? error.message : String(error),
681
- fragmentCount,
682
- linePreview,
683
- consoleMessage: `failed to parse codex app-server message${suffix}: preview=${JSON.stringify(
684
- linePreview,
685
- )}`,
686
- });
687
- }
688
-
689
- const CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS = new Set([
690
- "item/commandExecution/requestApproval",
691
- "item/fileChange/requestApproval",
692
- "item/permissions/requestApproval",
693
- ]);
694
-
695
- export function isCodexAppServerApprovalRequest(method: string): boolean {
696
- return CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS.has(method);
697
- }
698
-
699
- function formatExitValue(value: unknown): string {
700
- if (value === null || value === undefined) {
701
- return "null";
702
- }
703
- if (typeof value === "string" || typeof value === "number") {
704
- return String(value);
705
- }
706
- return "unknown";
707
- }
708
-
709
- export const testing = {
710
- closeCodexAppServerTransport,
711
- closeCodexAppServerTransportAndWait,
712
- CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS,
713
- redactCodexAppServerLinePreview,
714
- } as const;
715
- export { testing as __testing };