@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,623 +0,0 @@
1
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
- import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
3
- import {
4
- createAgentToolResultMiddlewareRunner,
5
- createCodexAppServerToolResultExtensionRunner,
6
- extractToolResultMediaArtifact,
7
- filterToolResultMediaUrls,
8
- HEARTBEAT_RESPONSE_TOOL_NAME,
9
- type EmbeddedRunAttemptParams,
10
- isToolWrappedWithBeforeToolCallHook,
11
- isMessagingTool,
12
- isMessagingToolSendAction,
13
- normalizeHeartbeatToolResponse,
14
- runAgentHarnessAfterToolCallHook,
15
- setBeforeToolCallDiagnosticsEnabled,
16
- type AnyAgentTool,
17
- type HeartbeatToolResponse,
18
- type MessagingToolSend,
19
- type MessagingToolSourceReplyPayload,
20
- wrapToolWithBeforeToolCallHook,
21
- } from "klaw/plugin-sdk/agent-harness-runtime";
22
- import { normalizeAgentId } from "klaw/plugin-sdk/routing";
23
- import type { CodexDynamicToolsLoading } from "./config.js";
24
- import { invalidInlineImageText, sanitizeInlineImageDataUrl } from "./image-payload-sanitizer.js";
25
- import {
26
- type CodexDynamicToolCallOutputContentItem,
27
- type CodexDynamicToolCallParams,
28
- type CodexDynamicToolCallResponse,
29
- type CodexDynamicToolDiagnosticTerminalType,
30
- type CodexDynamicToolSpec,
31
- type JsonValue,
32
- } from "./protocol.js";
33
-
34
- type CodexDynamicToolHookContext = {
35
- agentId?: string;
36
- config?: EmbeddedRunAttemptParams["config"];
37
- sessionId?: string;
38
- sessionKey?: string;
39
- runId?: string;
40
- channelId?: string;
41
- };
42
-
43
- type CodexToolResultHookContext = Omit<CodexDynamicToolHookContext, "config">;
44
-
45
- export type CodexDynamicToolBridge = {
46
- specs: CodexDynamicToolSpec[];
47
- handleToolCall: (
48
- params: CodexDynamicToolCallParams,
49
- options?: { signal?: AbortSignal },
50
- ) => Promise<CodexDynamicToolCallResponse>;
51
- telemetry: {
52
- didSendViaMessagingTool: boolean;
53
- messagingToolSentTexts: string[];
54
- messagingToolSentMediaUrls: string[];
55
- messagingToolSentTargets: MessagingToolSend[];
56
- messagingToolSourceReplyPayloads: MessagingToolSourceReplyPayload[];
57
- heartbeatToolResponse?: HeartbeatToolResponse;
58
- toolMediaUrls: string[];
59
- toolAudioAsVoice: boolean;
60
- successfulCronAdds?: number;
61
- };
62
- };
63
-
64
- export const CODEX_KLAW_DYNAMIC_TOOL_NAMESPACE = "klaw";
65
-
66
- // Keep Klaw session spawning searchable in Codex mode so Codex's native
67
- // spawn_agent remains the primary Codex subagent surface.
68
- const ALWAYS_DIRECT_DYNAMIC_TOOL_NAMES = new Set(["sessions_yield"]);
69
- const DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS = 16_000;
70
-
71
- export function createCodexDynamicToolBridge(params: {
72
- tools: AnyAgentTool[];
73
- signal: AbortSignal;
74
- hookContext?: CodexDynamicToolHookContext;
75
- loading?: CodexDynamicToolsLoading;
76
- directToolNames?: Iterable<string>;
77
- }): CodexDynamicToolBridge {
78
- const toolResultHookContext = toToolResultHookContext(params.hookContext);
79
- const toolResultMaxChars = resolveCodexDynamicToolResultMaxChars(params.hookContext);
80
- const tools = params.tools.map((tool) => {
81
- if (isToolWrappedWithBeforeToolCallHook(tool)) {
82
- setBeforeToolCallDiagnosticsEnabled(tool, false);
83
- return tool;
84
- }
85
- return wrapToolWithBeforeToolCallHook(tool, params.hookContext, { emitDiagnostics: false });
86
- });
87
- const toolMap = new Map(tools.map((tool) => [tool.name, tool]));
88
- const telemetry: CodexDynamicToolBridge["telemetry"] = {
89
- didSendViaMessagingTool: false,
90
- messagingToolSentTexts: [],
91
- messagingToolSentMediaUrls: [],
92
- messagingToolSentTargets: [],
93
- messagingToolSourceReplyPayloads: [],
94
- toolMediaUrls: [],
95
- toolAudioAsVoice: false,
96
- };
97
- const middlewareRunner = createAgentToolResultMiddlewareRunner({
98
- runtime: "codex",
99
- ...toolResultHookContext,
100
- });
101
- const legacyExtensionRunner =
102
- createCodexAppServerToolResultExtensionRunner(toolResultHookContext);
103
- const directToolNames = new Set([
104
- ...ALWAYS_DIRECT_DYNAMIC_TOOL_NAMES,
105
- ...(params.directToolNames ?? []),
106
- ]);
107
-
108
- return {
109
- specs: tools.map((tool) =>
110
- createCodexDynamicToolSpec({
111
- tool,
112
- loading: params.loading ?? "searchable",
113
- directToolNames,
114
- }),
115
- ),
116
- telemetry,
117
- handleToolCall: async (call, options) => {
118
- const tool = toolMap.get(call.tool);
119
- if (!tool) {
120
- return {
121
- contentItems: [{ type: "inputText", text: `Unknown Klaw tool: ${call.tool}` }],
122
- success: false,
123
- };
124
- }
125
- const args = jsonObjectToRecord(call.arguments);
126
- const startedAt = Date.now();
127
- const signal = composeAbortSignals(params.signal, options?.signal);
128
- try {
129
- const preparedArgs = tool.prepareArguments ? tool.prepareArguments(args) : args;
130
- const rawResult = await tool.execute(call.callId, preparedArgs, signal);
131
- const rawIsError = isToolResultError(rawResult);
132
- const middlewareResult = await middlewareRunner.applyToolResultMiddleware({
133
- threadId: call.threadId,
134
- turnId: call.turnId,
135
- toolCallId: call.callId,
136
- toolName: tool.name,
137
- args,
138
- isError: rawIsError,
139
- result: rawResult,
140
- });
141
- const result = await legacyExtensionRunner.applyToolResultExtensions({
142
- threadId: call.threadId,
143
- turnId: call.turnId,
144
- toolCallId: call.callId,
145
- toolName: tool.name,
146
- args,
147
- result: middlewareResult,
148
- });
149
- const resultIsError = rawIsError || isToolResultError(result);
150
- collectToolTelemetry({
151
- toolName: tool.name,
152
- args,
153
- result,
154
- mediaTrustResult: rawResult,
155
- telemetry,
156
- isError: resultIsError,
157
- });
158
- void runAgentHarnessAfterToolCallHook({
159
- toolName: tool.name,
160
- toolCallId: call.callId,
161
- runId: toolResultHookContext.runId,
162
- agentId: toolResultHookContext.agentId,
163
- sessionId: toolResultHookContext.sessionId,
164
- sessionKey: toolResultHookContext.sessionKey,
165
- channelId: toolResultHookContext.channelId,
166
- startArgs: args,
167
- result,
168
- startedAt,
169
- });
170
- return withDiagnosticTerminalType(
171
- {
172
- contentItems: convertToolContents(result.content, toolResultMaxChars),
173
- success: !resultIsError,
174
- },
175
- inferToolResultDiagnosticTerminalType(result, resultIsError),
176
- );
177
- } catch (error) {
178
- collectToolTelemetry({
179
- toolName: tool.name,
180
- args,
181
- result: undefined,
182
- telemetry,
183
- isError: true,
184
- });
185
- void runAgentHarnessAfterToolCallHook({
186
- toolName: tool.name,
187
- toolCallId: call.callId,
188
- runId: toolResultHookContext.runId,
189
- agentId: toolResultHookContext.agentId,
190
- sessionId: toolResultHookContext.sessionId,
191
- sessionKey: toolResultHookContext.sessionKey,
192
- channelId: toolResultHookContext.channelId,
193
- startArgs: args,
194
- error: error instanceof Error ? error.message : String(error),
195
- startedAt,
196
- });
197
- return withDiagnosticTerminalType(
198
- {
199
- contentItems: [
200
- {
201
- type: "inputText",
202
- text: error instanceof Error ? error.message : String(error),
203
- },
204
- ],
205
- success: false,
206
- },
207
- "error",
208
- );
209
- }
210
- },
211
- };
212
- }
213
-
214
- function createCodexDynamicToolSpec(params: {
215
- tool: AnyAgentTool;
216
- loading: CodexDynamicToolsLoading;
217
- directToolNames: ReadonlySet<string>;
218
- }): CodexDynamicToolSpec {
219
- const base = {
220
- name: params.tool.name,
221
- description: params.tool.description,
222
- inputSchema: toJsonValue(params.tool.parameters),
223
- };
224
- if (params.loading === "direct" || params.directToolNames.has(params.tool.name)) {
225
- return base;
226
- }
227
- return {
228
- ...base,
229
- namespace: CODEX_KLAW_DYNAMIC_TOOL_NAMESPACE,
230
- deferLoading: true,
231
- };
232
- }
233
-
234
- function toToolResultHookContext(
235
- ctx: CodexDynamicToolHookContext | undefined,
236
- ): CodexToolResultHookContext {
237
- const { agentId, sessionId, sessionKey, runId, channelId } = ctx ?? {};
238
- return {
239
- ...(agentId && { agentId }),
240
- ...(sessionId && { sessionId }),
241
- ...(sessionKey && { sessionKey }),
242
- ...(runId && { runId }),
243
- ...(channelId && { channelId }),
244
- };
245
- }
246
-
247
- function resolveCodexDynamicToolResultMaxChars(
248
- ctx: CodexDynamicToolHookContext | undefined,
249
- ): number {
250
- const configured = resolveAgentContextLimitValue({
251
- config: ctx?.config,
252
- agentId: ctx?.agentId,
253
- key: "toolResultMaxChars",
254
- });
255
- return configured ?? DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS;
256
- }
257
-
258
- function resolveAgentContextLimitValue(params: {
259
- config: EmbeddedRunAttemptParams["config"] | undefined;
260
- agentId?: string;
261
- key: string;
262
- }): number | undefined {
263
- const agents = readRecord(params.config?.agents);
264
- const defaults = readRecord(readRecord(agents?.defaults)?.contextLimits);
265
- const defaultValue = readPositiveInteger(defaults?.[params.key]);
266
- if (!params.agentId) {
267
- return defaultValue;
268
- }
269
- const list = agents?.list;
270
- if (!Array.isArray(list)) {
271
- return defaultValue;
272
- }
273
- const normalizedAgentId = normalizeAgentId(params.agentId);
274
- const agent = list.find((entry) => {
275
- const entryId = readRecord(entry)?.id;
276
- return typeof entryId === "string" && normalizeAgentId(entryId) === normalizedAgentId;
277
- });
278
- const agentValue = readPositiveInteger(
279
- readRecord(readRecord(agent)?.contextLimits)?.[params.key],
280
- );
281
- return agentValue ?? defaultValue;
282
- }
283
-
284
- function composeAbortSignals(...signals: Array<AbortSignal | undefined>): AbortSignal {
285
- const activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));
286
- if (activeSignals.length === 0) {
287
- return new AbortController().signal;
288
- }
289
- if (activeSignals.length === 1) {
290
- return activeSignals[0];
291
- }
292
- return AbortSignal.any(activeSignals);
293
- }
294
-
295
- function collectToolTelemetry(params: {
296
- toolName: string;
297
- args: Record<string, unknown>;
298
- result: AgentToolResult<unknown> | undefined;
299
- mediaTrustResult?: AgentToolResult<unknown>;
300
- telemetry: CodexDynamicToolBridge["telemetry"];
301
- isError: boolean;
302
- }): void {
303
- if (params.isError) {
304
- return;
305
- }
306
- if (!params.isError && params.toolName === "cron" && isCronAddAction(params.args)) {
307
- params.telemetry.successfulCronAdds = (params.telemetry.successfulCronAdds ?? 0) + 1;
308
- }
309
- if (!params.isError && params.toolName === HEARTBEAT_RESPONSE_TOOL_NAME) {
310
- const response = normalizeHeartbeatToolResponse(params.result?.details);
311
- if (response) {
312
- params.telemetry.heartbeatToolResponse = response;
313
- }
314
- }
315
- if (!params.isError && params.result) {
316
- const media = extractToolResultMediaArtifact(params.result);
317
- if (media) {
318
- const mediaUrls = filterToolResultMediaUrls(
319
- params.toolName,
320
- media.mediaUrls,
321
- params.mediaTrustResult ?? params.result,
322
- );
323
- const seen = new Set(params.telemetry.toolMediaUrls);
324
- for (const mediaUrl of mediaUrls) {
325
- if (!seen.has(mediaUrl)) {
326
- seen.add(mediaUrl);
327
- params.telemetry.toolMediaUrls.push(mediaUrl);
328
- }
329
- }
330
- if (media.audioAsVoice) {
331
- params.telemetry.toolAudioAsVoice = true;
332
- }
333
- }
334
- }
335
- if (
336
- !isMessagingTool(params.toolName) ||
337
- !isMessagingToolSendAction(params.toolName, params.args)
338
- ) {
339
- return;
340
- }
341
- params.telemetry.didSendViaMessagingTool = true;
342
- const sourceReplyPayload = extractInternalSourceReplyPayload(params.result?.details);
343
- if (sourceReplyPayload) {
344
- params.telemetry.messagingToolSourceReplyPayloads.push(sourceReplyPayload);
345
- return;
346
- }
347
- const text = readFirstString(params.args, ["text", "message", "body", "content"]);
348
- if (text) {
349
- params.telemetry.messagingToolSentTexts.push(text);
350
- }
351
- const mediaUrls = collectMediaUrls(params.args);
352
- params.telemetry.messagingToolSentMediaUrls.push(...mediaUrls);
353
- params.telemetry.messagingToolSentTargets.push({
354
- tool: params.toolName,
355
- provider: readFirstString(params.args, ["provider", "channel"]) ?? params.toolName,
356
- accountId: readFirstString(params.args, ["accountId", "account_id"]),
357
- to: readFirstString(params.args, ["to", "target", "recipient"]),
358
- threadId: readFirstString(params.args, ["threadId", "thread_id", "messageThreadId"]),
359
- ...(text ? { text } : {}),
360
- ...(mediaUrls.length > 0 ? { mediaUrls } : {}),
361
- });
362
- }
363
-
364
- function extractInternalSourceReplyPayload(
365
- details: unknown,
366
- ): MessagingToolSourceReplyPayload | undefined {
367
- if (!isRecord(details) || details.sourceReplySink !== "internal-ui") {
368
- return undefined;
369
- }
370
- const rawPayload = details.sourceReply;
371
- if (!isRecord(rawPayload)) {
372
- return undefined;
373
- }
374
- const text = readFirstString(rawPayload, ["text", "message"]);
375
- const mediaUrls = collectMediaUrls(rawPayload);
376
- const mediaUrl =
377
- typeof rawPayload.mediaUrl === "string" && rawPayload.mediaUrl.trim()
378
- ? rawPayload.mediaUrl.trim()
379
- : mediaUrls[0];
380
- const payload: MessagingToolSourceReplyPayload = {
381
- ...(text ? { text } : {}),
382
- ...(mediaUrl ? { mediaUrl } : {}),
383
- ...(mediaUrls.length > 0 ? { mediaUrls } : {}),
384
- ...(rawPayload.audioAsVoice === true ? { audioAsVoice: true } : {}),
385
- ...(isRecord(rawPayload.presentation)
386
- ? { presentation: rawPayload.presentation as never }
387
- : {}),
388
- ...(isRecord(rawPayload.interactive) ? { interactive: rawPayload.interactive as never } : {}),
389
- ...(isRecord(rawPayload.channelData) ? { channelData: rawPayload.channelData } : {}),
390
- ...(typeof details.idempotencyKey === "string" && details.idempotencyKey.trim()
391
- ? { idempotencyKey: details.idempotencyKey.trim() }
392
- : {}),
393
- };
394
- return text || mediaUrls.length > 0 || payload.presentation || payload.interactive
395
- ? payload
396
- : undefined;
397
- }
398
-
399
- function isRecord(value: unknown): value is Record<string, unknown> {
400
- return value !== null && typeof value === "object" && !Array.isArray(value);
401
- }
402
-
403
- function readRecord(value: unknown): Record<string, unknown> | undefined {
404
- return isRecord(value) ? value : undefined;
405
- }
406
-
407
- function readPositiveInteger(value: unknown): number | undefined {
408
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
409
- return undefined;
410
- }
411
- return Math.floor(value);
412
- }
413
-
414
- function isToolResultError(result: AgentToolResult<unknown>): boolean {
415
- const details = result.details;
416
- if (!isRecord(details)) {
417
- return false;
418
- }
419
- if (details.timedOut === true) {
420
- return true;
421
- }
422
- if (typeof details.exitCode === "number" && details.exitCode !== 0) {
423
- return true;
424
- }
425
- if (typeof details.status !== "string") {
426
- return false;
427
- }
428
- const status = details.status.trim().toLowerCase();
429
- return (
430
- status !== "" &&
431
- status !== "0" &&
432
- status !== "ok" &&
433
- status !== "success" &&
434
- status !== "completed" &&
435
- status !== "recorded" &&
436
- status !== "running"
437
- );
438
- }
439
-
440
- function inferToolResultDiagnosticTerminalType(
441
- result: AgentToolResult<unknown>,
442
- isError: boolean,
443
- ): CodexDynamicToolDiagnosticTerminalType {
444
- const details = result.details;
445
- if (isRecord(details) && typeof details.status === "string") {
446
- const status = details.status.trim().toLowerCase();
447
- if (status === "blocked") {
448
- return "blocked";
449
- }
450
- }
451
- return isError ? "error" : "completed";
452
- }
453
-
454
- function withDiagnosticTerminalType<T extends CodexDynamicToolCallResponse>(
455
- response: T,
456
- terminalType: CodexDynamicToolDiagnosticTerminalType,
457
- ): T {
458
- Object.defineProperty(response, "diagnosticTerminalType", {
459
- configurable: true,
460
- enumerable: false,
461
- value: terminalType,
462
- });
463
- return response;
464
- }
465
-
466
- function normalizeToolResultMaxChars(maxChars: number): number {
467
- return typeof maxChars === "number" && Number.isFinite(maxChars) && maxChars > 0
468
- ? Math.floor(maxChars)
469
- : DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS;
470
- }
471
-
472
- function convertToolContents(
473
- content: Array<TextContent | ImageContent>,
474
- toolResultMaxChars = DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS,
475
- ): CodexDynamicToolCallOutputContentItem[] {
476
- const maxChars = normalizeToolResultMaxChars(toolResultMaxChars);
477
- const totalTextChars = content.reduce(
478
- (total, item) => total + (item.type === "text" ? item.text.length : 0),
479
- 0,
480
- );
481
- if (totalTextChars <= maxChars) {
482
- return content.flatMap(convertToolContent);
483
- }
484
-
485
- const noticeText = `...(Klaw truncated dynamic tool result: original ${totalTextChars} chars, showing ${maxChars}; rerun with narrower args.)`;
486
- const notice = `\n${noticeText}`;
487
- const textBudget = Math.max(0, maxChars - notice.length);
488
- let remainingTextBudget = textBudget;
489
- let appendedNotice = false;
490
- const output: CodexDynamicToolCallOutputContentItem[] = [];
491
-
492
- for (const item of content) {
493
- if (item.type !== "text") {
494
- output.push(...convertToolContent(item));
495
- continue;
496
- }
497
- if (appendedNotice) {
498
- continue;
499
- }
500
- if (notice.length >= maxChars) {
501
- output.push({ type: "inputText", text: noticeText.slice(0, maxChars) });
502
- appendedNotice = true;
503
- continue;
504
- }
505
- const sliceLength = Math.min(item.text.length, remainingTextBudget);
506
- remainingTextBudget -= sliceLength;
507
- const shouldAppendNotice = remainingTextBudget <= 0;
508
- const text = item.text.slice(0, sliceLength);
509
- if (shouldAppendNotice) {
510
- output.push({ type: "inputText", text: `${text.trimEnd()}${notice}`.slice(0, maxChars) });
511
- appendedNotice = true;
512
- } else if (text.length > 0) {
513
- output.push({ type: "inputText", text });
514
- }
515
- }
516
-
517
- if (!appendedNotice) {
518
- output.push({ type: "inputText", text: noticeText.slice(0, maxChars) });
519
- }
520
- return output;
521
- }
522
-
523
- function convertToolContent(
524
- content: TextContent | ImageContent,
525
- ): CodexDynamicToolCallOutputContentItem[] {
526
- if (content.type === "text") {
527
- return [{ type: "inputText", text: content.text }];
528
- }
529
- const imageUrl = sanitizeInlineImageDataUrl(`data:${content.mimeType};base64,${content.data}`);
530
- if (!imageUrl) {
531
- return [{ type: "inputText", text: invalidInlineImageText("codex dynamic tool") }];
532
- }
533
- return [
534
- {
535
- type: "inputImage",
536
- imageUrl,
537
- },
538
- ];
539
- }
540
-
541
- function toJsonValue(value: unknown): JsonValue {
542
- try {
543
- const text = JSON.stringify(value);
544
- if (!text) {
545
- return {};
546
- }
547
- return JSON.parse(text) as JsonValue;
548
- } catch {
549
- return {};
550
- }
551
- }
552
-
553
- function jsonObjectToRecord(value: JsonValue | undefined): Record<string, unknown> {
554
- if (!value || typeof value !== "object" || Array.isArray(value)) {
555
- return {};
556
- }
557
- return value as Record<string, unknown>;
558
- }
559
-
560
- function readFirstString(record: Record<string, unknown>, keys: string[]): string | undefined {
561
- for (const key of keys) {
562
- const value = record[key];
563
- if (typeof value === "string" && value.trim()) {
564
- return value.trim();
565
- }
566
- if (typeof value === "number" && Number.isFinite(value)) {
567
- return String(value);
568
- }
569
- }
570
- return undefined;
571
- }
572
-
573
- function collectMediaUrls(record: Record<string, unknown>): string[] {
574
- const urls: string[] = [];
575
- const pushMediaUrl = (value: unknown) => {
576
- if (typeof value === "string" && value.trim()) {
577
- urls.push(value.trim());
578
- }
579
- };
580
- const pushAttachment = (value: unknown) => {
581
- if (!value || typeof value !== "object" || Array.isArray(value)) {
582
- return;
583
- }
584
- const attachment = value as Record<string, unknown>;
585
- for (const key of ["media", "mediaUrl", "path", "filePath", "fileUrl", "url"]) {
586
- pushMediaUrl(attachment[key]);
587
- }
588
- };
589
- for (const key of [
590
- "media",
591
- "mediaUrl",
592
- "media_url",
593
- "path",
594
- "filePath",
595
- "fileUrl",
596
- "imageUrl",
597
- "image_url",
598
- ]) {
599
- const value = record[key];
600
- pushMediaUrl(value);
601
- }
602
- for (const key of ["mediaUrls", "media_urls", "imageUrls", "image_urls"]) {
603
- const value = record[key];
604
- if (!Array.isArray(value)) {
605
- continue;
606
- }
607
- for (const entry of value) {
608
- pushMediaUrl(entry);
609
- }
610
- }
611
- const attachments = record.attachments;
612
- if (Array.isArray(attachments)) {
613
- for (const attachment of attachments) {
614
- pushAttachment(attachment);
615
- }
616
- }
617
- return urls;
618
- }
619
-
620
- function isCronAddAction(args: Record<string, unknown>): boolean {
621
- const action = args.action;
622
- return typeof action === "string" && action.trim().toLowerCase() === "add";
623
- }