@gakr-gakr/codex 0.1.0

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 (86) hide show
  1. package/autobot.plugin.json +374 -0
  2. package/doctor-contract-api.ts +68 -0
  3. package/harness.ts +72 -0
  4. package/index.ts +124 -0
  5. package/media-understanding-provider.ts +521 -0
  6. package/package.json +40 -0
  7. package/prompt-overlay.ts +21 -0
  8. package/provider-catalog.ts +83 -0
  9. package/provider-discovery.ts +45 -0
  10. package/provider.ts +243 -0
  11. package/src/app-server/app-inventory-cache.ts +324 -0
  12. package/src/app-server/approval-bridge.ts +1211 -0
  13. package/src/app-server/auth-bridge.ts +614 -0
  14. package/src/app-server/capabilities.ts +27 -0
  15. package/src/app-server/client-factory.ts +24 -0
  16. package/src/app-server/client.ts +715 -0
  17. package/src/app-server/compact.ts +512 -0
  18. package/src/app-server/computer-use.ts +683 -0
  19. package/src/app-server/config.ts +1038 -0
  20. package/src/app-server/context-engine-projection.ts +403 -0
  21. package/src/app-server/dynamic-tool-diagnostics.ts +73 -0
  22. package/src/app-server/dynamic-tool-profile.ts +70 -0
  23. package/src/app-server/dynamic-tools.ts +623 -0
  24. package/src/app-server/elicitation-bridge.ts +783 -0
  25. package/src/app-server/event-projector.ts +2065 -0
  26. package/src/app-server/image-payload-sanitizer.ts +167 -0
  27. package/src/app-server/local-runtime-attribution.ts +39 -0
  28. package/src/app-server/managed-binary.ts +193 -0
  29. package/src/app-server/models.ts +172 -0
  30. package/src/app-server/native-hook-relay.ts +150 -0
  31. package/src/app-server/native-subagent-task-mirror.ts +497 -0
  32. package/src/app-server/plugin-activation.ts +283 -0
  33. package/src/app-server/plugin-app-cache-key.ts +74 -0
  34. package/src/app-server/plugin-approval-roundtrip.ts +122 -0
  35. package/src/app-server/plugin-inventory.ts +357 -0
  36. package/src/app-server/plugin-thread-config.ts +455 -0
  37. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +33 -0
  38. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +199 -0
  39. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +102 -0
  40. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +227 -0
  41. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +2630 -0
  42. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +2630 -0
  43. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +1659 -0
  44. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +1655 -0
  45. package/src/app-server/protocol-validators.ts +203 -0
  46. package/src/app-server/protocol.ts +520 -0
  47. package/src/app-server/rate-limit-cache.ts +48 -0
  48. package/src/app-server/rate-limits.ts +583 -0
  49. package/src/app-server/request.ts +73 -0
  50. package/src/app-server/run-attempt.ts +4862 -0
  51. package/src/app-server/session-binding.ts +398 -0
  52. package/src/app-server/session-history.ts +44 -0
  53. package/src/app-server/shared-client.ts +289 -0
  54. package/src/app-server/side-question.ts +1009 -0
  55. package/src/app-server/test-support.ts +48 -0
  56. package/src/app-server/thread-lifecycle.ts +959 -0
  57. package/src/app-server/timeout.ts +9 -0
  58. package/src/app-server/tool-progress-normalization.ts +77 -0
  59. package/src/app-server/trajectory.ts +368 -0
  60. package/src/app-server/transcript-mirror.ts +208 -0
  61. package/src/app-server/transport-stdio.ts +107 -0
  62. package/src/app-server/transport-websocket.ts +90 -0
  63. package/src/app-server/transport.ts +117 -0
  64. package/src/app-server/user-input-bridge.ts +316 -0
  65. package/src/app-server/version.ts +4 -0
  66. package/src/app-server/vision-tools.ts +12 -0
  67. package/src/command-account.ts +544 -0
  68. package/src/command-formatters.ts +426 -0
  69. package/src/command-handlers.ts +2021 -0
  70. package/src/command-plugins-management.ts +137 -0
  71. package/src/command-rpc.ts +142 -0
  72. package/src/commands.ts +65 -0
  73. package/src/conversation-binding-data.ts +124 -0
  74. package/src/conversation-binding.ts +561 -0
  75. package/src/conversation-control.ts +303 -0
  76. package/src/conversation-turn-collector.ts +186 -0
  77. package/src/conversation-turn-input.ts +106 -0
  78. package/src/migration/apply.ts +501 -0
  79. package/src/migration/helpers.ts +55 -0
  80. package/src/migration/plan.ts +461 -0
  81. package/src/migration/provider.ts +41 -0
  82. package/src/migration/source.ts +643 -0
  83. package/src/migration/targets.ts +25 -0
  84. package/src/node-cli-sessions.ts +711 -0
  85. package/test-api.ts +95 -0
  86. package/tsconfig.json +16 -0
@@ -0,0 +1,623 @@
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 "autobot/plugin-sdk/agent-harness-runtime";
22
+ import { normalizeAgentId } from "autobot/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_AUTOBOT_DYNAMIC_TOOL_NAMESPACE = "autobot";
65
+
66
+ // Keep AutoBot 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 AutoBot 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_AUTOBOT_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 = `...(AutoBot 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
+ }