@kodelyth/codex 2026.5.42 → 2026.6.2

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 +17 -2
  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,599 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
-
6
- const sharedClientMocks = vi.hoisted(() => ({
7
- getSharedCodexAppServerClient: vi.fn(),
8
- }));
9
-
10
- const agentRuntimeMocks = vi.hoisted(() => ({
11
- ensureAuthProfileStore: vi.fn(),
12
- loadAuthProfileStoreForSecretsRuntime: vi.fn(),
13
- resolveApiKeyForProfile: vi.fn(),
14
- resolveAuthProfileOrder: vi.fn(),
15
- resolveDefaultAgentDir: vi.fn(() => "/agent"),
16
- resolvePersistedAuthProfileOwnerAgentDir: vi.fn(),
17
- resolveProviderIdForAuth: vi.fn((provider: string) => provider),
18
- saveAuthProfileStore: vi.fn(),
19
- }));
20
-
21
- vi.mock("./app-server/shared-client.js", () => sharedClientMocks);
22
- vi.mock("klaw/plugin-sdk/agent-runtime", () => agentRuntimeMocks);
23
-
24
- import {
25
- handleCodexConversationBindingResolved,
26
- handleCodexConversationInboundClaim,
27
- startCodexConversationThread,
28
- } from "./conversation-binding.js";
29
-
30
- let tempDir: string;
31
-
32
- function mockCallArg(mock: ReturnType<typeof vi.fn>, callIndex = 0, argIndex = 0): unknown {
33
- const call = mock.mock.calls[callIndex];
34
- if (!call) {
35
- throw new Error(`Expected mock call ${callIndex}`);
36
- }
37
- return call[argIndex];
38
- }
39
-
40
- describe("codex conversation binding", () => {
41
- beforeEach(async () => {
42
- tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "klaw-codex-binding-"));
43
- });
44
-
45
- afterEach(async () => {
46
- sharedClientMocks.getSharedCodexAppServerClient.mockReset();
47
- agentRuntimeMocks.ensureAuthProfileStore.mockReset();
48
- agentRuntimeMocks.loadAuthProfileStoreForSecretsRuntime.mockReset();
49
- agentRuntimeMocks.resolveApiKeyForProfile.mockReset();
50
- agentRuntimeMocks.resolveAuthProfileOrder.mockReset();
51
- agentRuntimeMocks.resolveDefaultAgentDir.mockClear();
52
- agentRuntimeMocks.resolvePersistedAuthProfileOwnerAgentDir.mockReset();
53
- agentRuntimeMocks.resolveProviderIdForAuth.mockClear();
54
- agentRuntimeMocks.saveAuthProfileStore.mockReset();
55
- await fs.rm(tempDir, { recursive: true, force: true });
56
- });
57
-
58
- beforeEach(() => {
59
- agentRuntimeMocks.ensureAuthProfileStore.mockReturnValue({
60
- version: 1,
61
- profiles: {},
62
- });
63
- agentRuntimeMocks.resolveAuthProfileOrder.mockReturnValue([]);
64
- agentRuntimeMocks.resolveDefaultAgentDir.mockReturnValue("/agent");
65
- agentRuntimeMocks.resolveProviderIdForAuth.mockImplementation((provider: string) => provider);
66
- });
67
-
68
- it("uses the default Codex auth profile and omits the public OpenAI provider for new binds", async () => {
69
- const sessionFile = path.join(tempDir, "session.jsonl");
70
- const config = {
71
- auth: { order: { "openai-codex": ["openai-codex:default"] } },
72
- };
73
- const requests: Array<{ method: string; params: Record<string, unknown> }> = [];
74
- agentRuntimeMocks.ensureAuthProfileStore.mockReturnValue({
75
- version: 1,
76
- profiles: {
77
- "openai-codex:default": {
78
- type: "oauth",
79
- provider: "openai-codex",
80
- access: "access-token",
81
- },
82
- },
83
- });
84
- agentRuntimeMocks.resolveAuthProfileOrder.mockReturnValue(["openai-codex:default"]);
85
- sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({
86
- request: vi.fn(async (method: string, requestParams: Record<string, unknown>) => {
87
- requests.push({ method, params: requestParams });
88
- return {
89
- thread: { id: "thread-new", sessionId: "session-1", cwd: tempDir },
90
- model: "gpt-5.4-mini",
91
- };
92
- }),
93
- });
94
-
95
- await startCodexConversationThread({
96
- config: config as never,
97
- sessionFile,
98
- workspaceDir: tempDir,
99
- model: "gpt-5.4-mini",
100
- modelProvider: "openai",
101
- });
102
-
103
- const authOrderParams = mockCallArg(agentRuntimeMocks.resolveAuthProfileOrder) as {
104
- cfg?: unknown;
105
- provider?: unknown;
106
- };
107
- expect(authOrderParams?.cfg).toBe(config);
108
- expect(authOrderParams?.provider).toBe("openai-codex");
109
- const sharedClientParams = mockCallArg(sharedClientMocks.getSharedCodexAppServerClient) as {
110
- authProfileId?: unknown;
111
- };
112
- expect(sharedClientParams?.authProfileId).toBe("openai-codex:default");
113
- expect(requests).toHaveLength(1);
114
- expect(requests[0]?.method).toBe("thread/start");
115
- expect(requests[0]?.params.model).toBe("gpt-5.4-mini");
116
- expect(requests[0]?.params).not.toHaveProperty("modelProvider");
117
- await expect(fs.readFile(`${sessionFile}.codex-app-server.json`, "utf8")).resolves.toContain(
118
- '"authProfileId": "openai-codex:default"',
119
- );
120
- });
121
-
122
- it("preserves Codex auth and omits the public OpenAI provider for native bind threads", async () => {
123
- const sessionFile = path.join(tempDir, "session.jsonl");
124
- agentRuntimeMocks.ensureAuthProfileStore.mockReturnValue({
125
- version: 1,
126
- profiles: {
127
- work: {
128
- type: "oauth",
129
- provider: "openai-codex",
130
- access: "access-token",
131
- refresh: "refresh-token",
132
- expires: Date.now() + 60_000,
133
- },
134
- },
135
- });
136
- await fs.writeFile(
137
- `${sessionFile}.codex-app-server.json`,
138
- JSON.stringify({
139
- schemaVersion: 1,
140
- threadId: "thread-old",
141
- cwd: tempDir,
142
- authProfileId: "work",
143
- modelProvider: "openai",
144
- }),
145
- );
146
- const requests: Array<{ method: string; params: Record<string, unknown> }> = [];
147
- sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({
148
- request: vi.fn(async (method: string, requestParams: Record<string, unknown>) => {
149
- requests.push({ method, params: requestParams });
150
- return {
151
- thread: { id: "thread-new", sessionId: "session-1", cwd: tempDir },
152
- model: "gpt-5.4-mini",
153
- modelProvider: "openai",
154
- };
155
- }),
156
- });
157
-
158
- await startCodexConversationThread({
159
- sessionFile,
160
- workspaceDir: tempDir,
161
- model: "gpt-5.4-mini",
162
- modelProvider: "openai",
163
- });
164
-
165
- const sharedClientParams = mockCallArg(sharedClientMocks.getSharedCodexAppServerClient) as {
166
- authProfileId?: unknown;
167
- };
168
- expect(sharedClientParams?.authProfileId).toBe("work");
169
- expect(requests).toHaveLength(1);
170
- expect(requests[0]?.method).toBe("thread/start");
171
- expect(requests[0]?.params.model).toBe("gpt-5.4-mini");
172
- expect(requests[0]?.params).not.toHaveProperty("modelProvider");
173
- await expect(fs.readFile(`${sessionFile}.codex-app-server.json`, "utf8")).resolves.toContain(
174
- '"authProfileId": "work"',
175
- );
176
- await expect(
177
- fs.readFile(`${sessionFile}.codex-app-server.json`, "utf8"),
178
- ).resolves.not.toContain('"modelProvider": "openai"');
179
- });
180
-
181
- it("stores and uses the owning agent dir for bound app-server sessions", async () => {
182
- const sessionFile = path.join(tempDir, "session.jsonl");
183
- const agentDir = path.join(tempDir, "agents", "bot-a", "agent");
184
- sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({
185
- request: vi.fn(async () => ({
186
- thread: { id: "thread-new", sessionId: "session-1", cwd: tempDir },
187
- model: "gpt-5.4-mini",
188
- })),
189
- });
190
-
191
- const data = await startCodexConversationThread({
192
- sessionFile,
193
- workspaceDir: tempDir,
194
- agentDir,
195
- model: "gpt-5.4-mini",
196
- });
197
-
198
- const sharedClientParams = mockCallArg(sharedClientMocks.getSharedCodexAppServerClient) as {
199
- agentDir?: unknown;
200
- };
201
- expect(sharedClientParams?.agentDir).toBe(agentDir);
202
- expect(data.agentDir).toBe(agentDir);
203
- });
204
-
205
- it("clears the Codex app-server sidecar when a pending bind is denied", async () => {
206
- const sessionFile = path.join(tempDir, "session.jsonl");
207
- const sidecar = `${sessionFile}.codex-app-server.json`;
208
- await fs.writeFile(sidecar, JSON.stringify({ schemaVersion: 1, threadId: "thread-1" }));
209
-
210
- await handleCodexConversationBindingResolved({
211
- status: "denied",
212
- decision: "deny",
213
- request: {
214
- data: {
215
- kind: "codex-app-server-session",
216
- version: 1,
217
- sessionFile,
218
- workspaceDir: tempDir,
219
- },
220
- conversation: {
221
- channel: "discord",
222
- accountId: "default",
223
- conversationId: "channel:1",
224
- },
225
- },
226
- });
227
-
228
- await expect(fs.stat(sidecar)).rejects.toHaveProperty("code", "ENOENT");
229
- });
230
-
231
- it("consumes inbound bound messages when command authorization is absent", async () => {
232
- const result = await handleCodexConversationInboundClaim(
233
- {
234
- content: "run this",
235
- channel: "discord",
236
- isGroup: true,
237
- },
238
- {
239
- channelId: "discord",
240
- pluginBinding: {
241
- bindingId: "binding-1",
242
- pluginId: "codex",
243
- pluginRoot: tempDir,
244
- channel: "discord",
245
- accountId: "default",
246
- conversationId: "channel-1",
247
- boundAt: Date.now(),
248
- data: {
249
- kind: "codex-app-server-session",
250
- version: 1,
251
- sessionFile: path.join(tempDir, "session.jsonl"),
252
- workspaceDir: tempDir,
253
- },
254
- },
255
- },
256
- );
257
-
258
- expect(result).toEqual({ handled: true });
259
- });
260
-
261
- it("routes bound Codex CLI node sessions through node resume", async () => {
262
- const resumeCodexCliSessionOnNode = vi.fn(async () => ({
263
- ok: true as const,
264
- sessionId: "019e2007-1f7e-7eb1-a42b-8c01f4b9b5cd",
265
- text: "done",
266
- }));
267
-
268
- const result = await handleCodexConversationInboundClaim(
269
- {
270
- content: "continue the task",
271
- channel: "discord",
272
- isGroup: true,
273
- commandAuthorized: true,
274
- },
275
- {
276
- channelId: "discord",
277
- pluginBinding: {
278
- bindingId: "binding-1",
279
- pluginId: "codex",
280
- pluginRoot: tempDir,
281
- channel: "discord",
282
- accountId: "default",
283
- conversationId: "channel-1",
284
- boundAt: Date.now(),
285
- data: {
286
- kind: "codex-cli-node-session",
287
- version: 1,
288
- nodeId: "mb-m5",
289
- sessionId: "019e2007-1f7e-7eb1-a42b-8c01f4b9b5cd",
290
- cwd: "/repo",
291
- },
292
- },
293
- },
294
- {
295
- resumeCodexCliSessionOnNode,
296
- timeoutMs: 1234,
297
- },
298
- );
299
-
300
- expect(result).toEqual({ handled: true, reply: { text: "done" } });
301
- expect(resumeCodexCliSessionOnNode).toHaveBeenCalledWith({
302
- nodeId: "mb-m5",
303
- sessionId: "019e2007-1f7e-7eb1-a42b-8c01f4b9b5cd",
304
- prompt: "continue the task",
305
- cwd: "/repo",
306
- timeoutMs: 1234,
307
- });
308
- });
309
-
310
- it("recreates a missing bound thread and preserves auth plus turn overrides", async () => {
311
- const sessionFile = path.join(tempDir, "session.jsonl");
312
- agentRuntimeMocks.ensureAuthProfileStore.mockReturnValue({
313
- version: 1,
314
- profiles: {
315
- work: {
316
- type: "oauth",
317
- provider: "openai-codex",
318
- access: "access-token",
319
- },
320
- },
321
- });
322
- await fs.writeFile(
323
- `${sessionFile}.codex-app-server.json`,
324
- JSON.stringify({
325
- schemaVersion: 1,
326
- threadId: "thread-old",
327
- cwd: tempDir,
328
- authProfileId: "work",
329
- model: "gpt-5.4-mini",
330
- modelProvider: "openai",
331
- approvalPolicy: "on-request",
332
- sandbox: "workspace-write",
333
- serviceTier: "fast",
334
- }),
335
- );
336
- const requests: Array<{ method: string; params: Record<string, unknown> }> = [];
337
- const notificationHandlers: Array<(notification: Record<string, unknown>) => void> = [];
338
- sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({
339
- request: vi.fn(async (method: string, requestParams: Record<string, unknown>) => {
340
- requests.push({ method, params: requestParams });
341
- if (method === "turn/start" && requestParams.threadId === "thread-old") {
342
- throw new Error("thread not found: thread-old");
343
- }
344
- if (method === "thread/start") {
345
- return {
346
- thread: { id: "thread-new", sessionId: "session-1", cwd: tempDir },
347
- model: "gpt-5.4-mini",
348
- };
349
- }
350
- if (method === "turn/start" && requestParams.threadId === "thread-new") {
351
- setImmediate(() => {
352
- for (const handler of notificationHandlers) {
353
- handler({
354
- method: "turn/completed",
355
- params: {
356
- threadId: "thread-new",
357
- turn: {
358
- id: "turn-new",
359
- status: "completed",
360
- items: [
361
- {
362
- id: "assistant-1",
363
- type: "agentMessage",
364
- text: "Recovered",
365
- },
366
- ],
367
- },
368
- },
369
- });
370
- }
371
- });
372
- return { turn: { id: "turn-new" } };
373
- }
374
- throw new Error(`unexpected method: ${method}`);
375
- }),
376
- addNotificationHandler: vi.fn((handler) => {
377
- notificationHandlers.push(handler);
378
- return () => undefined;
379
- }),
380
- addRequestHandler: vi.fn(() => () => undefined),
381
- });
382
-
383
- const result = await handleCodexConversationInboundClaim(
384
- {
385
- content: "hi again",
386
- bodyForAgent: "hi again",
387
- channel: "telegram",
388
- isGroup: false,
389
- commandAuthorized: true,
390
- },
391
- {
392
- channelId: "telegram",
393
- pluginBinding: {
394
- bindingId: "binding-1",
395
- pluginId: "codex",
396
- pluginRoot: tempDir,
397
- channel: "telegram",
398
- accountId: "default",
399
- conversationId: "5185575566",
400
- boundAt: Date.now(),
401
- data: {
402
- kind: "codex-app-server-session",
403
- version: 1,
404
- sessionFile,
405
- workspaceDir: tempDir,
406
- },
407
- },
408
- },
409
- { timeoutMs: 500 },
410
- );
411
-
412
- expect(result).toEqual({ handled: true, reply: { text: "Recovered" } });
413
- expect(requests.map((request) => request.method)).toEqual([
414
- "turn/start",
415
- "thread/start",
416
- "turn/start",
417
- ]);
418
- const sharedClientParams = mockCallArg(sharedClientMocks.getSharedCodexAppServerClient) as {
419
- authProfileId?: unknown;
420
- };
421
- expect(sharedClientParams?.authProfileId).toBe("work");
422
- expect(requests[1]?.params.model).toBe("gpt-5.4-mini");
423
- expect(requests[1]?.params.approvalPolicy).toBe("on-request");
424
- expect(requests[1]?.params.sandbox).toBe("workspace-write");
425
- expect(requests[1]?.params.serviceTier).toBe("priority");
426
- expect(requests[1]?.params).not.toHaveProperty("modelProvider");
427
- expect(requests[2]?.params.threadId).toBe("thread-new");
428
- expect(requests[2]?.params.approvalPolicy).toBe("on-request");
429
- expect(requests[2]?.params.serviceTier).toBe("priority");
430
- const savedBinding = JSON.parse(
431
- await fs.readFile(`${sessionFile}.codex-app-server.json`, "utf8"),
432
- );
433
- expect(savedBinding.threadId).toBe("thread-new");
434
- expect(savedBinding.authProfileId).toBe("work");
435
- expect(savedBinding.approvalPolicy).toBe("on-request");
436
- expect(savedBinding.sandbox).toBe("workspace-write");
437
- expect(savedBinding.serviceTier).toBe("priority");
438
- expect(savedBinding).not.toHaveProperty("modelProvider");
439
- });
440
-
441
- it("returns a clean failure reply when app-server turn start rejects", async () => {
442
- const sessionFile = path.join(tempDir, "session.jsonl");
443
- const agentDir = path.join(tempDir, "agents", "bot-b", "agent");
444
- await fs.writeFile(
445
- `${sessionFile}.codex-app-server.json`,
446
- JSON.stringify({
447
- schemaVersion: 1,
448
- threadId: "thread-1",
449
- cwd: tempDir,
450
- authProfileId: "openai-codex:work",
451
- }),
452
- );
453
- const unhandledRejections: unknown[] = [];
454
- const onUnhandledRejection = (reason: unknown) => {
455
- unhandledRejections.push(reason);
456
- };
457
- process.on("unhandledRejection", onUnhandledRejection);
458
- sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({
459
- request: vi.fn(async (method: string) => {
460
- if (method === "turn/start") {
461
- throw new Error(
462
- "unexpected status 401 Unauthorized: Missing bearer <@U123> [trusted](https://evil) @here",
463
- );
464
- }
465
- throw new Error(`unexpected method: ${method}`);
466
- }),
467
- addNotificationHandler: vi.fn(() => () => undefined),
468
- addRequestHandler: vi.fn(() => () => undefined),
469
- });
470
-
471
- try {
472
- const result = await handleCodexConversationInboundClaim(
473
- {
474
- content: "hi",
475
- bodyForAgent: "hi",
476
- channel: "telegram",
477
- isGroup: false,
478
- commandAuthorized: true,
479
- },
480
- {
481
- channelId: "telegram",
482
- pluginBinding: {
483
- bindingId: "binding-1",
484
- pluginId: "codex",
485
- pluginRoot: tempDir,
486
- channel: "telegram",
487
- accountId: "default",
488
- conversationId: "5185575566",
489
- boundAt: Date.now(),
490
- data: {
491
- kind: "codex-app-server-session",
492
- version: 1,
493
- sessionFile,
494
- workspaceDir: tempDir,
495
- agentDir,
496
- },
497
- },
498
- },
499
- { timeoutMs: 50 },
500
- );
501
- await new Promise<void>((resolve) => setImmediate(resolve));
502
-
503
- expect(result).toEqual({
504
- handled: true,
505
- reply: {
506
- text: "Codex app-server turn failed: unexpected status 401 Unauthorized: Missing bearer &lt;\uff20U123&gt; \uff3btrusted\uff3d\uff08https://evil\uff09 \uff20here",
507
- },
508
- });
509
- const replyText = result?.reply?.text ?? "";
510
- expect(replyText).not.toContain("<@U123>");
511
- expect(replyText).not.toContain("[trusted](https://evil)");
512
- expect(replyText).not.toContain("@here");
513
- expect(unhandledRejections).toStrictEqual([]);
514
- } finally {
515
- process.off("unhandledRejection", onUnhandledRejection);
516
- }
517
- });
518
-
519
- it("falls back to content when the channel body for agent is blank", async () => {
520
- const sessionFile = path.join(tempDir, "session.jsonl");
521
- const agentDir = path.join(tempDir, "agents", "bot-b", "agent");
522
- await fs.writeFile(
523
- `${sessionFile}.codex-app-server.json`,
524
- JSON.stringify({
525
- schemaVersion: 1,
526
- threadId: "thread-1",
527
- cwd: tempDir,
528
- }),
529
- );
530
- let notificationHandler: ((notification: unknown) => void) | undefined;
531
- const turnStartParams: Record<string, unknown>[] = [];
532
- sharedClientMocks.getSharedCodexAppServerClient.mockResolvedValue({
533
- request: vi.fn(async (method: string, requestParams: Record<string, unknown>) => {
534
- if (method === "turn/start") {
535
- turnStartParams.push(requestParams);
536
- setImmediate(() =>
537
- notificationHandler?.({
538
- method: "turn/completed",
539
- params: {
540
- threadId: "thread-1",
541
- turn: {
542
- id: "turn-1",
543
- status: "completed",
544
- items: [{ type: "agentMessage", id: "item-1", text: "done" }],
545
- },
546
- },
547
- }),
548
- );
549
- return { turn: { id: "turn-1" } };
550
- }
551
- throw new Error(`unexpected method: ${method}`);
552
- }),
553
- addNotificationHandler: vi.fn((handler: (notification: unknown) => void) => {
554
- notificationHandler = handler;
555
- return () => undefined;
556
- }),
557
- addRequestHandler: vi.fn(() => () => undefined),
558
- });
559
-
560
- const result = await handleCodexConversationInboundClaim(
561
- {
562
- content: "use the fallback prompt",
563
- bodyForAgent: "",
564
- channel: "telegram",
565
- isGroup: false,
566
- commandAuthorized: true,
567
- },
568
- {
569
- channelId: "telegram",
570
- pluginBinding: {
571
- bindingId: "binding-1",
572
- pluginId: "codex",
573
- pluginRoot: tempDir,
574
- channel: "telegram",
575
- accountId: "default",
576
- conversationId: "5185575566",
577
- boundAt: Date.now(),
578
- data: {
579
- kind: "codex-app-server-session",
580
- version: 1,
581
- sessionFile,
582
- workspaceDir: tempDir,
583
- agentDir,
584
- },
585
- },
586
- },
587
- { timeoutMs: 50 },
588
- );
589
-
590
- expect(result).toEqual({ handled: true, reply: { text: "done" } });
591
- const sharedClientParams = mockCallArg(sharedClientMocks.getSharedCodexAppServerClient) as {
592
- agentDir?: unknown;
593
- };
594
- expect(sharedClientParams?.agentDir).toBe(agentDir);
595
- expect(turnStartParams[0]?.input).toEqual([
596
- { type: "text", text: "use the fallback prompt", text_elements: [] },
597
- ]);
598
- });
599
- });