@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,521 +0,0 @@
1
- import {
2
- type JsonSchemaObject,
3
- validateJsonSchemaValue,
4
- } from "klaw/plugin-sdk/json-schema-runtime";
5
- import {
6
- type ImagesDescriptionRequest,
7
- type ImagesDescriptionResult,
8
- type MediaUnderstandingProvider,
9
- type StructuredExtractionRequest,
10
- type StructuredExtractionResult,
11
- } from "klaw/plugin-sdk/media-understanding";
12
- import { CODEX_PROVIDER_ID, FALLBACK_CODEX_MODELS } from "./provider-catalog.js";
13
- import { type CodexAppServerClientFactory } from "./src/app-server/client-factory.js";
14
- import type { CodexAppServerClient } from "./src/app-server/client.js";
15
- import { resolveCodexAppServerRuntimeOptions } from "./src/app-server/config.js";
16
- import { readModelListResult } from "./src/app-server/models.js";
17
- import {
18
- assertCodexThreadStartResponse,
19
- assertCodexTurnStartResponse,
20
- readCodexErrorNotification,
21
- readCodexTurnCompletedNotification,
22
- } from "./src/app-server/protocol-validators.js";
23
- import {
24
- isJsonObject,
25
- type CodexServerNotification,
26
- type CodexThreadItem,
27
- type CodexThreadStartParams,
28
- type CodexTurn,
29
- type CodexTurnStartParams,
30
- type CodexUserInput,
31
- type JsonObject,
32
- type JsonValue,
33
- } from "./src/app-server/protocol.js";
34
-
35
- const DEFAULT_CODEX_IMAGE_MODEL =
36
- FALLBACK_CODEX_MODELS.find((model) => model.inputModalities.includes("image"))?.id ??
37
- FALLBACK_CODEX_MODELS[0]?.id;
38
- const DEFAULT_CODEX_IMAGE_PROMPT = "Describe the image.";
39
-
40
- export type CodexMediaUnderstandingProviderOptions = {
41
- pluginConfig?: unknown;
42
- clientFactory?: CodexAppServerClientFactory;
43
- };
44
-
45
- export function buildCodexMediaUnderstandingProvider(
46
- options: CodexMediaUnderstandingProviderOptions = {},
47
- ): MediaUnderstandingProvider {
48
- return {
49
- id: CODEX_PROVIDER_ID,
50
- capabilities: ["image"],
51
- ...(DEFAULT_CODEX_IMAGE_MODEL ? { defaultModels: { image: DEFAULT_CODEX_IMAGE_MODEL } } : {}),
52
- describeImage: async (req) =>
53
- describeCodexImages(
54
- {
55
- images: [
56
- {
57
- buffer: req.buffer,
58
- fileName: req.fileName,
59
- mime: req.mime,
60
- },
61
- ],
62
- provider: req.provider,
63
- model: req.model,
64
- prompt: req.prompt,
65
- maxTokens: req.maxTokens,
66
- timeoutMs: req.timeoutMs,
67
- profile: req.profile,
68
- preferredProfile: req.preferredProfile,
69
- authStore: req.authStore,
70
- agentDir: req.agentDir,
71
- cfg: req.cfg,
72
- },
73
- options,
74
- ),
75
- describeImages: async (req) => describeCodexImages(req, options),
76
- extractStructured: async (req) => extractCodexStructured(req, options),
77
- };
78
- }
79
-
80
- async function describeCodexImages(
81
- req: ImagesDescriptionRequest,
82
- options: CodexMediaUnderstandingProviderOptions,
83
- ): Promise<ImagesDescriptionResult> {
84
- const model = req.model.trim();
85
- if (!model) {
86
- throw new Error("Codex image understanding requires model id.");
87
- }
88
-
89
- const text = await runBoundedCodexVisionTurn({
90
- model,
91
- profile: req.profile,
92
- timeoutMs: req.timeoutMs,
93
- agentDir: req.agentDir,
94
- options,
95
- taskLabel: "image understanding",
96
- developerInstructions:
97
- "You are Klaw's bounded image-understanding worker. Describe only the provided image content. Do not call tools, edit files, or ask follow-up questions.",
98
- input: [
99
- { type: "text", text: buildCodexImagePrompt(req), text_elements: [] },
100
- ...req.images.map((image) => ({
101
- type: "image" as const,
102
- url: `data:${image.mime ?? "image/png"};base64,${image.buffer.toString("base64")}`,
103
- })),
104
- ],
105
- requiredModalities: ["text", "image"],
106
- });
107
- return { text, model };
108
- }
109
-
110
- type BoundedCodexVisionTurnParams = {
111
- model: string;
112
- profile?: string;
113
- timeoutMs: number;
114
- agentDir?: string;
115
- options: CodexMediaUnderstandingProviderOptions;
116
- taskLabel: string;
117
- developerInstructions: string;
118
- input: CodexUserInput[];
119
- requiredModalities: string[];
120
- };
121
-
122
- async function runBoundedCodexVisionTurn(params: BoundedCodexVisionTurnParams): Promise<string> {
123
- const appServer = resolveCodexAppServerRuntimeOptions({
124
- pluginConfig: params.options.pluginConfig,
125
- });
126
- const timeoutMs = Math.max(100, params.timeoutMs);
127
- const ownsClient = !params.options.clientFactory;
128
- const client = params.options.clientFactory
129
- ? await params.options.clientFactory(appServer.start, params.profile)
130
- : await import("./src/app-server/shared-client.js").then(
131
- ({ createIsolatedCodexAppServerClient }) =>
132
- createIsolatedCodexAppServerClient({
133
- startOptions: appServer.start,
134
- timeoutMs,
135
- authProfileId: params.profile,
136
- }),
137
- );
138
- const abortController = new AbortController();
139
- const timeout = setTimeout(() => abortController.abort("timeout"), timeoutMs);
140
- timeout.unref?.();
141
-
142
- try {
143
- await assertCodexModelSupportsInput({
144
- client,
145
- model: params.model,
146
- requiredModalities: params.requiredModalities,
147
- timeoutMs,
148
- signal: abortController.signal,
149
- });
150
- const thread = assertCodexThreadStartResponse(
151
- await client.request<unknown>(
152
- "thread/start",
153
- {
154
- model: params.model,
155
- modelProvider: "openai",
156
- cwd: params.agentDir || process.cwd(),
157
- approvalPolicy: "on-request",
158
- sandbox: "read-only",
159
- serviceName: "Klaw",
160
- developerInstructions: params.developerInstructions,
161
- dynamicTools: [],
162
- experimentalRawEvents: true,
163
- persistExtendedHistory: false,
164
- ephemeral: true,
165
- } satisfies CodexThreadStartParams,
166
- { timeoutMs, signal: abortController.signal },
167
- ),
168
- );
169
- const collector = createCodexTurnCollector(thread.thread.id, params.taskLabel);
170
- const cleanup = client.addNotificationHandler(collector.handleNotification);
171
- const requestCleanup = client.addRequestHandler(denyCodexImageApprovalRequest);
172
- try {
173
- const turn = assertCodexTurnStartResponse(
174
- await client.request<unknown>(
175
- "turn/start",
176
- {
177
- threadId: thread.thread.id,
178
- input: params.input,
179
- cwd: params.agentDir || process.cwd(),
180
- approvalPolicy: "on-request",
181
- model: params.model,
182
- effort: "low",
183
- } satisfies CodexTurnStartParams,
184
- { timeoutMs, signal: abortController.signal },
185
- ),
186
- );
187
- const text = await collector.collect(turn.turn, {
188
- timeoutMs,
189
- signal: abortController.signal,
190
- });
191
- return text;
192
- } finally {
193
- requestCleanup();
194
- cleanup();
195
- }
196
- } finally {
197
- clearTimeout(timeout);
198
- if (ownsClient) {
199
- client.close();
200
- }
201
- }
202
- }
203
-
204
- async function extractCodexStructured(
205
- req: StructuredExtractionRequest,
206
- options: CodexMediaUnderstandingProviderOptions,
207
- ): Promise<StructuredExtractionResult> {
208
- const model = req.model.trim();
209
- if (!model) {
210
- throw new Error("Codex structured extraction requires model id.");
211
- }
212
- const instructions = req.instructions.trim();
213
- if (!instructions) {
214
- throw new Error("Codex structured extraction requires instructions.");
215
- }
216
- if (req.input.length === 0) {
217
- throw new Error("Codex structured extraction requires at least one input.");
218
- }
219
- if (!req.input.some((entry) => entry.type === "image")) {
220
- throw new Error("Codex structured extraction requires at least one image input.");
221
- }
222
-
223
- const text = await runBoundedCodexVisionTurn({
224
- model,
225
- profile: req.profile,
226
- timeoutMs: req.timeoutMs,
227
- agentDir: req.agentDir,
228
- options,
229
- taskLabel: "structured extraction",
230
- developerInstructions:
231
- "You are Klaw's bounded structured-extraction worker. Return only the requested extraction. Do not call tools, edit files, ask follow-up questions, or include secrets.",
232
- input: buildCodexStructuredInput(req),
233
- requiredModalities: requiredStructuredModalities(),
234
- });
235
- return normalizeStructuredExtractionResult({ text, model, provider: req.provider, req });
236
- }
237
-
238
- function denyCodexImageApprovalRequest(request: { method: string }): JsonValue | undefined {
239
- if (
240
- request.method === "item/commandExecution/requestApproval" ||
241
- request.method === "item/fileChange/requestApproval"
242
- ) {
243
- return {
244
- decision: "decline",
245
- reason: "Klaw Codex image understanding does not grant tool or file approvals.",
246
- };
247
- }
248
- if (request.method === "item/permissions/requestApproval") {
249
- return { permissions: {}, scope: "turn" };
250
- }
251
- if (request.method.includes("requestApproval")) {
252
- return {
253
- decision: "decline",
254
- reason: "Klaw Codex image understanding does not grant native approvals.",
255
- };
256
- }
257
- if (request.method === "mcpServer/elicitation/request") {
258
- return { action: "decline" };
259
- }
260
- return undefined;
261
- }
262
-
263
- async function assertCodexModelSupportsInput(params: {
264
- client: CodexAppServerClient;
265
- model: string;
266
- requiredModalities: string[];
267
- timeoutMs: number;
268
- signal: AbortSignal;
269
- }): Promise<void> {
270
- const result = await params.client.request<unknown>(
271
- "model/list",
272
- { limit: 100, cursor: null, includeHidden: false },
273
- { timeoutMs: Math.min(params.timeoutMs, 5_000), signal: params.signal },
274
- );
275
- const listed = readModelListResult(result).models;
276
- const match = listed.find((entry) => entry.model === params.model || entry.id === params.model);
277
- if (!match) {
278
- throw new Error(`Codex app-server model not found: ${params.model}`);
279
- }
280
- if (params.requiredModalities.includes("image") && !match.inputModalities.includes("image")) {
281
- throw new Error(`Codex app-server model does not support images: ${params.model}`);
282
- }
283
- if (params.requiredModalities.includes("text") && !match.inputModalities.includes("text")) {
284
- throw new Error(`Codex app-server model does not support text: ${params.model}`);
285
- }
286
- }
287
-
288
- function buildCodexImagePrompt(req: ImagesDescriptionRequest): string {
289
- const prompt = req.prompt?.trim() || DEFAULT_CODEX_IMAGE_PROMPT;
290
- if (req.images.length <= 1) {
291
- return prompt;
292
- }
293
- return `${prompt}\n\nAnalyze all ${req.images.length} images together.`;
294
- }
295
-
296
- function requiredStructuredModalities(): string[] {
297
- return ["text", "image"];
298
- }
299
-
300
- function buildCodexStructuredInput(req: StructuredExtractionRequest): CodexUserInput[] {
301
- return [
302
- { type: "text", text: buildStructuredExtractionPrompt(req), text_elements: [] },
303
- ...req.input.map((entry) => {
304
- if (entry.type === "text") {
305
- return { type: "text" as const, text: entry.text, text_elements: [] };
306
- }
307
- return {
308
- type: "image" as const,
309
- url: `data:${entry.mime ?? "image/png"};base64,${entry.buffer.toString("base64")}`,
310
- };
311
- }),
312
- ];
313
- }
314
-
315
- function buildStructuredExtractionPrompt(req: StructuredExtractionRequest): string {
316
- return [
317
- req.instructions.trim(),
318
- req.schemaName ? `Schema name: ${req.schemaName}` : undefined,
319
- req.jsonSchema ? `JSON schema:\n${JSON.stringify(req.jsonSchema)}` : undefined,
320
- req.jsonMode === false
321
- ? "Return the extraction as concise text."
322
- : "Return valid JSON only. Do not wrap the JSON in Markdown fences.",
323
- ]
324
- .filter((part): part is string => Boolean(part))
325
- .join("\n\n");
326
- }
327
-
328
- function isJsonSchemaObject(value: unknown): value is JsonSchemaObject {
329
- return typeof value === "object" && value !== null && !Array.isArray(value);
330
- }
331
-
332
- function normalizeStructuredExtractionResult(params: {
333
- text: string;
334
- model: string;
335
- provider: string;
336
- req: StructuredExtractionRequest;
337
- }): StructuredExtractionResult {
338
- const result: StructuredExtractionResult = {
339
- text: params.text,
340
- model: params.model,
341
- provider: params.provider,
342
- contentType: params.req.jsonMode === false ? "text" : "json",
343
- };
344
- if (params.req.jsonMode !== false) {
345
- try {
346
- result.parsed = JSON.parse(params.text);
347
- } catch {
348
- throw new Error("Codex structured extraction returned invalid JSON.");
349
- }
350
- if (isJsonSchemaObject(params.req.jsonSchema)) {
351
- const validation = validateJsonSchemaValue({
352
- schema: params.req.jsonSchema,
353
- cacheKey: "codex.media-understanding.extractStructured",
354
- value: result.parsed,
355
- cache: false,
356
- });
357
- if (!validation.ok) {
358
- const message = validation.errors.map((error) => error.text).join("; ") || "invalid";
359
- throw new Error(`Codex structured extraction JSON did not match schema: ${message}`);
360
- }
361
- result.parsed = validation.value;
362
- }
363
- }
364
- return result;
365
- }
366
-
367
- function createCodexTurnCollector(threadId: string, taskLabel: string) {
368
- let turnId: string | undefined;
369
- let completedTurn: CodexTurn | undefined;
370
- let promptError: string | undefined;
371
- const pending: CodexServerNotification[] = [];
372
- const assistantTextByItem = new Map<string, string>();
373
- const assistantItemOrder: string[] = [];
374
- let resolveCompletion: (() => void) | undefined;
375
- const completion = new Promise<void>((resolve) => {
376
- resolveCompletion = resolve;
377
- });
378
-
379
- const rememberAssistantText = (itemId: string, text: string) => {
380
- if (!text) {
381
- return;
382
- }
383
- if (!assistantTextByItem.has(itemId)) {
384
- assistantItemOrder.push(itemId);
385
- }
386
- assistantTextByItem.set(itemId, text);
387
- };
388
-
389
- const handleNotification = (notification: CodexServerNotification): void => {
390
- const params = isJsonObject(notification.params) ? notification.params : undefined;
391
- if (!params || readString(params, "threadId") !== threadId) {
392
- return;
393
- }
394
- if (!turnId) {
395
- pending.push(notification);
396
- return;
397
- }
398
- const notificationTurnId = readNotificationTurnId(params);
399
- if (notificationTurnId !== turnId) {
400
- return;
401
- }
402
- if (notification.method === "item/agentMessage/delta") {
403
- const itemId = readString(params, "itemId") ?? readString(params, "id") ?? "assistant";
404
- const delta = readString(params, "delta") ?? "";
405
- rememberAssistantText(itemId, `${assistantTextByItem.get(itemId) ?? ""}${delta}`);
406
- return;
407
- }
408
- if (notification.method === "turn/completed") {
409
- completedTurn =
410
- readCodexTurnCompletedNotification(notification.params)?.turn ?? completedTurn;
411
- resolveCompletion?.();
412
- return;
413
- }
414
- if (notification.method === "error") {
415
- promptError =
416
- readCodexErrorNotification(notification.params)?.error.message ??
417
- `codex app-server ${taskLabel} turn failed`;
418
- resolveCompletion?.();
419
- }
420
- };
421
-
422
- return {
423
- handleNotification,
424
- async collect(
425
- startedTurn: CodexTurn,
426
- options: { timeoutMs: number; signal: AbortSignal },
427
- ): Promise<string> {
428
- turnId = startedTurn.id;
429
- if (isTerminalTurn(startedTurn)) {
430
- completedTurn = startedTurn;
431
- }
432
- for (const notification of pending.splice(0)) {
433
- handleNotification(notification);
434
- }
435
- if (!completedTurn && !promptError) {
436
- await waitForTurnCompletion({
437
- completion,
438
- timeoutMs: options.timeoutMs,
439
- signal: options.signal,
440
- taskLabel,
441
- });
442
- }
443
- if (promptError) {
444
- throw new Error(promptError);
445
- }
446
- if (completedTurn?.status === "failed") {
447
- throw new Error(
448
- completedTurn.error?.message ?? `codex app-server ${taskLabel} turn failed`,
449
- );
450
- }
451
- const itemText = collectAssistantTextFromItems(completedTurn?.items);
452
- const deltaText = assistantItemOrder
453
- .map((itemId) => assistantTextByItem.get(itemId)?.trim())
454
- .filter((text): text is string => Boolean(text))
455
- .join("\n\n")
456
- .trim();
457
- const text = (itemText || deltaText).trim();
458
- if (!text) {
459
- throw new Error(`Codex app-server ${taskLabel} turn returned no text.`);
460
- }
461
- return text;
462
- },
463
- };
464
- }
465
-
466
- async function waitForTurnCompletion(params: {
467
- completion: Promise<void>;
468
- timeoutMs: number;
469
- signal: AbortSignal;
470
- taskLabel: string;
471
- }): Promise<void> {
472
- let timeout: ReturnType<typeof setTimeout> | undefined;
473
- let cleanupAbort: (() => void) | undefined;
474
- try {
475
- await Promise.race([
476
- params.completion,
477
- new Promise<never>((_, reject) => {
478
- timeout = setTimeout(
479
- () => reject(new Error(`codex app-server ${params.taskLabel} turn timed out`)),
480
- params.timeoutMs,
481
- );
482
- timeout.unref?.();
483
- const abortListener = () =>
484
- reject(new Error(`codex app-server ${params.taskLabel} turn aborted`));
485
- params.signal.addEventListener("abort", abortListener, { once: true });
486
- cleanupAbort = () => params.signal.removeEventListener("abort", abortListener);
487
- }),
488
- ]);
489
- } finally {
490
- if (timeout) {
491
- clearTimeout(timeout);
492
- }
493
- cleanupAbort?.();
494
- }
495
- }
496
-
497
- function collectAssistantTextFromItems(items: CodexThreadItem[] | undefined): string {
498
- return (items ?? [])
499
- .filter((item) => item.type === "agentMessage")
500
- .map((item) => item.text.trim())
501
- .filter(Boolean)
502
- .join("\n\n")
503
- .trim();
504
- }
505
-
506
- function readNotificationTurnId(record: JsonObject): string | undefined {
507
- const direct = readString(record, "turnId");
508
- if (direct) {
509
- return direct;
510
- }
511
- return isJsonObject(record.turn) ? readString(record.turn, "id") : undefined;
512
- }
513
-
514
- function readString(record: JsonObject, key: string): string | undefined {
515
- const value = record[key];
516
- return typeof value === "string" ? value : undefined;
517
- }
518
-
519
- function isTerminalTurn(turn: CodexTurn): boolean {
520
- return turn.status === "completed" || turn.status === "interrupted" || turn.status === "failed";
521
- }
@@ -1,48 +0,0 @@
1
- import {
2
- codexPromptOverlayContext,
3
- GPT5_CONTRACT_MODEL_ID,
4
- NON_GPT5_CONTRACT_MODEL_ID,
5
- sharedGpt5PersonalityConfig,
6
- } from "klaw/plugin-sdk/agent-runtime-test-contracts";
7
- import { describe, expect, it } from "vitest";
8
- import { buildCodexProvider } from "./provider.js";
9
-
10
- describe("Codex prompt overlay runtime contract", () => {
11
- it("adds the shared GPT-5 behavior contract to Codex GPT-5 provider runs", () => {
12
- const provider = buildCodexProvider();
13
- const contribution = provider.resolveSystemPromptContribution?.(
14
- codexPromptOverlayContext({ modelId: GPT5_CONTRACT_MODEL_ID }),
15
- );
16
-
17
- expect(contribution?.stablePrefix).toContain("<persona_latch>");
18
- expect(contribution?.sectionOverrides?.interaction_style).toContain(
19
- "Live chat tone: short, natural, human.",
20
- );
21
- expect(contribution?.sectionOverrides?.interaction_style).not.toContain(
22
- "Use heartbeats to create useful proactive progress",
23
- );
24
- });
25
-
26
- it("respects shared GPT-5 prompt overlay config for Codex runs", () => {
27
- const provider = buildCodexProvider();
28
- const contribution = provider.resolveSystemPromptContribution?.(
29
- codexPromptOverlayContext({
30
- modelId: GPT5_CONTRACT_MODEL_ID,
31
- config: sharedGpt5PersonalityConfig("off"),
32
- }),
33
- );
34
-
35
- expect(contribution?.stablePrefix).toContain("<persona_latch>");
36
- expect(contribution?.sectionOverrides).toStrictEqual({});
37
- });
38
-
39
- it("does not add the shared GPT-5 overlay to non-GPT-5 Codex provider runs", () => {
40
- const provider = buildCodexProvider();
41
-
42
- expect(
43
- provider.resolveSystemPromptContribution?.(
44
- codexPromptOverlayContext({ modelId: NON_GPT5_CONTRACT_MODEL_ID }),
45
- ),
46
- ).toBeUndefined();
47
- });
48
- });
package/prompt-overlay.ts DELETED
@@ -1,21 +0,0 @@
1
- import {
2
- GPT5_BEHAVIOR_CONTRACT,
3
- GPT5_HEARTBEAT_PROMPT_OVERLAY,
4
- renderGpt5PromptOverlay,
5
- resolveGpt5SystemPromptContribution,
6
- } from "klaw/plugin-sdk/provider-model-shared";
7
-
8
- export const CODEX_GPT5_BEHAVIOR_CONTRACT = GPT5_BEHAVIOR_CONTRACT;
9
- export const CODEX_GPT5_HEARTBEAT_PROMPT_OVERLAY = GPT5_HEARTBEAT_PROMPT_OVERLAY;
10
-
11
- export function resolveCodexSystemPromptContribution(
12
- params: Parameters<typeof resolveGpt5SystemPromptContribution>[0],
13
- ) {
14
- return resolveGpt5SystemPromptContribution(params);
15
- }
16
-
17
- export function renderCodexPromptOverlay(
18
- params: Parameters<typeof renderGpt5PromptOverlay>[0],
19
- ): string | undefined {
20
- return renderGpt5PromptOverlay(params);
21
- }
@@ -1,83 +0,0 @@
1
- import type {
2
- ModelDefinitionConfig,
3
- ModelProviderConfig,
4
- } from "klaw/plugin-sdk/provider-model-shared";
5
- import type { CodexAppServerModel } from "./src/app-server/models.js";
6
-
7
- export const CODEX_PROVIDER_ID = "codex";
8
- export const CODEX_BASE_URL = "https://chatgpt.com/backend-api";
9
- export const CODEX_APP_SERVER_AUTH_MARKER = "codex-app-server";
10
-
11
- const DEFAULT_CONTEXT_WINDOW = 272_000;
12
- const DEFAULT_MAX_TOKENS = 128_000;
13
-
14
- export const FALLBACK_CODEX_MODELS = [
15
- {
16
- id: "gpt-5.5",
17
- model: "gpt-5.5",
18
- displayName: "gpt-5.5",
19
- description: "Latest frontier agentic coding model.",
20
- isDefault: true,
21
- inputModalities: ["text", "image"],
22
- supportedReasoningEfforts: ["low", "medium", "high", "xhigh"],
23
- },
24
- {
25
- id: "gpt-5.4-mini",
26
- model: "gpt-5.4-mini",
27
- displayName: "GPT-5.4-Mini",
28
- description: "Smaller frontier agentic coding model.",
29
- inputModalities: ["text", "image"],
30
- supportedReasoningEfforts: ["low", "medium", "high", "xhigh"],
31
- },
32
- {
33
- id: "gpt-5.2",
34
- model: "gpt-5.2",
35
- displayName: "gpt-5.2",
36
- inputModalities: ["text", "image"],
37
- supportedReasoningEfforts: ["low", "medium", "high", "xhigh"],
38
- },
39
- ] satisfies CodexAppServerModel[];
40
-
41
- export function buildCodexModelDefinition(model: {
42
- id: string;
43
- model: string;
44
- displayName?: string;
45
- inputModalities: string[];
46
- supportedReasoningEfforts: string[];
47
- }): ModelDefinitionConfig {
48
- const id = model.id.trim() || model.model.trim();
49
- return {
50
- id,
51
- name: model.displayName?.trim() || id,
52
- api: "openai-codex-responses",
53
- reasoning: model.supportedReasoningEfforts.length > 0 || shouldDefaultToReasoningModel(id),
54
- input: model.inputModalities.includes("image") ? ["text", "image"] : ["text"],
55
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
56
- contextWindow: DEFAULT_CONTEXT_WINDOW,
57
- maxTokens: DEFAULT_MAX_TOKENS,
58
- compat: {
59
- supportsReasoningEffort: model.supportedReasoningEfforts.length > 0,
60
- supportsUsageInStreaming: true,
61
- },
62
- };
63
- }
64
-
65
- export function buildCodexProviderConfig(models: CodexAppServerModel[]): ModelProviderConfig {
66
- return {
67
- baseUrl: CODEX_BASE_URL,
68
- apiKey: CODEX_APP_SERVER_AUTH_MARKER,
69
- auth: "token",
70
- api: "openai-codex-responses",
71
- models: models.map(buildCodexModelDefinition),
72
- };
73
- }
74
-
75
- function shouldDefaultToReasoningModel(modelId: string): boolean {
76
- const lower = modelId.toLowerCase();
77
- return (
78
- lower.startsWith("gpt-5") ||
79
- lower.startsWith("o1") ||
80
- lower.startsWith("o3") ||
81
- lower.startsWith("o4")
82
- );
83
- }