@kodelyth/codex 2026.5.40 → 2026.5.42

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 (178) hide show
  1. package/dist/client-ChMX13_o.js +642 -0
  2. package/dist/client-factory-D3dIsp4Y.js +9 -0
  3. package/dist/command-formatters-BRW7_Nu7.js +519 -0
  4. package/dist/command-handlers-P2IqtXaZ.js +1462 -0
  5. package/dist/compact-baos5flR.js +329 -0
  6. package/dist/computer-use-VfLvTMaa.js +367 -0
  7. package/dist/config-CezENx_E.js +510 -0
  8. package/dist/doctor-contract-api.js +53 -0
  9. package/dist/harness.js +51 -0
  10. package/dist/index.js +1133 -0
  11. package/dist/media-understanding-provider.js +335 -0
  12. package/dist/models-B9DhrIwD.js +110 -0
  13. package/dist/node-cli-sessions-De4_DuFw.js +1216 -0
  14. package/dist/plugin-activation-BlMuJeXz.js +452 -0
  15. package/dist/prompt-overlay.js +12 -0
  16. package/dist/protocol-C9UWI98H.js +9 -0
  17. package/dist/protocol-validators-BGBspNmF.js +5988 -0
  18. package/dist/provider-catalog.js +84 -0
  19. package/dist/provider-discovery.js +33 -0
  20. package/dist/provider.js +150 -0
  21. package/dist/rate-limit-cache-CHuacE27.js +24 -0
  22. package/dist/request-CTQKUxaa.js +89 -0
  23. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  24. package/dist/run-attempt-DqV2OU1R.js +5366 -0
  25. package/dist/session-binding-3PzU7ZTW.js +222 -0
  26. package/dist/shared-client-Cnyr9dyT.js +631 -0
  27. package/dist/side-question-CP5XlA0U.js +667 -0
  28. package/dist/test-api.js +45 -0
  29. package/dist/thread-lifecycle-DBJetBuV.js +1561 -0
  30. package/dist/vision-tools-Cl_5a93K.js +1379 -0
  31. package/doctor-contract-api.test.ts +44 -0
  32. package/doctor-contract-api.ts +68 -0
  33. package/harness.ts +72 -0
  34. package/index.test.ts +230 -0
  35. package/index.ts +66 -0
  36. package/klaw.plugin.json +24 -85
  37. package/media-understanding-provider.test.ts +486 -0
  38. package/media-understanding-provider.ts +521 -0
  39. package/package.json +3 -3
  40. package/prompt-overlay-runtime-contract.test.ts +48 -0
  41. package/prompt-overlay.ts +21 -0
  42. package/provider-catalog.ts +83 -0
  43. package/provider-discovery.ts +45 -0
  44. package/provider.test.ts +384 -0
  45. package/provider.ts +243 -0
  46. package/src/app-server/app-inventory-cache.test.ts +176 -0
  47. package/src/app-server/app-inventory-cache.ts +324 -0
  48. package/src/app-server/approval-bridge.test.ts +1471 -0
  49. package/src/app-server/approval-bridge.ts +1211 -0
  50. package/src/app-server/auth-bridge.test.ts +1449 -0
  51. package/src/app-server/auth-bridge.ts +614 -0
  52. package/src/app-server/auth-profile-runtime-contract.test.ts +239 -0
  53. package/src/app-server/capabilities.ts +27 -0
  54. package/src/app-server/client-factory.ts +24 -0
  55. package/src/app-server/client.test.ts +563 -0
  56. package/src/app-server/client.ts +715 -0
  57. package/src/app-server/compact.test.ts +710 -0
  58. package/src/app-server/compact.ts +500 -0
  59. package/src/app-server/computer-use.test.ts +788 -0
  60. package/src/app-server/computer-use.ts +683 -0
  61. package/src/app-server/config.test.ts +879 -0
  62. package/src/app-server/config.ts +1038 -0
  63. package/src/app-server/context-engine-projection.test.ts +252 -0
  64. package/src/app-server/context-engine-projection.ts +403 -0
  65. package/src/app-server/delivery-no-reply-runtime-contract.test.ts +80 -0
  66. package/src/app-server/dynamic-tool-diagnostics.ts +73 -0
  67. package/src/app-server/dynamic-tool-profile.ts +69 -0
  68. package/src/app-server/dynamic-tools.test.ts +1302 -0
  69. package/src/app-server/dynamic-tools.ts +623 -0
  70. package/src/app-server/elicitation-bridge.test.ts +1056 -0
  71. package/src/app-server/elicitation-bridge.ts +783 -0
  72. package/src/app-server/event-projector.test.ts +2668 -0
  73. package/src/app-server/event-projector.ts +2057 -0
  74. package/src/app-server/image-payload-sanitizer.test.ts +49 -0
  75. package/src/app-server/image-payload-sanitizer.ts +167 -0
  76. package/src/app-server/klaw-owned-tool-runtime-contract.test.ts +456 -0
  77. package/src/app-server/local-runtime-attribution.ts +39 -0
  78. package/src/app-server/managed-binary.test.ts +139 -0
  79. package/src/app-server/managed-binary.ts +193 -0
  80. package/src/app-server/models.test.ts +246 -0
  81. package/src/app-server/models.ts +172 -0
  82. package/src/app-server/native-hook-relay.test.ts +271 -0
  83. package/src/app-server/native-hook-relay.ts +150 -0
  84. package/src/app-server/native-subagent-task-mirror.test.ts +573 -0
  85. package/src/app-server/native-subagent-task-mirror.ts +497 -0
  86. package/src/app-server/outcome-fallback-runtime-contract.test.ts +404 -0
  87. package/src/app-server/plugin-activation.test.ts +336 -0
  88. package/src/app-server/plugin-activation.ts +283 -0
  89. package/src/app-server/plugin-app-cache-key.ts +74 -0
  90. package/src/app-server/plugin-approval-roundtrip.ts +122 -0
  91. package/src/app-server/plugin-inventory.test.ts +355 -0
  92. package/src/app-server/plugin-inventory.ts +357 -0
  93. package/src/app-server/plugin-thread-config.test.ts +865 -0
  94. package/src/app-server/plugin-thread-config.ts +455 -0
  95. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +33 -0
  96. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +199 -0
  97. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +102 -0
  98. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +227 -0
  99. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +2630 -0
  100. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +2630 -0
  101. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +1659 -0
  102. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +1655 -0
  103. package/src/app-server/protocol-validators.test.ts +75 -0
  104. package/src/app-server/protocol-validators.ts +203 -0
  105. package/src/app-server/protocol.ts +520 -0
  106. package/src/app-server/rate-limit-cache.ts +48 -0
  107. package/src/app-server/rate-limits.test.ts +202 -0
  108. package/src/app-server/rate-limits.ts +583 -0
  109. package/src/app-server/request.ts +73 -0
  110. package/src/app-server/run-attempt.context-engine.test.ts +1004 -0
  111. package/src/app-server/run-attempt.test.ts +9477 -0
  112. package/src/app-server/run-attempt.ts +4683 -0
  113. package/src/app-server/run-attempt.vision-tools.test.ts +35 -0
  114. package/src/app-server/schema-normalization-runtime-contract.test.ts +206 -0
  115. package/src/app-server/session-binding.test.ts +303 -0
  116. package/src/app-server/session-binding.ts +398 -0
  117. package/src/app-server/session-history.ts +44 -0
  118. package/src/app-server/shared-client.test.ts +589 -0
  119. package/src/app-server/shared-client.ts +289 -0
  120. package/src/app-server/side-question.test.ts +1175 -0
  121. package/src/app-server/side-question.ts +1007 -0
  122. package/src/app-server/test-support.ts +48 -0
  123. package/src/app-server/thread-lifecycle.test.ts +447 -0
  124. package/src/app-server/thread-lifecycle.ts +939 -0
  125. package/src/app-server/thread-lifecycle.user-mcp-servers.test.ts +442 -0
  126. package/src/app-server/timeout.ts +9 -0
  127. package/src/app-server/tool-progress-normalization.ts +77 -0
  128. package/src/app-server/trajectory.test.ts +205 -0
  129. package/src/app-server/trajectory.ts +365 -0
  130. package/src/app-server/transcript-mirror.test.ts +524 -0
  131. package/src/app-server/transcript-mirror.ts +208 -0
  132. package/src/app-server/transcript-repair-runtime-contract.test.ts +44 -0
  133. package/src/app-server/transport-stdio.test.ts +171 -0
  134. package/src/app-server/transport-stdio.ts +107 -0
  135. package/src/app-server/transport-websocket.test.ts +69 -0
  136. package/src/app-server/transport-websocket.ts +90 -0
  137. package/src/app-server/transport.ts +117 -0
  138. package/src/app-server/user-input-bridge.test.ts +249 -0
  139. package/src/app-server/user-input-bridge.ts +316 -0
  140. package/src/app-server/version.ts +4 -0
  141. package/src/app-server/vision-tools.ts +12 -0
  142. package/src/command-account.ts +544 -0
  143. package/src/command-formatters.ts +425 -0
  144. package/src/command-handlers.ts +2004 -0
  145. package/src/command-rpc.test.ts +16 -0
  146. package/src/command-rpc.ts +142 -0
  147. package/src/commands.test.ts +3312 -0
  148. package/src/commands.ts +65 -0
  149. package/src/conversation-binding-data.ts +124 -0
  150. package/src/conversation-binding.test.ts +599 -0
  151. package/src/conversation-binding.ts +561 -0
  152. package/src/conversation-control.test.ts +126 -0
  153. package/src/conversation-control.ts +303 -0
  154. package/src/conversation-turn-collector.test.ts +191 -0
  155. package/src/conversation-turn-collector.ts +186 -0
  156. package/src/conversation-turn-input.test.ts +141 -0
  157. package/src/conversation-turn-input.ts +106 -0
  158. package/src/manifest.test.ts +20 -0
  159. package/src/migration/apply.ts +501 -0
  160. package/src/migration/helpers.ts +55 -0
  161. package/src/migration/plan.ts +461 -0
  162. package/src/migration/provider.test.ts +1741 -0
  163. package/src/migration/provider.ts +41 -0
  164. package/src/migration/source.ts +643 -0
  165. package/src/migration/targets.ts +25 -0
  166. package/src/node-cli-sessions.test.ts +180 -0
  167. package/src/node-cli-sessions.ts +711 -0
  168. package/test-api.ts +82 -0
  169. package/tsconfig.json +16 -0
  170. package/doctor-contract-api.js +0 -7
  171. package/harness.js +0 -7
  172. package/index.js +0 -7
  173. package/media-understanding-provider.js +0 -7
  174. package/prompt-overlay.js +0 -7
  175. package/provider-catalog.js +0 -7
  176. package/provider-discovery.js +0 -7
  177. package/provider.js +0 -7
  178. package/test-api.js +0 -7
@@ -0,0 +1,117 @@
1
+ export type CodexAppServerTransport = {
2
+ stdin: {
3
+ write: (data: string, callback?: (error?: Error | null) => void) => unknown;
4
+ end?: () => unknown;
5
+ destroy?: () => unknown;
6
+ unref?: () => unknown;
7
+ on?: (event: "error", listener: (error: Error) => void) => unknown;
8
+ };
9
+ stdout: NodeJS.ReadableStream & {
10
+ destroy?: () => unknown;
11
+ unref?: () => unknown;
12
+ };
13
+ stderr: NodeJS.ReadableStream & {
14
+ destroy?: () => unknown;
15
+ unref?: () => unknown;
16
+ };
17
+ pid?: number;
18
+ exitCode?: number | null;
19
+ signalCode?: string | null;
20
+ killed?: boolean;
21
+ kill?: (signal?: NodeJS.Signals) => unknown;
22
+ unref?: () => unknown;
23
+ once: (event: string, listener: (...args: unknown[]) => void) => unknown;
24
+ off?: (event: string, listener: (...args: unknown[]) => void) => unknown;
25
+ };
26
+
27
+ export function closeCodexAppServerTransport(
28
+ child: CodexAppServerTransport,
29
+ options: { forceKillDelayMs?: number } = {},
30
+ ): void {
31
+ child.stdin.end?.();
32
+ child.stdin.destroy?.();
33
+ const forceKillDelayMs = options.forceKillDelayMs ?? 1_000;
34
+ const forceKill = setTimeout(
35
+ () => {
36
+ if (hasCodexAppServerTransportExited(child)) {
37
+ return;
38
+ }
39
+ signalCodexAppServerTransport(child, "SIGKILL");
40
+ },
41
+ Math.max(1, forceKillDelayMs),
42
+ );
43
+ forceKill.unref?.();
44
+ child.once("exit", () => {
45
+ clearTimeout(forceKill);
46
+ child.stdout.destroy?.();
47
+ child.stderr.destroy?.();
48
+ });
49
+ child.unref?.();
50
+ child.stdout.unref?.();
51
+ child.stderr.unref?.();
52
+ child.stdin.unref?.();
53
+ }
54
+
55
+ export async function closeCodexAppServerTransportAndWait(
56
+ child: CodexAppServerTransport,
57
+ options: { exitTimeoutMs?: number; forceKillDelayMs?: number } = {},
58
+ ): Promise<boolean> {
59
+ if (!hasCodexAppServerTransportExited(child)) {
60
+ closeCodexAppServerTransport(child, options);
61
+ }
62
+ return await waitForCodexAppServerTransportExit(child, options.exitTimeoutMs ?? 2_000);
63
+ }
64
+
65
+ function hasCodexAppServerTransportExited(child: CodexAppServerTransport): boolean {
66
+ return child.exitCode !== null && child.exitCode !== undefined
67
+ ? true
68
+ : child.signalCode !== null && child.signalCode !== undefined;
69
+ }
70
+
71
+ async function waitForCodexAppServerTransportExit(
72
+ child: CodexAppServerTransport,
73
+ timeoutMs: number,
74
+ ): Promise<boolean> {
75
+ if (hasCodexAppServerTransportExited(child)) {
76
+ return true;
77
+ }
78
+ return await new Promise<boolean>((resolve) => {
79
+ let settled = false;
80
+ const onExit = () => {
81
+ if (settled) {
82
+ return;
83
+ }
84
+ settled = true;
85
+ clearTimeout(timeout);
86
+ resolve(true);
87
+ };
88
+ const timeout = setTimeout(
89
+ () => {
90
+ if (settled) {
91
+ return;
92
+ }
93
+ settled = true;
94
+ child.off?.("exit", onExit);
95
+ resolve(false);
96
+ },
97
+ Math.max(1, timeoutMs),
98
+ );
99
+ child.once("exit", onExit);
100
+ });
101
+ }
102
+
103
+ function signalCodexAppServerTransport(
104
+ child: CodexAppServerTransport,
105
+ signal: NodeJS.Signals,
106
+ ): void {
107
+ if (child.pid && process.platform !== "win32") {
108
+ try {
109
+ process.kill(-child.pid, signal);
110
+ return;
111
+ } catch {
112
+ // Fall back to the child handle. The process may already be gone or not
113
+ // be a process-group leader on older call sites.
114
+ }
115
+ }
116
+ child.kill?.(signal);
117
+ }
@@ -0,0 +1,249 @@
1
+ import type { EmbeddedRunAttemptParams } from "klaw/plugin-sdk/agent-harness-runtime";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { createCodexUserInputBridge } from "./user-input-bridge.js";
4
+
5
+ function createParams(): EmbeddedRunAttemptParams {
6
+ return {
7
+ sessionId: "session-1",
8
+ sessionKey: "agent:main:session-1",
9
+ onBlockReply: vi.fn(),
10
+ } as unknown as EmbeddedRunAttemptParams;
11
+ }
12
+
13
+ function expectFirstBlockReplyText(params: EmbeddedRunAttemptParams): string {
14
+ const onBlockReply = params.onBlockReply;
15
+ if (onBlockReply === undefined) {
16
+ throw new Error("Expected onBlockReply callback");
17
+ }
18
+ const payload = vi.mocked(onBlockReply).mock.calls[0]?.[0];
19
+ if (typeof payload?.text !== "string") {
20
+ throw new Error("Expected first block reply text");
21
+ }
22
+ return payload.text;
23
+ }
24
+
25
+ describe("Codex app-server user input bridge", () => {
26
+ it("prompts the originating chat and resolves request_user_input from the next queued message", async () => {
27
+ const params = createParams();
28
+ const bridge = createCodexUserInputBridge({
29
+ paramsForRun: params,
30
+ threadId: "thread-1",
31
+ turnId: "turn-1",
32
+ });
33
+
34
+ const response = bridge.handleRequest({
35
+ id: "input-1",
36
+ params: {
37
+ threadId: "thread-1",
38
+ turnId: "turn-1",
39
+ itemId: "tool-1",
40
+ questions: [
41
+ {
42
+ id: "choice",
43
+ header: "Mode",
44
+ question: "Pick a mode",
45
+ isOther: false,
46
+ isSecret: false,
47
+ options: [
48
+ { label: "Fast", description: "Use less reasoning" },
49
+ { label: "Deep", description: "Use more reasoning" },
50
+ ],
51
+ },
52
+ ],
53
+ },
54
+ });
55
+
56
+ await vi.waitFor(() => expect(params.onBlockReply).toHaveBeenCalledTimes(1));
57
+ expect(expectFirstBlockReplyText(params)).toContain("Pick a mode");
58
+ expect(bridge.handleQueuedMessage("2")).toBe(true);
59
+
60
+ await expect(response).resolves.toEqual({
61
+ answers: { choice: { answers: ["Deep"] } },
62
+ });
63
+ });
64
+
65
+ it("maps keyed multi-question replies to Codex answer ids", async () => {
66
+ const params = createParams();
67
+ const bridge = createCodexUserInputBridge({
68
+ paramsForRun: params,
69
+ threadId: "thread-1",
70
+ turnId: "turn-1",
71
+ });
72
+
73
+ const response = bridge.handleRequest({
74
+ id: "input-2",
75
+ params: {
76
+ threadId: "thread-1",
77
+ turnId: "turn-1",
78
+ itemId: "tool-1",
79
+ questions: [
80
+ {
81
+ id: "repo",
82
+ header: "Repository",
83
+ question: "Which repo?",
84
+ isOther: true,
85
+ isSecret: false,
86
+ options: null,
87
+ },
88
+ {
89
+ id: "scope",
90
+ header: "Scope",
91
+ question: "Which scope?",
92
+ isOther: false,
93
+ isSecret: false,
94
+ options: [{ label: "Tests", description: "Only tests" }],
95
+ },
96
+ ],
97
+ },
98
+ });
99
+
100
+ await vi.waitFor(() => expect(params.onBlockReply).toHaveBeenCalledTimes(1));
101
+ expect(bridge.handleQueuedMessage("repo: klaw\nscope: Tests")).toBe(true);
102
+
103
+ await expect(response).resolves.toEqual({
104
+ answers: {
105
+ repo: { answers: ["klaw"] },
106
+ scope: { answers: ["Tests"] },
107
+ },
108
+ });
109
+ });
110
+
111
+ it("rejects free-form option replies when Other is disabled", async () => {
112
+ const params = createParams();
113
+ const bridge = createCodexUserInputBridge({
114
+ paramsForRun: params,
115
+ threadId: "thread-1",
116
+ turnId: "turn-1",
117
+ });
118
+
119
+ const response = bridge.handleRequest({
120
+ id: "input-options",
121
+ params: {
122
+ threadId: "thread-1",
123
+ turnId: "turn-1",
124
+ itemId: "tool-1",
125
+ questions: [
126
+ {
127
+ id: "mode",
128
+ header: "Mode",
129
+ question: "Pick a mode",
130
+ isOther: false,
131
+ isSecret: false,
132
+ options: [{ label: "Fast", description: "Use less reasoning" }],
133
+ },
134
+ ],
135
+ },
136
+ });
137
+
138
+ await vi.waitFor(() => expect(params.onBlockReply).toHaveBeenCalledTimes(1));
139
+ expect(bridge.handleQueuedMessage("banana")).toBe(true);
140
+
141
+ await expect(response).resolves.toEqual({
142
+ answers: { mode: { answers: [] } },
143
+ });
144
+ });
145
+
146
+ it("escapes prompt question and option text before chat display", async () => {
147
+ const params = createParams();
148
+ const bridge = createCodexUserInputBridge({
149
+ paramsForRun: params,
150
+ threadId: "thread-1",
151
+ turnId: "turn-1",
152
+ });
153
+
154
+ const response = bridge.handleRequest({
155
+ id: "input-escaped",
156
+ params: {
157
+ threadId: "thread-1",
158
+ turnId: "turn-1",
159
+ itemId: "tool-1",
160
+ questions: [
161
+ {
162
+ id: "mode",
163
+ header: "Mode <@U123>",
164
+ question: "Pick [trusted](https://evil) @here",
165
+ isOther: false,
166
+ isSecret: false,
167
+ options: [{ label: "Fast <@U123>", description: "Use [less](https://evil)" }],
168
+ },
169
+ ],
170
+ },
171
+ });
172
+
173
+ await vi.waitFor(() => expect(params.onBlockReply).toHaveBeenCalledTimes(1));
174
+ const text = expectFirstBlockReplyText(params);
175
+ expect(text).toContain("Mode &lt;\uff20U123&gt;");
176
+ expect(text).toContain("Pick \uff3btrusted\uff3d\uff08https://evil\uff09 \uff20here");
177
+ expect(text).toContain(
178
+ "Fast &lt;\uff20U123&gt; - Use \uff3bless\uff3d\uff08https://evil\uff09",
179
+ );
180
+ expect(text).not.toContain("<@U123>");
181
+ expect(text).not.toContain("[trusted](https://evil)");
182
+ expect(text).not.toContain("@here");
183
+
184
+ expect(bridge.handleQueuedMessage("1")).toBe(true);
185
+ await expect(response).resolves.toEqual({
186
+ answers: { mode: { answers: ["Fast <@U123>"] } },
187
+ });
188
+ });
189
+
190
+ it("clears pending prompts when Codex resolves the server request itself", async () => {
191
+ const params = createParams();
192
+ const bridge = createCodexUserInputBridge({
193
+ paramsForRun: params,
194
+ threadId: "thread-1",
195
+ turnId: "turn-1",
196
+ });
197
+
198
+ const response = bridge.handleRequest({
199
+ id: "input-3",
200
+ params: {
201
+ threadId: "thread-1",
202
+ turnId: "turn-1",
203
+ itemId: "tool-1",
204
+ questions: [
205
+ {
206
+ id: "answer",
207
+ header: "Answer",
208
+ question: "Continue?",
209
+ isOther: true,
210
+ isSecret: false,
211
+ options: null,
212
+ },
213
+ ],
214
+ },
215
+ });
216
+
217
+ await vi.waitFor(() => expect(params.onBlockReply).toHaveBeenCalledTimes(1));
218
+ bridge.handleNotification({
219
+ method: "serverRequest/resolved",
220
+ params: { threadId: "thread-1", requestId: "input-3" },
221
+ });
222
+
223
+ await expect(response).resolves.toEqual({ answers: {} });
224
+ expect(bridge.handleQueuedMessage("too late")).toBe(false);
225
+ });
226
+
227
+ it("resolves malformed empty question prompts without waiting for chat input", async () => {
228
+ const params = createParams();
229
+ const bridge = createCodexUserInputBridge({
230
+ paramsForRun: params,
231
+ threadId: "thread-1",
232
+ turnId: "turn-1",
233
+ });
234
+
235
+ await expect(
236
+ bridge.handleRequest({
237
+ id: "input-empty",
238
+ params: {
239
+ threadId: "thread-1",
240
+ turnId: "turn-1",
241
+ itemId: "tool-1",
242
+ questions: [],
243
+ },
244
+ }),
245
+ ).resolves.toEqual({ answers: {} });
246
+ expect(params.onBlockReply).not.toHaveBeenCalled();
247
+ expect(bridge.handleQueuedMessage("late answer")).toBe(false);
248
+ });
249
+ });
@@ -0,0 +1,316 @@
1
+ import {
2
+ embeddedAgentLog,
3
+ type EmbeddedRunAttemptParams,
4
+ } from "klaw/plugin-sdk/agent-harness-runtime";
5
+ import { formatCodexDisplayText } from "../command-formatters.js";
6
+ import {
7
+ isJsonObject,
8
+ type CodexServerNotification,
9
+ type JsonObject,
10
+ type JsonValue,
11
+ } from "./protocol.js";
12
+
13
+ type PendingUserInput = {
14
+ requestId: number | string;
15
+ threadId: string;
16
+ turnId: string;
17
+ itemId: string;
18
+ questions: UserInputQuestion[];
19
+ resolve: (value: JsonValue) => void;
20
+ cleanup: () => void;
21
+ };
22
+
23
+ type UserInputQuestion = {
24
+ id: string;
25
+ header: string;
26
+ question: string;
27
+ isOther: boolean;
28
+ isSecret: boolean;
29
+ options: UserInputOption[] | null;
30
+ };
31
+
32
+ type UserInputOption = {
33
+ label: string;
34
+ description: string;
35
+ };
36
+
37
+ type CodexUserInputBridge = {
38
+ handleRequest: (request: {
39
+ id: number | string;
40
+ params?: JsonValue;
41
+ }) => Promise<JsonValue | undefined>;
42
+ handleQueuedMessage: (text: string) => boolean;
43
+ handleNotification: (notification: CodexServerNotification) => void;
44
+ cancelPending: () => void;
45
+ };
46
+
47
+ export function createCodexUserInputBridge(params: {
48
+ paramsForRun: EmbeddedRunAttemptParams;
49
+ threadId: string;
50
+ turnId: string;
51
+ signal?: AbortSignal;
52
+ }): CodexUserInputBridge {
53
+ let pending: PendingUserInput | undefined;
54
+
55
+ const resolvePending = (value: JsonValue) => {
56
+ const current = pending;
57
+ if (!current) {
58
+ return;
59
+ }
60
+ pending = undefined;
61
+ current.cleanup();
62
+ current.resolve(value);
63
+ };
64
+
65
+ return {
66
+ async handleRequest(request) {
67
+ const requestParams = readUserInputParams(request.params);
68
+ if (!requestParams) {
69
+ return undefined;
70
+ }
71
+ if (requestParams.threadId !== params.threadId || requestParams.turnId !== params.turnId) {
72
+ return undefined;
73
+ }
74
+ if (requestParams.questions.length === 0) {
75
+ return emptyUserInputResponse();
76
+ }
77
+
78
+ resolvePending(emptyUserInputResponse());
79
+
80
+ return new Promise<JsonValue>((resolve) => {
81
+ const abortListener = () => resolvePending(emptyUserInputResponse());
82
+ const cleanup = () => params.signal?.removeEventListener("abort", abortListener);
83
+ pending = {
84
+ requestId: request.id,
85
+ threadId: requestParams.threadId,
86
+ turnId: requestParams.turnId,
87
+ itemId: requestParams.itemId,
88
+ questions: requestParams.questions,
89
+ resolve,
90
+ cleanup,
91
+ };
92
+ params.signal?.addEventListener("abort", abortListener, { once: true });
93
+ if (params.signal?.aborted) {
94
+ resolvePending(emptyUserInputResponse());
95
+ return;
96
+ }
97
+ void deliverUserInputPrompt(params.paramsForRun, requestParams.questions).catch((error) => {
98
+ embeddedAgentLog.warn("failed to deliver codex user input prompt", { error });
99
+ });
100
+ });
101
+ },
102
+ handleQueuedMessage(text) {
103
+ const current = pending;
104
+ if (!current) {
105
+ return false;
106
+ }
107
+ resolvePending(buildUserInputResponse(current.questions, text));
108
+ return true;
109
+ },
110
+ handleNotification(notification) {
111
+ if (notification.method !== "serverRequest/resolved" || !pending) {
112
+ return;
113
+ }
114
+ const notificationParams = isJsonObject(notification.params)
115
+ ? notification.params
116
+ : undefined;
117
+ const requestId = notificationParams ? readRequestId(notificationParams) : undefined;
118
+ if (
119
+ notificationParams &&
120
+ readString(notificationParams, "threadId") === pending.threadId &&
121
+ requestId !== undefined &&
122
+ String(requestId) === String(pending.requestId)
123
+ ) {
124
+ resolvePending(emptyUserInputResponse());
125
+ }
126
+ },
127
+ cancelPending() {
128
+ resolvePending(emptyUserInputResponse());
129
+ },
130
+ };
131
+ }
132
+
133
+ function readUserInputParams(value: JsonValue | undefined):
134
+ | {
135
+ threadId: string;
136
+ turnId: string;
137
+ itemId: string;
138
+ questions: UserInputQuestion[];
139
+ }
140
+ | undefined {
141
+ if (!isJsonObject(value)) {
142
+ return undefined;
143
+ }
144
+ const threadId = readString(value, "threadId");
145
+ const turnId = readString(value, "turnId");
146
+ const itemId = readString(value, "itemId");
147
+ const questionsRaw = value.questions;
148
+ if (!threadId || !turnId || !itemId || !Array.isArray(questionsRaw)) {
149
+ return undefined;
150
+ }
151
+ const questions = questionsRaw
152
+ .map(readQuestion)
153
+ .filter((question): question is UserInputQuestion => Boolean(question));
154
+ return { threadId, turnId, itemId, questions };
155
+ }
156
+
157
+ function readQuestion(value: JsonValue): UserInputQuestion | undefined {
158
+ if (!isJsonObject(value)) {
159
+ return undefined;
160
+ }
161
+ const id = readString(value, "id");
162
+ const header = readString(value, "header");
163
+ const question = readString(value, "question");
164
+ if (!id || !header || !question) {
165
+ return undefined;
166
+ }
167
+ return {
168
+ id,
169
+ header,
170
+ question,
171
+ isOther: value.isOther === true,
172
+ isSecret: value.isSecret === true,
173
+ options: readOptions(value.options),
174
+ };
175
+ }
176
+
177
+ function readOptions(value: JsonValue | undefined): UserInputOption[] | null {
178
+ if (!Array.isArray(value)) {
179
+ return null;
180
+ }
181
+ const options = value
182
+ .map(readOption)
183
+ .filter((option): option is UserInputOption => Boolean(option));
184
+ return options.length > 0 ? options : null;
185
+ }
186
+
187
+ function readOption(value: JsonValue): UserInputOption | undefined {
188
+ if (!isJsonObject(value)) {
189
+ return undefined;
190
+ }
191
+ const label = readString(value, "label");
192
+ const description = readString(value, "description") ?? "";
193
+ return label ? { label, description } : undefined;
194
+ }
195
+
196
+ async function deliverUserInputPrompt(
197
+ params: EmbeddedRunAttemptParams,
198
+ questions: UserInputQuestion[],
199
+ ): Promise<void> {
200
+ const text = formatUserInputPrompt(questions);
201
+ if (params.onBlockReply) {
202
+ await params.onBlockReply({ text });
203
+ return;
204
+ }
205
+ await params.onPartialReply?.({ text });
206
+ }
207
+
208
+ function formatUserInputPrompt(questions: UserInputQuestion[]): string {
209
+ const lines = ["Codex needs input:"];
210
+ questions.forEach((question, index) => {
211
+ if (questions.length > 1) {
212
+ lines.push(
213
+ "",
214
+ `${index + 1}. ${formatCodexDisplayText(question.header)}`,
215
+ formatCodexDisplayText(question.question),
216
+ );
217
+ } else {
218
+ lines.push(
219
+ "",
220
+ formatCodexDisplayText(question.header),
221
+ formatCodexDisplayText(question.question),
222
+ );
223
+ }
224
+ if (question.isSecret) {
225
+ lines.push("This channel may show your reply to other participants.");
226
+ }
227
+ question.options?.forEach((option, optionIndex) => {
228
+ lines.push(
229
+ `${optionIndex + 1}. ${formatCodexDisplayText(option.label)}${
230
+ option.description ? ` - ${formatCodexDisplayText(option.description)}` : ""
231
+ }`,
232
+ );
233
+ });
234
+ if (question.isOther) {
235
+ lines.push("Other: reply with your own answer.");
236
+ }
237
+ });
238
+ return lines.join("\n");
239
+ }
240
+
241
+ function buildUserInputResponse(questions: UserInputQuestion[], inputText: string): JsonObject {
242
+ const answers: JsonObject = {};
243
+ if (questions.length === 1) {
244
+ const question = questions[0];
245
+ if (question) {
246
+ const answer = normalizeAnswer(inputText, question);
247
+ answers[question.id] = { answers: answer ? [answer] : [] };
248
+ }
249
+ return { answers };
250
+ }
251
+
252
+ const keyed = parseKeyedAnswers(inputText);
253
+ const fallbackLines = inputText
254
+ .split(/\r?\n/)
255
+ .map((line) => line.trim())
256
+ .filter(Boolean);
257
+ questions.forEach((question, index) => {
258
+ const key =
259
+ keyed.get(question.id.toLowerCase()) ??
260
+ keyed.get(question.header.toLowerCase()) ??
261
+ keyed.get(question.question.toLowerCase()) ??
262
+ keyed.get(String(index + 1));
263
+ const answer = key ?? fallbackLines[index] ?? "";
264
+ const normalized = answer ? normalizeAnswer(answer, question) : undefined;
265
+ answers[question.id] = { answers: normalized ? [normalized] : [] };
266
+ });
267
+ return { answers };
268
+ }
269
+
270
+ function normalizeAnswer(answer: string, question: UserInputQuestion): string | undefined {
271
+ const trimmed = answer.trim();
272
+ const options = question.options ?? [];
273
+ const optionIndex = /^\d+$/.test(trimmed) ? Number(trimmed) - 1 : -1;
274
+ const indexed = optionIndex >= 0 ? options[optionIndex] : undefined;
275
+ if (indexed) {
276
+ return indexed.label;
277
+ }
278
+ const exact = options.find((option) => option.label.toLowerCase() === trimmed.toLowerCase());
279
+ if (exact) {
280
+ return exact.label;
281
+ }
282
+ if (options.length > 0 && !question.isOther) {
283
+ return undefined;
284
+ }
285
+ return trimmed || undefined;
286
+ }
287
+
288
+ function parseKeyedAnswers(inputText: string): Map<string, string> {
289
+ const answers = new Map<string, string>();
290
+ for (const line of inputText.split(/\r?\n/)) {
291
+ const match = line.match(/^\s*([^:=-]+?)\s*[:=-]\s*(.+?)\s*$/);
292
+ if (!match) {
293
+ continue;
294
+ }
295
+ const key = match[1]?.trim().toLowerCase();
296
+ const value = match[2]?.trim();
297
+ if (key && value) {
298
+ answers.set(key, value);
299
+ }
300
+ }
301
+ return answers;
302
+ }
303
+
304
+ function emptyUserInputResponse(): JsonObject {
305
+ return { answers: {} };
306
+ }
307
+
308
+ function readString(record: JsonObject, key: string): string | undefined {
309
+ const value = record[key];
310
+ return typeof value === "string" ? value : undefined;
311
+ }
312
+
313
+ function readRequestId(record: JsonObject): string | number | undefined {
314
+ const value = record.requestId;
315
+ return typeof value === "string" || typeof value === "number" ? value : undefined;
316
+ }
@@ -0,0 +1,4 @@
1
+ export const MIN_CODEX_APP_SERVER_VERSION = "0.125.0";
2
+ export const MANAGED_CODEX_APP_SERVER_PACKAGE = "@openai/codex";
3
+ // Keep this in sync with the Codex CLI live-test package pin.
4
+ export const MANAGED_CODEX_APP_SERVER_PACKAGE_VERSION = "0.130.0";
@@ -0,0 +1,12 @@
1
+ export function filterToolsForVisionInputs<T extends { name?: string }>(
2
+ tools: T[],
3
+ params: {
4
+ modelHasVision: boolean;
5
+ hasInboundImages: boolean;
6
+ },
7
+ ): T[] {
8
+ if (!params.modelHasVision || !params.hasInboundImages) {
9
+ return tools;
10
+ }
11
+ return tools.filter((tool) => tool.name !== "image");
12
+ }