@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,335 @@
1
+ import { CODEX_PROVIDER_ID, FALLBACK_CODEX_MODELS } from "./provider-catalog.js";
2
+ import { c as resolveCodexAppServerRuntimeOptions } from "./config-CezENx_E.js";
3
+ import { i as assertCodexTurnStartResponse, l as readCodexTurnCompletedNotification, o as readCodexErrorNotification, r as assertCodexThreadStartResponse } from "./protocol-validators-BGBspNmF.js";
4
+ import { i as readModelListResult } from "./models-B9DhrIwD.js";
5
+ import { t as isJsonObject } from "./protocol-C9UWI98H.js";
6
+ import { validateJsonSchemaValue } from "klaw/plugin-sdk/json-schema-runtime";
7
+ //#region extensions/codex/media-understanding-provider.ts
8
+ const DEFAULT_CODEX_IMAGE_MODEL = FALLBACK_CODEX_MODELS.find((model) => model.inputModalities.includes("image"))?.id ?? FALLBACK_CODEX_MODELS[0]?.id;
9
+ const DEFAULT_CODEX_IMAGE_PROMPT = "Describe the image.";
10
+ function buildCodexMediaUnderstandingProvider(options = {}) {
11
+ return {
12
+ id: CODEX_PROVIDER_ID,
13
+ capabilities: ["image"],
14
+ ...DEFAULT_CODEX_IMAGE_MODEL ? { defaultModels: { image: DEFAULT_CODEX_IMAGE_MODEL } } : {},
15
+ describeImage: async (req) => describeCodexImages({
16
+ images: [{
17
+ buffer: req.buffer,
18
+ fileName: req.fileName,
19
+ mime: req.mime
20
+ }],
21
+ provider: req.provider,
22
+ model: req.model,
23
+ prompt: req.prompt,
24
+ maxTokens: req.maxTokens,
25
+ timeoutMs: req.timeoutMs,
26
+ profile: req.profile,
27
+ preferredProfile: req.preferredProfile,
28
+ authStore: req.authStore,
29
+ agentDir: req.agentDir,
30
+ cfg: req.cfg
31
+ }, options),
32
+ describeImages: async (req) => describeCodexImages(req, options),
33
+ extractStructured: async (req) => extractCodexStructured(req, options)
34
+ };
35
+ }
36
+ async function describeCodexImages(req, options) {
37
+ const model = req.model.trim();
38
+ if (!model) throw new Error("Codex image understanding requires model id.");
39
+ return {
40
+ text: await runBoundedCodexVisionTurn({
41
+ model,
42
+ profile: req.profile,
43
+ timeoutMs: req.timeoutMs,
44
+ agentDir: req.agentDir,
45
+ options,
46
+ taskLabel: "image understanding",
47
+ developerInstructions: "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.",
48
+ input: [{
49
+ type: "text",
50
+ text: buildCodexImagePrompt(req),
51
+ text_elements: []
52
+ }, ...req.images.map((image) => ({
53
+ type: "image",
54
+ url: `data:${image.mime ?? "image/png"};base64,${image.buffer.toString("base64")}`
55
+ }))],
56
+ requiredModalities: ["text", "image"]
57
+ }),
58
+ model
59
+ };
60
+ }
61
+ async function runBoundedCodexVisionTurn(params) {
62
+ const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig: params.options.pluginConfig });
63
+ const timeoutMs = Math.max(100, params.timeoutMs);
64
+ const ownsClient = !params.options.clientFactory;
65
+ const client = params.options.clientFactory ? await params.options.clientFactory(appServer.start, params.profile) : await import("./shared-client-Cnyr9dyT.js").then((n) => n.a).then(({ createIsolatedCodexAppServerClient }) => createIsolatedCodexAppServerClient({
66
+ startOptions: appServer.start,
67
+ timeoutMs,
68
+ authProfileId: params.profile
69
+ }));
70
+ const abortController = new AbortController();
71
+ const timeout = setTimeout(() => abortController.abort("timeout"), timeoutMs);
72
+ timeout.unref?.();
73
+ try {
74
+ await assertCodexModelSupportsInput({
75
+ client,
76
+ model: params.model,
77
+ requiredModalities: params.requiredModalities,
78
+ timeoutMs,
79
+ signal: abortController.signal
80
+ });
81
+ const thread = assertCodexThreadStartResponse(await client.request("thread/start", {
82
+ model: params.model,
83
+ modelProvider: "openai",
84
+ cwd: params.agentDir || process.cwd(),
85
+ approvalPolicy: "on-request",
86
+ sandbox: "read-only",
87
+ serviceName: "Klaw",
88
+ developerInstructions: params.developerInstructions,
89
+ dynamicTools: [],
90
+ experimentalRawEvents: true,
91
+ persistExtendedHistory: false,
92
+ ephemeral: true
93
+ }, {
94
+ timeoutMs,
95
+ signal: abortController.signal
96
+ }));
97
+ const collector = createCodexTurnCollector(thread.thread.id, params.taskLabel);
98
+ const cleanup = client.addNotificationHandler(collector.handleNotification);
99
+ const requestCleanup = client.addRequestHandler(denyCodexImageApprovalRequest);
100
+ try {
101
+ const turn = assertCodexTurnStartResponse(await client.request("turn/start", {
102
+ threadId: thread.thread.id,
103
+ input: params.input,
104
+ cwd: params.agentDir || process.cwd(),
105
+ approvalPolicy: "on-request",
106
+ model: params.model,
107
+ effort: "low"
108
+ }, {
109
+ timeoutMs,
110
+ signal: abortController.signal
111
+ }));
112
+ return await collector.collect(turn.turn, {
113
+ timeoutMs,
114
+ signal: abortController.signal
115
+ });
116
+ } finally {
117
+ requestCleanup();
118
+ cleanup();
119
+ }
120
+ } finally {
121
+ clearTimeout(timeout);
122
+ if (ownsClient) client.close();
123
+ }
124
+ }
125
+ async function extractCodexStructured(req, options) {
126
+ const model = req.model.trim();
127
+ if (!model) throw new Error("Codex structured extraction requires model id.");
128
+ if (!req.instructions.trim()) throw new Error("Codex structured extraction requires instructions.");
129
+ if (req.input.length === 0) throw new Error("Codex structured extraction requires at least one input.");
130
+ if (!req.input.some((entry) => entry.type === "image")) throw new Error("Codex structured extraction requires at least one image input.");
131
+ return normalizeStructuredExtractionResult({
132
+ text: await runBoundedCodexVisionTurn({
133
+ model,
134
+ profile: req.profile,
135
+ timeoutMs: req.timeoutMs,
136
+ agentDir: req.agentDir,
137
+ options,
138
+ taskLabel: "structured extraction",
139
+ developerInstructions: "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.",
140
+ input: buildCodexStructuredInput(req),
141
+ requiredModalities: requiredStructuredModalities()
142
+ }),
143
+ model,
144
+ provider: req.provider,
145
+ req
146
+ });
147
+ }
148
+ function denyCodexImageApprovalRequest(request) {
149
+ if (request.method === "item/commandExecution/requestApproval" || request.method === "item/fileChange/requestApproval") return {
150
+ decision: "decline",
151
+ reason: "Klaw Codex image understanding does not grant tool or file approvals."
152
+ };
153
+ if (request.method === "item/permissions/requestApproval") return {
154
+ permissions: {},
155
+ scope: "turn"
156
+ };
157
+ if (request.method.includes("requestApproval")) return {
158
+ decision: "decline",
159
+ reason: "Klaw Codex image understanding does not grant native approvals."
160
+ };
161
+ if (request.method === "mcpServer/elicitation/request") return { action: "decline" };
162
+ }
163
+ async function assertCodexModelSupportsInput(params) {
164
+ const match = readModelListResult(await params.client.request("model/list", {
165
+ limit: 100,
166
+ cursor: null,
167
+ includeHidden: false
168
+ }, {
169
+ timeoutMs: Math.min(params.timeoutMs, 5e3),
170
+ signal: params.signal
171
+ })).models.find((entry) => entry.model === params.model || entry.id === params.model);
172
+ if (!match) throw new Error(`Codex app-server model not found: ${params.model}`);
173
+ if (params.requiredModalities.includes("image") && !match.inputModalities.includes("image")) throw new Error(`Codex app-server model does not support images: ${params.model}`);
174
+ if (params.requiredModalities.includes("text") && !match.inputModalities.includes("text")) throw new Error(`Codex app-server model does not support text: ${params.model}`);
175
+ }
176
+ function buildCodexImagePrompt(req) {
177
+ const prompt = req.prompt?.trim() || DEFAULT_CODEX_IMAGE_PROMPT;
178
+ if (req.images.length <= 1) return prompt;
179
+ return `${prompt}\n\nAnalyze all ${req.images.length} images together.`;
180
+ }
181
+ function requiredStructuredModalities() {
182
+ return ["text", "image"];
183
+ }
184
+ function buildCodexStructuredInput(req) {
185
+ return [{
186
+ type: "text",
187
+ text: buildStructuredExtractionPrompt(req),
188
+ text_elements: []
189
+ }, ...req.input.map((entry) => {
190
+ if (entry.type === "text") return {
191
+ type: "text",
192
+ text: entry.text,
193
+ text_elements: []
194
+ };
195
+ return {
196
+ type: "image",
197
+ url: `data:${entry.mime ?? "image/png"};base64,${entry.buffer.toString("base64")}`
198
+ };
199
+ })];
200
+ }
201
+ function buildStructuredExtractionPrompt(req) {
202
+ return [
203
+ req.instructions.trim(),
204
+ req.schemaName ? `Schema name: ${req.schemaName}` : void 0,
205
+ req.jsonSchema ? `JSON schema:\n${JSON.stringify(req.jsonSchema)}` : void 0,
206
+ req.jsonMode === false ? "Return the extraction as concise text." : "Return valid JSON only. Do not wrap the JSON in Markdown fences."
207
+ ].filter((part) => Boolean(part)).join("\n\n");
208
+ }
209
+ function isJsonSchemaObject(value) {
210
+ return typeof value === "object" && value !== null && !Array.isArray(value);
211
+ }
212
+ function normalizeStructuredExtractionResult(params) {
213
+ const result = {
214
+ text: params.text,
215
+ model: params.model,
216
+ provider: params.provider,
217
+ contentType: params.req.jsonMode === false ? "text" : "json"
218
+ };
219
+ if (params.req.jsonMode !== false) {
220
+ try {
221
+ result.parsed = JSON.parse(params.text);
222
+ } catch {
223
+ throw new Error("Codex structured extraction returned invalid JSON.");
224
+ }
225
+ if (isJsonSchemaObject(params.req.jsonSchema)) {
226
+ const validation = validateJsonSchemaValue({
227
+ schema: params.req.jsonSchema,
228
+ cacheKey: "codex.media-understanding.extractStructured",
229
+ value: result.parsed,
230
+ cache: false
231
+ });
232
+ if (!validation.ok) {
233
+ const message = validation.errors.map((error) => error.text).join("; ") || "invalid";
234
+ throw new Error(`Codex structured extraction JSON did not match schema: ${message}`);
235
+ }
236
+ result.parsed = validation.value;
237
+ }
238
+ }
239
+ return result;
240
+ }
241
+ function createCodexTurnCollector(threadId, taskLabel) {
242
+ let turnId;
243
+ let completedTurn;
244
+ let promptError;
245
+ const pending = [];
246
+ const assistantTextByItem = /* @__PURE__ */ new Map();
247
+ const assistantItemOrder = [];
248
+ let resolveCompletion;
249
+ const completion = new Promise((resolve) => {
250
+ resolveCompletion = resolve;
251
+ });
252
+ const rememberAssistantText = (itemId, text) => {
253
+ if (!text) return;
254
+ if (!assistantTextByItem.has(itemId)) assistantItemOrder.push(itemId);
255
+ assistantTextByItem.set(itemId, text);
256
+ };
257
+ const handleNotification = (notification) => {
258
+ const params = isJsonObject(notification.params) ? notification.params : void 0;
259
+ if (!params || readString(params, "threadId") !== threadId) return;
260
+ if (!turnId) {
261
+ pending.push(notification);
262
+ return;
263
+ }
264
+ if (readNotificationTurnId(params) !== turnId) return;
265
+ if (notification.method === "item/agentMessage/delta") {
266
+ const itemId = readString(params, "itemId") ?? readString(params, "id") ?? "assistant";
267
+ const delta = readString(params, "delta") ?? "";
268
+ rememberAssistantText(itemId, `${assistantTextByItem.get(itemId) ?? ""}${delta}`);
269
+ return;
270
+ }
271
+ if (notification.method === "turn/completed") {
272
+ completedTurn = readCodexTurnCompletedNotification(notification.params)?.turn ?? completedTurn;
273
+ resolveCompletion?.();
274
+ return;
275
+ }
276
+ if (notification.method === "error") {
277
+ promptError = readCodexErrorNotification(notification.params)?.error.message ?? `codex app-server ${taskLabel} turn failed`;
278
+ resolveCompletion?.();
279
+ }
280
+ };
281
+ return {
282
+ handleNotification,
283
+ async collect(startedTurn, options) {
284
+ turnId = startedTurn.id;
285
+ if (isTerminalTurn(startedTurn)) completedTurn = startedTurn;
286
+ for (const notification of pending.splice(0)) handleNotification(notification);
287
+ if (!completedTurn && !promptError) await waitForTurnCompletion({
288
+ completion,
289
+ timeoutMs: options.timeoutMs,
290
+ signal: options.signal,
291
+ taskLabel
292
+ });
293
+ if (promptError) throw new Error(promptError);
294
+ if (completedTurn?.status === "failed") throw new Error(completedTurn.error?.message ?? `codex app-server ${taskLabel} turn failed`);
295
+ const itemText = collectAssistantTextFromItems(completedTurn?.items);
296
+ const deltaText = assistantItemOrder.map((itemId) => assistantTextByItem.get(itemId)?.trim()).filter((text) => Boolean(text)).join("\n\n").trim();
297
+ const text = (itemText || deltaText).trim();
298
+ if (!text) throw new Error(`Codex app-server ${taskLabel} turn returned no text.`);
299
+ return text;
300
+ }
301
+ };
302
+ }
303
+ async function waitForTurnCompletion(params) {
304
+ let timeout;
305
+ let cleanupAbort;
306
+ try {
307
+ await Promise.race([params.completion, new Promise((_, reject) => {
308
+ timeout = setTimeout(() => reject(/* @__PURE__ */ new Error(`codex app-server ${params.taskLabel} turn timed out`)), params.timeoutMs);
309
+ timeout.unref?.();
310
+ const abortListener = () => reject(/* @__PURE__ */ new Error(`codex app-server ${params.taskLabel} turn aborted`));
311
+ params.signal.addEventListener("abort", abortListener, { once: true });
312
+ cleanupAbort = () => params.signal.removeEventListener("abort", abortListener);
313
+ })]);
314
+ } finally {
315
+ if (timeout) clearTimeout(timeout);
316
+ cleanupAbort?.();
317
+ }
318
+ }
319
+ function collectAssistantTextFromItems(items) {
320
+ return (items ?? []).filter((item) => item.type === "agentMessage").map((item) => item.text.trim()).filter(Boolean).join("\n\n").trim();
321
+ }
322
+ function readNotificationTurnId(record) {
323
+ const direct = readString(record, "turnId");
324
+ if (direct) return direct;
325
+ return isJsonObject(record.turn) ? readString(record.turn, "id") : void 0;
326
+ }
327
+ function readString(record, key) {
328
+ const value = record[key];
329
+ return typeof value === "string" ? value : void 0;
330
+ }
331
+ function isTerminalTurn(turn) {
332
+ return turn.status === "completed" || turn.status === "interrupted" || turn.status === "failed";
333
+ }
334
+ //#endregion
335
+ export { buildCodexMediaUnderstandingProvider };
@@ -0,0 +1,110 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-DUslC3ob.js";
2
+ import { s as readCodexModelListResponse } from "./protocol-validators-BGBspNmF.js";
3
+ //#region extensions/codex/src/app-server/models.ts
4
+ var models_exports = /* @__PURE__ */ __exportAll({
5
+ listAllCodexAppServerModels: () => listAllCodexAppServerModels,
6
+ listCodexAppServerModels: () => listCodexAppServerModels,
7
+ readModelListResult: () => readModelListResult
8
+ });
9
+ async function listCodexAppServerModels(options = {}) {
10
+ return await withCodexAppServerModelClient(options, async ({ client, timeoutMs }) => requestModelListPage(client, {
11
+ ...options,
12
+ timeoutMs
13
+ }));
14
+ }
15
+ async function listAllCodexAppServerModels(options = {}) {
16
+ const maxPages = normalizeMaxPages(options.maxPages);
17
+ return await withCodexAppServerModelClient(options, async ({ client, timeoutMs }) => {
18
+ const models = [];
19
+ let cursor = options.cursor;
20
+ let nextCursor;
21
+ for (let page = 0; page < maxPages; page += 1) {
22
+ const result = await requestModelListPage(client, {
23
+ ...options,
24
+ timeoutMs,
25
+ cursor
26
+ });
27
+ models.push(...result.models);
28
+ nextCursor = result.nextCursor;
29
+ if (!nextCursor) return { models };
30
+ cursor = nextCursor;
31
+ }
32
+ return {
33
+ models,
34
+ nextCursor,
35
+ truncated: true
36
+ };
37
+ });
38
+ }
39
+ async function withCodexAppServerModelClient(options, run) {
40
+ const timeoutMs = options.timeoutMs ?? 2500;
41
+ const useSharedClient = options.sharedClient !== false;
42
+ const { createIsolatedCodexAppServerClient, getSharedCodexAppServerClient } = await import("./shared-client-Cnyr9dyT.js").then((n) => n.a);
43
+ const client = useSharedClient ? await getSharedCodexAppServerClient({
44
+ startOptions: options.startOptions,
45
+ timeoutMs,
46
+ authProfileId: options.authProfileId,
47
+ agentDir: options.agentDir,
48
+ config: options.config
49
+ }) : await createIsolatedCodexAppServerClient({
50
+ startOptions: options.startOptions,
51
+ timeoutMs,
52
+ authProfileId: options.authProfileId,
53
+ agentDir: options.agentDir,
54
+ config: options.config
55
+ });
56
+ try {
57
+ return await run({
58
+ client,
59
+ timeoutMs
60
+ });
61
+ } finally {
62
+ if (!useSharedClient) client.close();
63
+ }
64
+ }
65
+ async function requestModelListPage(client, options) {
66
+ return readModelListResult(await client.request("model/list", {
67
+ limit: options.limit ?? null,
68
+ cursor: options.cursor ?? null,
69
+ includeHidden: options.includeHidden ?? null
70
+ }, { timeoutMs: options.timeoutMs }));
71
+ }
72
+ function readModelListResult(value) {
73
+ const response = readCodexModelListResponse(value);
74
+ if (!response) return { models: [] };
75
+ const models = response.data.map((entry) => readCodexModel(entry)).filter((entry) => entry !== void 0);
76
+ const nextCursor = response.nextCursor ?? void 0;
77
+ return {
78
+ models,
79
+ ...nextCursor ? { nextCursor } : {}
80
+ };
81
+ }
82
+ function readCodexModel(value) {
83
+ const id = readNonEmptyString(value.id);
84
+ const model = readNonEmptyString(value.model) ?? id;
85
+ if (!id || !model) return;
86
+ return {
87
+ id,
88
+ model,
89
+ ...readNonEmptyString(value.displayName) ? { displayName: readNonEmptyString(value.displayName) } : {},
90
+ ...readNonEmptyString(value.description) ? { description: readNonEmptyString(value.description) } : {},
91
+ hidden: value.hidden,
92
+ isDefault: value.isDefault,
93
+ inputModalities: value.inputModalities,
94
+ supportedReasoningEfforts: readReasoningEfforts(value.supportedReasoningEfforts),
95
+ ...readNonEmptyString(value.defaultReasoningEffort) ? { defaultReasoningEffort: readNonEmptyString(value.defaultReasoningEffort) } : {}
96
+ };
97
+ }
98
+ function readReasoningEfforts(value) {
99
+ const efforts = value.map((entry) => readNonEmptyString(entry.reasoningEffort)).filter((entry) => entry !== void 0);
100
+ return [...new Set(efforts)];
101
+ }
102
+ function readNonEmptyString(value) {
103
+ if (typeof value !== "string") return;
104
+ return value.trim() || void 0;
105
+ }
106
+ function normalizeMaxPages(value) {
107
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 20;
108
+ }
109
+ //#endregion
110
+ export { readModelListResult as i, listCodexAppServerModels as n, models_exports as r, listAllCodexAppServerModels as t };